package controllers

import (
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/system"
	"eta/eta_mobile/utils"
	"strconv"
	"strings"
)

type SysMenuController struct {
	BaseAuthController
}

// @Title 获取用户权限菜单
// @Description 获取用户权限菜单接口
// @Success 200 {object} system.MenuListResp
// @router /menu/list [get]
func (this *SysMenuController) 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)
		}
	}
	groupId := 0
	if utils.RunMode == "release" {
		groupId = 37
	} else {
		groupId = 61
	}
	//共享客户组下的用户
	shareSellerMap := make(map[int]bool, 0)
	subAdmins, err := system.GetAdminByGroupId(groupId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取销售失败"
		br.ErrMsg = "获取销售失败,Err:" + err.Error()
		return
	}
	for _, admin := range subAdmins {
		shareSellerMap[admin.AdminId] = true
	}

	list, err := system.GetMenuListByRoleIds(roleIds)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	lenList := len(list)
	for i := 0; i < lenList; i++ {
		item := list[i]
		child, err := system.GetMenuByParentIdRoleIds(roleIds, item.MenuId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取子菜单数据失败，Err:" + err.Error()
			return
		}
		lenChild := len(child)
		for ci := 0; ci < lenChild; ci++ {
			if child[ci].Name == "领取列表" {
				if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER {
					child[ci].Name = "权益客户"
				} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
					child[ci].Name = "ficc客户"
				}
			}
		}
		for i, menu := range child {
			if menu.Name == "正式客户共享" && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN &&
				sysUser.AdminId != 66 && sysUser.AdminId != 15 {
				//如果不是admin角色、共享客户分组下用户、楼颖丹账号、王沛账号 就不显示该页面
				if ok, _ := shareSellerMap[sysUser.AdminId]; !ok {
					child = append(child[:i], child[i+1:]...)
				}
			}
		}

		if strings.Contains(item.Name, "出差管理") && sysUser.AdminId == 66 {
			cm := new(system.ChildMenu)
			cm.MenuId = 10000
			cm.Name = "出差审批"
			cm.Path = "businessTripApproval"
			cm.Component = "businessTripApproval"
			cm.IconPath = ""
			cm.Hidden = false
			child = append(child, cm)
		}
		//if lenChild > 1 {
		//	list[i].IsLevel = 2
		//} else {
		//	list[i].IsLevel = 1
		//	list[i].LevelPath = ""
		//}
		list[i].Children = child
	}
	resp := new(system.MenuListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
