package common

import (
	"encoding/json"
	"fmt"
	"mtp2_if/global/app"
	"mtp2_if/global/e"
	"mtp2_if/logger"
	"mtp2_if/models"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

// ClientMenu 客户端菜单
type ClientMenu struct {
	Code     string       `json:"code"`     // ID
	Title    string       `json:"title"`    // 标题
	Sort     int          `json:"sort"`     // 排序
	Type     int          `json:"type"`     // 类型，1：菜单 2：按钮
	RuleKey  string       `json:"rulekey"`  // 对应权限主键，对应FUNCMENULIST表RESOURCECODE
	IsShow   bool         `json:"isshow"`   // 是否显示
	Children []ClientMenu `json:"children"` // 子菜单列表
}

// GetClientMenusReq 获取PC交易端菜单请求参数
type GetClientMenusReq struct {
	LoginID    int `form:"loginID"`
	ClientType int `form:"clientType"`
}

// GetClientMenus 获取交易端菜单
// @Summary 获取交易端菜单
// @Produce json
// @Security ApiKeyAuth
// @Param loginID query int true "登录账号"
// @Param clientType query int false "终端类型，0：PC 1：Mobile"
// @Success 200 {array} ClientMenu
// @Failure 500 {object} app.Response
// @Router /Common/GetClientMenus [get]
// @Tags 通用服务
func GetClientMenus(c *gin.Context) {
	appG := app.Gin{C: c}

	// 获取请求参数
	var req GetClientMenusReq
	if err := c.ShouldBind(&req); err != nil {
		logger.GetLogger().Errorf("GetClientMenus parse query req: %v", err)
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	// 获取菜单数据
	jsonFile := "pc_menu.json"
	if req.ClientType == 1 {
		// Mobile
		jsonFile = "mobile_menu.json"
	}

	// 读取json文件
	filePtr, err := os.Open(fmt.Sprintf("config/%s", jsonFile))
	if err != nil {
		// 读取文件失败
		logger.GetLogger().Errorf("GetClientMenus failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_CFG_FILE_FAIL, nil)
		return
	}
	defer filePtr.Close()

	var datas []interface{}
	// 创建Json编码器
	decoder := json.NewDecoder(filePtr)
	if err = decoder.Decode(&datas); err != nil {
		// Json解码失败
		logger.GetLogger().Errorf("GetClientMenus failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_CFG_JSON_FAIL, nil)
		return
	}

	rst := createMenu(datas, req.LoginID)

	// 查询成功
	logger.GetLogger().Debugln("GetPCMenus successed: %v", rst)
	appG.Response(http.StatusOK, e.SUCCESS, rst)
}

// createMenu 创建菜单数据
func createMenu(datas []interface{}, loginID int) []ClientMenu {
	clientMenus := make([]ClientMenu, 0)
	for _, v := range datas {
		data := v.(map[string]interface{})
		if data["isshow"].(bool) {
			rulekey := data["rulekey"].(string)
			if len(rulekey) != 0 {
				// 判断是否有权限
				funcMenuList, err := models.GetErmcpRoleFuncMenuLists(loginID, rulekey)
				if err != nil {
					continue
				}
				if len(funcMenuList) == 0 {
					continue
				}
			}

			clientMenus = append(clientMenus, ClientMenu{
				Code:     data["code"].(string),
				Title:    data["title"].(string),
				Sort:     int(data["sort"].(float64)),
				Type:     int(data["type"].(float64)),
				RuleKey:  data["rulekey"].(string),
				IsShow:   data["isshow"].(bool),
				Children: createMenu(data["children"].([]interface{}), loginID), // TODO: - 这里为什么可以这样转？
			})
		}
	}

	return clientMenus
}
