package db

import (
	"applet/app/db/model"
	"applet/app/md"
	"applet/app/utils/cache"
	"applet/app/utils/logx"
	"fmt"
	"xorm.io/xorm"
)

// 系统配置get
func SysCfgGetAll(Db *xorm.Engine) (*[]model.SysCfg, error) {
	var cfgList []model.SysCfg
	if err := Db.Cols("key,val,memo").Find(&cfgList); err != nil {
		return nil, logx.Error(err)
	}
	return &cfgList, nil
}

// 获取一条记录
func SysCfgGetOne(Db *xorm.Engine, key string) (*model.SysCfg, error) {
	var cfgList model.SysCfg
	if has, err := Db.Where("`key`=?", key).Get(&cfgList); err != nil || has == false {
		return nil, logx.Error(err)
	}
	return &cfgList, nil
}
func SysCfgGetOneData(Db *xorm.Engine, key string) string {
	var cfgList model.SysCfg
	if has, err := Db.Where("`key`=?", key).Get(&cfgList); err != nil || has == false {
		return ""
	}
	return cfgList.Val
}

// 返回最后插入id
func SysCfgInsert(Db *xorm.Engine, key, val, memo string) bool {
	cfg := model.SysCfg{Key: key, Val: val, Memo: memo}
	_, err := Db.InsertOne(&cfg)
	if err != nil {
		logx.Error(err)
		return false
	}
	return true
}

func SysCfgUpdate(Db *xorm.Engine, key, val, memo string) bool {
	cfg := model.SysCfg{Key: key, Val: val, Memo: memo}
	_, err := Db.Where("`key`=?", key).Cols("val,memo").Update(&cfg)
	if err != nil {
		logx.Error(err)
		return false
	}
	return true
}

// 单条记录获取DB
func SysCfgGetWithDb(eg *xorm.Engine, masterId string, HKey string) string {
	cacheKey := fmt.Sprintf(md.AppCfgCacheKey, masterId) + HKey
	get, err := cache.GetString(cacheKey)
	if err != nil || get == "" {
		cfg, err := SysCfgGetOne(eg, HKey)
		if err != nil || cfg == nil {
			_ = logx.Error(err)
			return ""
		}

		// key是否存在
		cacheKeyExist := false
		if cache.Exists(cacheKey) {
			cacheKeyExist = true
		}

		// 设置缓存
		_, err = cache.SetEx(cacheKey, cfg.Val, 30)
		if err != nil {
			_ = logx.Error(err)
			return ""
		}
		if !cacheKeyExist { // 如果是首次设置 设置过期时间
			_, err := cache.Expire(cacheKey, md.CfgCacheTime)
			if err != nil {
				_ = logx.Error(err)
				return ""
			}
		}
		return cfg.Val
	}
	return get
}
func SysCfgGetWithStr(eg *xorm.Engine, masterId string, HKey string) string {

	cfg, err := SysCfgGetOne(eg, HKey)
	if err != nil || cfg == nil {
		_ = logx.Error(err)
		return ""
	}
	return cfg.Val
}

// 多条记录获取DB
func SysCfgFindWithDb(eg *xorm.Engine, masterId string, keys ...string) map[string]string {
	res := map[string]string{}
	//TODO::判断keys长度(大于10个直接查数据库)
	if len(keys) > 10 {
		cfgList, _ := SysCfgGetAll(eg)
		if cfgList == nil {
			return nil
		}
		for _, v := range *cfgList {
			res[v.Key] = v.Val
		}
	} else {
		for _, key := range keys {
			res[key] = SysCfgGetWithDb(eg, masterId, key)
		}
	}
	return res
}
