package models

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// RiskConfig 表示风险配置表
type RiskConfig struct {
	Id          int          `description:"primaryKey;autoIncrement"`
	RiskName    string       `description:"size:10"`                                 // 风险名称
	RiskType    RiskTypeEnum `description:"type:enum('customer','product')"`         // 风险类型
	CreatedTime time.Time    `description:"default:null"`                            // 创建时间
	UpdatedTime time.Time    `description:"default:null;onUpdate:CURRENT_TIMESTAMP"` // 更新时间
}
type RiskConfigView struct {
	Id       int
	RiskName string
	RiskType string
}

// RiskTypeEnum 定义风险类型的枚举
type RiskTypeEnum string

const (
	Customer RiskTypeEnum = "customer"
	Product  RiskTypeEnum = "product"
)

func GetCustomerRiskList() (list []*RiskConfig, err error) {
	o := orm.NewOrm()
	sql := "select id, risk_name,risk_type  from risk_config where risk_type= ? ORDER BY CAST(substr(risk_name,  2) AS UNSIGNED)"
	_, err = o.Raw(sql, Customer).QueryRows(&list)
	return
}
func GetCustomerRisk(riskName string) (risk *RiskConfig, err error) {
	o := orm.NewOrm()
	sql := "select id, risk_name,risk_type  from risk_config where risk_type= ? and risk_name=?"
	err = o.Raw(sql, Customer, riskName).QueryRow(&risk)
	return
}
func (r *RiskConfig) ToView() *RiskConfigView {
	return &RiskConfigView{
		Id:       r.Id,
		RiskName: r.RiskName,
		RiskType: string(r.RiskType),
	}
}
func GetProductRiskList() (list []*RiskConfig, err error) {
	o := orm.NewOrm()
	sql := "select id, risk_name,risk_type from risk_config where risk_type= ? ORDER BY CAST(substr(risk_name,  2) AS UNSIGNED)"
	_, err = o.Raw(sql, Product).QueryRows(&list)
	return
}

func InsertProductRiskLevel(riskName string) (err error) {
	var riskConfig RiskConfig
	o := orm.NewOrm()
	sql := "select * from  risk_config where risk_name =? and risk_type=?"
	err = o.Raw(sql, riskName, Product).QueryRow(&riskConfig)
	if err != nil && err != orm.ErrNoRows {
		return
	}
	if err == orm.ErrNoRows || riskConfig.Id == 0 {
		riskConfig.RiskType = Product
		riskConfig.RiskName = riskName
		_, err = o.Insert(&riskConfig)
	}
	return
}
