package serverinit

import (
	"fmt"
	"go-admin/app/admin/models"
	"go-admin/app/admin/service"
	"go-admin/common/const/rediskey"
	"go-admin/common/helper"
	"go-admin/config"
	"go-admin/pkg/httputils"
	"go-admin/services/cacheservice"
	"go-admin/services/futureservice"
	"go-admin/services/scriptservice"
	"os"

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

// 业务初始化
func BusinessInit(db *gorm.DB) {
	httputils.InitProxy(config.ExtConfig.ProxyUrl)

	if err := loadApiUser(db); err != nil { //加载api用户
		os.Exit(-1)
	}

	//初始化参数配置
	cacheservice.InitConfigCache(db)
	//初始化可缓存价格交易对
	symbolPriceService := service.LineSymbolPrice{}
	symbolPriceService.Orm = db
	symbolPriceService.Log = logger.NewHelper(sdk.Runtime.GetLogger()).WithFields(map[string]interface{}{})
	symbolPriceService.InitCache()

	//初始化订单配置
	cacheservice.ResetSystemSetting(db)
	lineApiUser := service.LineApiUser{}
	lineApiUser.Orm = db
	if err := lineApiUser.InitCache(); err != nil {
		logger.Errorf("初始化api用户失败:%v", err)
		os.Exit(-1)
	}

	//定时任务
	RunSpotJobs(db)
}

// 行情监听初始化
func BinanceMarketInit() error {
	//币安 现货交易对（仅数据初始化，不启动WebSocket）
	SpotCurrencyInit()
	//币安 合约交易对（仅数据初始化，不启动WebSocket）
	FuturesInit()

	//现货 订阅
	SpotSubscribeInit("normal")
	//合约订阅
	futureservice.StartBinanceProWs("normal")
	// log.Info("订阅合约-开始")
	// go futureservice.StartBinanceProWs("normal")

	return nil
}

// 开启现货ws监听
func SpotWsInit() {
}

// 定义任务
func RunSpotJobs(db *gorm.DB) {
	cronJob := cron.New()
	//定时执行脚本任务
	_, err := cronJob.AddFunc("@every 3s", func() {
		order := scriptservice.PreOrder{}
		order.AddOrder(db)
	})
	if err != nil {
		return
	}

	//启动
	cronJob.Start()
}

/*
加载api user
*/
func loadApiUser(db *gorm.DB) error {
	users := make([]models.LineApiUser, 0)

	if err := db.Model(&models.LineApiUser{}).Where("open_status =1").Find(&users).Error; err != nil {
		logger.Error("loadApiUser：", err)
		return err
	}

	for _, user := range users {
		key := fmt.Sprintf(rediskey.API_USER, user.Id)
		val, _ := sonic.MarshalString(&user)

		if val != "" {
			if err := helper.DefaultRedis.SetString(key, val); err != nil {
				logger.Error("loadApiUser 保存redis：", err)
			}
		}
	}

	groups := make([]models.LineApiGroup, 0)

	if err := db.Model(&models.LineApiGroup{}).Find(&groups).Error; err != nil {
		logger.Error("loadApiGroup：", err)
		return err
	}

	apiGroupService := service.LineApiGroup{}
	apiGroupService.Log = logger.NewHelper(sdk.Runtime.GetLogger()).WithFields(map[string]interface{}{})

	for _, group := range groups {
		service.SetApiGroupCache(group)
	}

	return nil
}
