package dao

import (
	"fmt"
	"git.rosy.net.cn/baseapi/utils/errlist"
	"time"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
)

func QueryConfigs(db *DaoDB, key, configType, keyword string) (configList []*model.NewConfig, err error) {
	sql := `
	SELECT
	t1.*
	FROM new_config t1
	WHERE t1.deleted_at = ?`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if key != "" {
		sql += " AND t1.key = ?"
		sqlParams = append(sqlParams, key)
	}
	if configType != "" {
		sql += " AND t1.type = ?"
		sqlParams = append(sqlParams, configType)
	}
	if keyword != "" {
		keywordLike := "%" + keyword + "%"
		sql += " AND (t1.type LIKE ? OR t1.key LIKE ? OR value LIKE ?)"
		sqlParams = append(sqlParams, keywordLike, keywordLike, keywordLike)
	}

	err = GetRows(db, &configList, sql, sqlParams...)
	if err == nil && len(configList) == 0 && key != "" {
		fmt.Println("条件:key:,type:,keyword:不能找到配置", key, configType, keyword)
		err = fmt.Errorf("条件:key:%s,type:%s,keyword:%s不能找到配置", key, configType, keyword)
	}
	return configList, err
}

func ValidateRoles(db *DaoDB, roles ...string) (err error) {
	errList := errlist.New()
	for _, v := range roles {
		if v != "" {
			_, err2 := QueryConfigs(db, v, model.ConfigTypeRole, "")
			errList.AddErr(err2)
		}
	}
	return errList.GetErrListAsOne()
}

func GetSysConfigAsInt64(db *DaoDB, key string) (value int64, err error) {
	configList, err := QueryConfigs(db, key, model.ConfigTypeSys, "")
	if err == nil && len(configList) > 0 {
		value = utils.Str2Int64WithDefault(configList[0].Value, 0)
	} else if true { //IsNoRowsError(err) { // todo 暂时忽略所有错误
		err = nil
	}
	return value, err
}

// 修改配置
func UpdateOperatorConfig(param string, types, key string) error {
	sql := `UPDATE new_config c SET c.value = ?,c.updated_at = ? WHERE c.type = ? AND c.key = ?`
	_, err := ExecuteSQL(GetDB(), sql, []interface{}{param, time.Now(), types, key})
	return err
}
