package controllers

import (
	"eta/eta_mobile/models"
	"eta/eta_mobile/services"
	"eta/eta_mobile/utils"
)

// 分类
type ClassifyController struct {
	BaseAuthController
}

// @Title 获取分类列表
// @Description 获取分类列表
// @Param   KeyWord   query   string  true       "检索关键词"
// @Param   CompanyType   query   string  false       "产品类型，枚举值：'ficc','权益';不传默认返回全部"
// @Param   HideDayWeek   query   int  false       "是否隐藏晨周报"
// @Success 200 {object} models.Classify
// @router /list [get]
func (this *ClassifyController) ListClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	keyWord := this.GetString("KeyWord")
	reqEnabled, _ := this.GetInt("Enabled", -1)

	enabled := -1
	if reqEnabled == 1 {
		enabled = reqEnabled
	}

	list, err := models.GetClassifyListByKeyword(keyWord, enabled)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	if keyWord != `` {
		idMap := make(map[int]bool)

		currParentClassifyIdList := make([]int, 0)
		for _, v := range list {
			idMap[v.Id] = true
			if v.ParentId > 0 {
				currParentClassifyIdList = append(currParentClassifyIdList, v.ParentId)
			}
		}

		findList := list
		list = make([]*models.ClassifyList, 0)

		tmpList, tmpErr := services.GetParentClassifyListByParentIdList(currParentClassifyIdList)
		if tmpErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取上级分类信息失败，Err:" + tmpErr.Error()
			return
		}
		for _, v := range tmpList {
			if _, ok := idMap[v.Id]; !ok {
				list = append(list, v)
			}
		}

		list = append(list, findList...)
	}

	classifyIdList := make([]int, 0)
	for i := range list {
		classifyIdList = append(classifyIdList, list[i].Id)
	}
	parentIdLen := len(classifyIdList)
	if parentIdLen == 0 {
		resp := &models.ClassifyListResp{
			List: list,
		}
		br.Data = resp
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	// 获取子目录列表
	menuListMap := make(map[int][]*models.ClassifyMenu, 0)
	var menuCond string
	var menuPars []interface{}
	menuCond += ` AND classify_id IN (` + utils.GetOrmInReplace(parentIdLen) + `)`
	menuPars = append(menuPars, classifyIdList)
	parentMenus, e := models.GetClassifyMenuList(menuCond, menuPars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取一级分类子目录列表失败"
		return
	}
	for i := range parentMenus {
		if menuListMap[parentMenus[i].ClassifyId] == nil {
			menuListMap[parentMenus[i].ClassifyId] = make([]*models.ClassifyMenu, 0)
		}
		menuListMap[parentMenus[i].ClassifyId] = append(menuListMap[parentMenus[i].ClassifyId], parentMenus[i])
	}

	// 分类与子目录关联
	relateMap := make(map[int]int, 0)
	{
		var relateCond string
		var relatePars []interface{}
		relateCond += ` AND classify_id IN (` + utils.GetOrmInReplace(parentIdLen) + `)`
		relatePars = append(relatePars, classifyIdList)
		relates, e := models.GetClassifyMenuRelationList(relateCond, relatePars)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取二级分类子目录关联失败, Err: " + e.Error()
			return
		}
		for i := range relates {
			relateMap[relates[i].ClassifyId] = relates[i].MenuId
		}
	}

	// 查询分类绑定的权限
	permissionList, _ := models.GetAllPermissionMapping()
	classifyPermissionMap := make(map[int][]int)
	if len(permissionList) > 0 {
		for _, v := range permissionList {
			classifyPermissionMap[v.ClassifyId] = append(classifyPermissionMap[v.ClassifyId], v.ChartPermissionId)
		}
	}
	// 遍历分类并绑定子目录和权限
	for i, v := range list {
		list[i].ClassifyMenuList = menuListMap[v.Id]

		list[i].ClassifyMenuId = relateMap[v.Id]
		if permissionIds, ok := classifyPermissionMap[v.Id]; ok {
			list[i].ChartPermissionIdList = permissionIds
		}
	}

	// 先将分类列表排序
	services.SortClassifyListBySortAndCreateTime(list)
	// 接着转换结构
	list = services.GetClassifyListTreeRecursive(list, 0)

	resp := new(models.ClassifyListResp)
	resp.List = list
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// ClassifyPermission
// @Title 获取分类权限列表
// @Description 获取分类权限列表
// @Param   ClassifyId   query   int  true       "分类id"
// @Success 200 {object} []models.ChartPermissionSearchKeyWordMapping
// @router /permission_list [get]
func (this *ClassifyController) ClassifyPermission() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	classifyId, _ := this.GetInt("ClassifyId")
	if classifyId <= 0 {
		br.Msg = "参数错误"
		return
	}

	//获取报告分类详情
	classifyInfo, err := models.GetClassifyById(classifyId)
	if err != nil {
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	//获取报告分类权限列表
	list, err := models.GetPermissionByClassifyId(classifyInfo.Id)
	if err != nil {
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	br.Data = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}
