package controllers

import (
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/models/response"
)

type ChartPermissionController struct {
	BaseAuthController
}

// List
// @Title 系统品种列表
// @Description 系统品种列表
// @Param   UserId   query   int  true       "角色ID"
// @Success 200 {object} models.LoginResp
// @router /list [get]
func (this *ChartPermissionController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	userId, _ := this.GetInt("UserId")

	items, err := models.GetChartPermissionList()

	if err != nil {
		br.Msg = "权限列表获取失败"
		br.ErrMsg = "权限列表获取失败，系统错误，Err:" + err.Error()
		return
	}
	root := &PermissionNode{
		ID:       0,
		ParentID: 0,
	}
	assemblePermissionNode(items, root, 0, 2)
	resp := new(response.ChartPermissionListresp)
	if userId > 0 {
		ids, err := models.GetChartPermissionIdByUserId(userId)
		if err != nil {
			br.Msg = "权限列表获取失败"
			br.ErrMsg = "权限列表获取失败，系统错误，Err:" + err.Error()
		}
		resp.SelectedList = ids
	}
	resp.List = root.Children
	br.Ret = 200
	br.Data = resp
	br.Msg = "列表获取成功"
	br.Success = true
}

type PermissionNode struct {
	ID       int               `json:"id"`
	Name     string            `json:"name"`
	ParentID int               `json:"parentId"`
	Children []*PermissionNode `json:"children,omitempty"`
}

func assemblePermissionNode(list []*models.ChartPermission, node *PermissionNode, current int, level int) {
	if node != nil && current < level {
		for _, permission := range list {
			if permission.ParentId == node.ID {

				childNode := &PermissionNode{
					ID:       permission.ChartPermissionId,
					Name:     permission.PermissionName,
					ParentID: permission.ParentId,
				}
				node.Children = append(node.Children, childNode)
				assemblePermissionNode(list, childNode, current+1, level)
			}
		}
	}
}
