package controllers

import (
	"encoding/json"
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/models/request"
	"eta/eta_mini_crm_ht/models/response"
	"regexp"
)

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()
	}()
	items, err := models.GetPermissionList()
	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)
	resp.List = root.Children
	br.Ret = 200
	br.Data = resp
	br.Msg = "列表获取成功"
	br.Success = true
}

func checkRiskLevel(riskLevel string) bool {
	pattern := `^R\d+$`
	matched, _ := regexp.MatchString(pattern, riskLevel)
	return matched
}

// SetRiskLevel
// @Title 系统品种列表
// @Description 系统品种列表
// @Param   UserId   query   int  true       "角色ID"
// @Success 200 {object} models.LoginResp
// @router /setRiskLevel [post]
func (this *ChartPermissionController) SetRiskLevel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.PermissionRiskReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "请求参数错误"
		br.ErrMsg = "解析请求参数异常，Err:" + err.Error()
		return
	}
	if req.Id <= 0 {
		br.Msg = "品种ID非法"
		br.ErrMsg = "品种ID不能为负数"
		return
	}
	if req.RiskLevel == "" {
		br.Msg = "风控等级为空"
		br.ErrMsg = "风控等级为空"
		return
	}
	if !checkRiskLevel(req.RiskLevel) {
		br.Msg = "风控等级包含非法字符"
		br.ErrMsg = "风控等级非法:" + req.RiskLevel
		return
	}
	item, err := models.GetPermissionByPermissionId(req.Id)
	if err != nil {
		br.Msg = "获取品种信息失败"
		br.ErrMsg = "获取品种信息失败，系统错误，Err:" + err.Error()
		return
	}
	if item.ParentId == 0 {
		br.Msg = "当前品种为一级品种,不能设置风险等级"
		br.ErrMsg = "当前品种为一级品种,不能设置风险等级"
		return
	}
	item.RiskLevel = req.RiskLevel
	err = models.InsertProductRiskLevel(req.RiskLevel)
	if err != nil {
		br.Msg = "保存自定义风险等级失败"
		br.ErrMsg = "保存自定义风险等级失败，Err:" + err.Error()
		return
	}
	err = item.SetPermissionRiskLevel()
	if err != nil {
		br.Msg = "设置风险等级失败"
		br.ErrMsg = "设置风险等级失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "设置风险等级成功"
	br.Success = true
}

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

func assemblePermissionNode(list []*models.Permission, node *PermissionNode, current int, level int) {
	if node != nil && current < level {
		for _, permission := range list {
			if permission.ParentId == node.ID {
				childNode := &PermissionNode{
					ID:        permission.PermissionId,
					Name:      permission.Name,
					RiskLevel: permission.RiskLevel,
					ParentID:  permission.ParentId,
				}
				node.Children = append(node.Children, childNode)
				assemblePermissionNode(list, childNode, current+1, level)
			}
		}
	}
}
