package models

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

type CustomerProductRiskMappingView struct {
	Id           int
	CustomerRisk string
	ProductRisk  string
	Creator      string
	UpdatedTime  string
}

func (cp *CustomerProductRiskMapping) ToView() *CustomerProductRiskMappingView {
	return &CustomerProductRiskMappingView{
		Id:           cp.Id,
		CustomerRisk: cp.CustomerRisk,
		ProductRisk:  cp.ProductRisk,
		Creator:      cp.Creator,
		UpdatedTime:  cp.UpdatedTime.Format(time.DateTime),
	}
}

type CustomerProductRiskMapping struct {
	Id           int       `description:"primaryKey;autoIncrement"`
	CustomerRisk string    `description:"size:10"`                                 // 客户风险
	ProductRisk  string    `description:"size:10"`                                 // 产品风险
	Creator      string    `description:"size:10"`                                 //创建人
	Modifier     string    `description:"size:10"`                                 //修改人
	IsDeleted    bool      `description:"default:0"`                               // 是否删除
	CreatedTime  time.Time `description:"default:null"`                            // 创建时间
	UpdatedTime  time.Time `description:"default:null;onUpdate:CURRENT_TIMESTAMP"` // 更新时间
}

func GetMappingList(sort string) (list []*CustomerProductRiskMapping, err error) {
	o := orm.NewOrm()
	sql := "select id, customer_risk,product_risk,creator,updated_time  from customer_product_risk_mapping where is_deleted= ? ORDER BY updated_time " + sort
	_, err = o.Raw(sql, false).QueryRows(&list)
	return
}

func CheckCustomerRisk(customerRisk string) (exist bool, err error) {
	var mapping *CustomerProductRiskMapping
	o := orm.NewOrm()
	sql := "select id, customer_risk,product_risk,creator  from customer_product_risk_mapping where customer_risk=? and is_deleted= ?   "
	err = o.Raw(sql, customerRisk, false).QueryRow(&mapping)
	if err != nil && !errors.Is(err, orm.ErrNoRows) {
		return
	}
	if errors.Is(err, orm.ErrNoRows) || mapping.Id == 0 {
		exist = false
		err = nil
		return
	}
	exist = true
	return
}
func (cp *CustomerProductRiskMapping) Insert() (err error) {
	cp.CreatedTime = time.Now()
	cp.UpdatedTime = time.Now()
	o := orm.NewOrm()
	_, err = o.Insert(cp)
	return
}
func (cp *CustomerProductRiskMapping) Update() (err error) {
	o := orm.NewOrm()
	_, err = o.Update(cp, "product_risk", "modifier")
	return
}
func (cp *CustomerProductRiskMapping) Delete() (err error) {
	o := orm.NewOrm()
	_, err = o.Update(cp, "is_deleted", "modifier")
	return
}
func GetCustomerRiskMapping(customerRisk string) (mapping *CustomerProductRiskMapping, err error) {
	o := orm.NewOrm()
	sql := "select id, customer_risk,product_risk,creator  from customer_product_risk_mapping where customer_risk=? and  is_deleted= ? "
	err = o.Raw(sql, customerRisk, false).QueryRow(&mapping)
	return
}
