package controllers

import (
	"encoding/json"
	"errors"
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/models/request"
	"eta/eta_mini_crm_ht/models/response"
	"github.com/beego/beego/v2/client/orm"
	"regexp"
	"strings"
)

type CustomerProductRiskMappingController struct {
	BaseAuthController
}

func sortStr(sort string) string {
	if sort == "desc" {
		return "desc"
	}
	if sort == "asc" {
		return "asc"
	}
	return "desc"
}

// GetMappingList
// @Title 获取风险等级映射关系
// @Description 获取风险等级映射关系
// @Success 200 {object} models.LoginResp
// @router /mappingList [get]
func (this *CustomerProductRiskMappingController) GetMappingList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sort := this.GetString("Sort")
	sort = sortStr(sort)
	list, err := models.GetMappingList(sort)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var viewList []*models.CustomerProductRiskMappingView
	for _, item := range list {
		viewList = append(viewList, item.ToView())
	}
	resp := new(response.CustomerProductRiskMappingListResp)
	resp.List = viewList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// AddMapping
// @Title 获取产品风险等级
// @Description  获取产品风险等级
// @Success 200 {object} models.LoginResp
// @router /addMapping [post]
func (this *CustomerProductRiskMappingController) AddMapping() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.CustomerProductRiskMappingListReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "请求参数错误"
		br.ErrMsg = "解析请求参数异常，Err:" + err.Error()
		return
	}
	if req.CustomerRisk == "" {
		br.Msg = "客户风险等级为空"
		br.ErrMsg = "客户风险等级为空"
		return
	}
	if req.ProductRisk == "" {
		br.Msg = "产品风险等级为空"
		br.ErrMsg = "产品风险等级为空"
		return
	}
	exist, err := models.CheckCustomerRisk(req.CustomerRisk)
	if err != nil {
		br.Msg = "查询客户产品风险等级规则失败"
		br.ErrMsg = "查询客户产品风险等级规则失败：" + err.Error()
		return
	}
	if !checkCustomerRiskLevel(req.CustomerRisk) {
		br.Msg = "客户产品风险等级非法"
		br.ErrMsg = "客户产品风险等级非法：" + req.CustomerRisk
		return
	}
	pdList := strings.Split(req.ProductRisk, ",")
	for _, pd := range pdList {
		if !checkProductRiskLevel(pd) {
			br.Msg = "产品风险等级非法"
			br.ErrMsg = "产品风险等级非法：" + pd
			return
		}
	}
	if exist {
		br.Msg = "该用户风险等级已配置"
		br.ErrMsg = "该用户风险等级已配置"
		return
	}
	var mapping models.CustomerProductRiskMapping
	mapping.CustomerRisk = req.CustomerRisk
	mapping.ProductRisk = req.ProductRisk
	mapping.Creator = this.SysUser.SysRealName
	err = mapping.Insert()
	if err != nil {
		br.Msg = "新增客户风险等级规则失败"
		br.ErrMsg = "新增客户风险等级规则失败：" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// EditMapping
// @Title 获取产品风险等级
// @Description  获取产品风险等级
// @Success 200 {object} models.LoginResp
// @router /editMapping [post]
func (this *CustomerProductRiskMappingController) EditMapping() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.CustomerProductRiskMappingListReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "请求参数错误"
		br.ErrMsg = "解析请求参数异常，Err:" + err.Error()
		return
	}
	if req.CustomerRisk == "" {
		br.Msg = "客户风险等级为空"
		br.ErrMsg = "客户风险等级为空"
		return
	}
	if req.ProductRisk == "" {
		br.Msg = "产品风险等级为空"
		br.ErrMsg = "产品风险等级为空"
		return
	}
	mapping, err := models.GetCustomerRiskMapping(req.CustomerRisk)
	if err != nil {
		br.Msg = "编辑用户风险等级配置失败"
		br.ErrMsg = "编辑用户风险等级配置失败：" + err.Error()
		return
	}
	mapping.ProductRisk = req.ProductRisk
	mapping.Modifier = this.SysUser.SysRealName
	err = mapping.Update()
	if err != nil {
		br.Msg = "编辑客户风险等级规则失败"
		br.ErrMsg = "编辑客户风险等级规则失败：" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// DeleteMapping
// @Title 获取产品风险等级
// @Description  获取产品风险等级
// @Success 200 {object} models.LoginResp
// @router /deleteMapping [post]
func (this *CustomerProductRiskMappingController) DeleteMapping() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.CustomerProductRiskMappingListReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "请求参数错误"
		br.ErrMsg = "解析请求参数异常，Err:" + err.Error()
		return
	}
	if req.CustomerRisk == "" {
		br.Msg = "客户风险等级为空"
		br.ErrMsg = "客户风险等级为空"
		return
	}
	mapping, err := models.GetCustomerRiskMapping(req.CustomerRisk)
	if err != nil && errors.Is(err, orm.ErrNoRows) {
		br.Ret = 200
		br.Success = true
		br.Msg = "删除成功"
	}
	mapping.IsDeleted = true
	mapping.Modifier = this.SysUser.SysRealName
	err = mapping.Delete()
	if err != nil {
		br.Msg = "编辑客户风险等级规则失败"
		br.ErrMsg = "编辑客户风险等级规则失败：" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

func checkCustomerRiskLevel(riskLevel string) (exist bool) {
	pattern := `^C\d+$`
	matched, _ := regexp.MatchString(pattern, riskLevel)
	_, err := models.GetCustomerRisk(riskLevel)
	if err != nil {
		return false
	}
	return matched
}
func checkProductRiskLevel(riskLevel string) (exist bool) {
	pattern := `^R\d+$`
	matched, _ := regexp.MatchString(pattern, riskLevel)
	return matched
}
