package company

import (
	"encoding/json"
	"errors"
	"eta/eta_api/utils"
	"github.com/beego/beego/v2/client/orm"
)

const (
	ConfAreaCodeListKey = "area_code_list" // 手机号区号列表
	ConfEnAuthRoleKey   = "en_auth_role"   // 英文权限角色配置Key
)

type CrmConfig struct {
	ConfigValue string `description:"详情"`
}

func GetConfigValueByCode(configCode string) (total int, err error) {
	o := orm.NewOrm()
	sql := ` SELECT config_value FROM crm_config WHERE config_code=? `
	err = o.Raw(sql, configCode).QueryRow(&total)
	return
}

// 修改
func CrmConfigUpdate(newValue, configCode string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE crm_config SET  config_value=?   WHERE config_code=  ?`
	_, err = o.Raw(sql, newValue, configCode).Exec()
	return
}

func GetConfigDetailByCode(configCode string) (item CrmConfig, err error) {
	o := orm.NewOrm()
	sql := ` SELECT config_value FROM crm_config WHERE config_code=? `
	err = o.Raw(sql, configCode).QueryRow(&item)
	return
}

// ConfEnAuthRole 配置-英文权限角色
type ConfEnAuthRole struct {
	RoleCode string `description:"角色编码"`
	RoleName string `description:"角色名称"`
	SyncCrm  bool   `description:"是否同步CRM"`
}

// ConfigClassifyId
// @Description: 后台配置的报告id
type ConfigClassifyId struct {
	Debug   int `json:"debug"`
	Release int `json:"release"`
}

// GetReportClassifyIdByConfigKey
// @Description: 获取关联的报告id
// @author: Roc
// @datetime 2024-06-18 14:10:27
// @param configKey string
// @return classifyId int
// @return err error
func GetReportClassifyIdByConfigKey(configKey string) (classifyId int, err error) {
	// 别问为啥要从配置里拿=_=!
	conf, e := GetConfigDetailByCode(configKey)
	if e != nil {
		err = errors.New("获取配置的id失败, Err: " + e.Error())
		return
	}
	if conf.ConfigValue == "" {
		err = errors.New("ID配置有误")
		return
	}
	type TwoWeekIdConf struct {
		Debug   []int
		Release []int
	}
	classifyIdConf := new(ConfigClassifyId)
	if e = json.Unmarshal([]byte(conf.ConfigValue), &classifyIdConf); e != nil {
		err = errors.New("解析ID配置失败, Err: " + e.Error())
		return
	}
	if utils.RunMode == "debug" {
		classifyId = classifyIdConf.Debug
	} else {
		classifyId = classifyIdConf.Release
	}

	return
}