package cacheservice

import (
	"errors"
	"fmt"
	"go-admin/app/admin/models"
	"go-admin/common/const/rediskey"
	"go-admin/common/global"
	"go-admin/common/helper"
	models2 "go-admin/models"

	"github.com/bytedance/sonic"
	"github.com/go-admin-team/go-admin-core/logger"
	"gorm.io/gorm"
)

// 加载config缓存
func InitConfigCache(db *gorm.DB) {
	datas := []models.SysConfig{}
	db.Model(&models.SysConfig{}).Find(&datas)
	for _, item := range datas {
		cacheKey := fmt.Sprintf(rediskey.SysConfigKey, item.ConfigKey)

		content, err := sonic.Marshal(item)

		if err != nil {
			logger.Error(err)
			continue
		}

		if len(content) > 0 {
			helper.DefaultRedis.SetString(cacheKey, item.ConfigValue)
		}
	}
}

// 获取 sys config缓存
func GetConfigCacheByKey(db *gorm.DB, key string) models.SysConfig {
	cacheKey := fmt.Sprintf(rediskey.SysConfigKey, key)
	val, _ := helper.DefaultRedis.GetString(key)
	result := models.SysConfig{}

	if val == "" {
		sonic.Unmarshal([]byte(val), &result)
	}

	if result.Id == 0 {
		if err := db.Model(&result).Where("config_key = ?", key).First(&result).Error; err != nil {
			logger.Errorf("GetConfigCacheByKey %s", err.Error())
		}
	}

	if result.Id > 0 {
		content, err := sonic.Marshal(result)

		if err != nil {
			logger.Errorf("GetConfigCacheByKey %s", err.Error())
		} else {
			helper.DefaultRedis.SetString(cacheKey, string(content))
		}
	}

	return result
}

// 获取缓存交易对
// symbolType 1-现货 2-合约
func GetTradeSet(exchangeType string, symbol string, symbolType int) (models2.TradeSet, error) {
	result := models2.TradeSet{}
	val := ""

	switch symbolType {
	case 1:
		key := fmt.Sprintf(global.TICKER_SPOT, exchangeType, symbol)
		val, _ = helper.DefaultRedis.GetString(key)
	case 2:
		key := fmt.Sprintf(global.TICKER_FUTURES, exchangeType, symbol)
		val, _ = helper.DefaultRedis.GetString(key)
	}

	if val != "" {
		if err := sonic.Unmarshal([]byte(val), &result); err != nil {
			return result, err
		}
	} else {
		return result, errors.New("未找到交易对信息")
	}

	return result, nil
}

// 获取交易所所有交易对
// symbolType 1-现货 2-合约
func GetExchangeTradeSets(exchange string, symbolType int) ([]models2.TradeSet, error) {
	result := []models2.TradeSet{}
	val := []string{}

	switch symbolType {
	case 1:
		key := fmt.Sprintf(global.TICKER_SPOT, exchange, "*")
		val, _ = helper.DefaultRedis.GetAllKeysAndValues(key)
	case 2:
		key := fmt.Sprintf(global.TICKER_FUTURES, exchange, "*")
		val, _ = helper.DefaultRedis.GetAllKeysAndValues(key)
	}

	for _, v := range val {
		item := models2.TradeSet{}
		if err := sonic.Unmarshal([]byte(v), &item); err != nil {
			return result, err
		}
		result = append(result, item)
	}

	if len(result) == 0 {
		return result, errors.New("未找到交易对信息")
	}

	return result, nil
}

func GetSystemSetting(db *gorm.DB) (models.LineSystemSetting, error) {
	key := fmt.Sprintf(rediskey.SystemSetting)
	val, _ := helper.DefaultRedis.GetString(key)
	setting := models.LineSystemSetting{}

	if val != "" {
		sonic.UnmarshalString(val, &setting)
	}

	if setting.Id > 0 {
		return setting, nil
	}

	var err error
	setting, err = ResetSystemSetting(db)
	if err != nil {
		return setting, err
	}

	return setting, nil
}
func ResetSystemSetting(db *gorm.DB) (models.LineSystemSetting, error) {
	setting := models.LineSystemSetting{}
	if err := db.Model(&setting).First(&setting).Error; err != nil {
		return setting, err
	}

	settVal, _ := sonic.MarshalString(&setting)

	if settVal != "" {
		if err := helper.DefaultRedis.SetString(rediskey.SystemSetting, settVal); err != nil {
			logger.Error("redis添加系统设置失败", err)
		}
	}
	return models.LineSystemSetting{}, nil
}
