package controllers

import (
	"eta_gn/eta_api/models"
	"eta_gn/eta_api/models/system"
	"strconv"
)

type SysMenuController struct {
	BaseAuthController
}

// @Title 获取用户权限菜单
// @Description 获取用户权限菜单接口
// @Success 200 {object} system.MenuListResp
// @router /menu/list [get]
func (this *SysRoleController) SysMenuList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		return
	}
	roleId := sysUser.RoleId
	//roleId=1
	if roleId <= 0 {
		br.Msg = "参数错误"
		return
	}
	roleIds := strconv.Itoa(roleId)
	//查询账号绑定的其他角色
	otherRoles, err := system.GetRoleIdsByAdminId(sysUser.AdminId)
	if err != nil {
		br.Msg = "获取其他角色失败"
		br.ErrMsg = "获取其他角色失败,Err:" + err.Error()
		return
	}
	if len(otherRoles) > 0 {
		for _, v := range otherRoles {
			roleIds += "," + strconv.Itoa(v.RoleId)
		}
	}
	// 审批配置
	//confMap, e := models.GetBusinessConf()
	//if e != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取商家配置失败, Err: " + e.Error()
	//	return
	//}
	//openMap := map[string]bool{"false": false, "true": true}
	//openApprove := openMap[confMap[models.BusinessConfIsReportApprove]]

	list, err := system.GetMenuListAllByRoleIds(roleIds)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	rootList, err := system.GetMenuListByRoleIds(roleIds)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	menuMap := make(map[int][]*system.MenuList)

	for _, v := range list {
		if menus, ok := menuMap[v.ParentId]; !ok {
			menus = make([]*system.MenuList, 0)
			menus = append(menus, v)
			menuMap[v.ParentId] = menus
		} else {
			menus = append(menus, v)
			menuMap[v.ParentId] = menus
		}
	}

	//menuList := make([]*system.MenuList, 0)
	for _, firstMenus := range rootList {
		if secondMenus, ok := menuMap[firstMenus.MenuId]; ok {
			for _, sencodMenu := range secondMenus {
				if thirdMenus, ok := menuMap[sencodMenu.MenuId]; ok {
					sencodMenu.Children = thirdMenus
				} else {
					thirdMenuList := make([]*system.MenuList, 0)
					sencodMenu.Children = thirdMenuList
				}
			}

			firstMenus.Children = secondMenus
		}
	}
	resp := new(system.MenuListResp)
	resp.List = rootList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}