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/binanceservice"
	"go-admin/services/futureservice"
	"go-admin/services/scriptservice"
	"os"

	"github.com/bytedance/sonic"
	"github.com/go-admin-team/go-admin-core/logger"
	log "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)
	}

	//初始化订单配置
	binanceservice.ResetSystemSetting(db)

	//币安 现货交易对
	SpotCurrencyInit()

	//币安 合约交易对
	FuturesInit()

	//第一次初始化交易对价格
	spotApi := binanceservice.SpotRestApi{}
	futApi := binanceservice.FutRestApi{}
	spotApi.Ticker()
	futApi.Ticker()

	//现货 订阅
	SpotSubscribeInit("normal")
	//合约订阅
	futureservice.StartBinanceProWs("normal")
	//定时任务
	RunSpotJobs(db)
}

// 开启现货ws监听
func SpotWsInit() {
	//启动websocket服务
	//go func() {
	//	err := wsservice.StartServer(":3333")
	//	if err != nil {
	//		log.Info("wsservice.StartServer", zap.Error(err))
	//
	//		_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	//		cancel()
	//	}
	//}()
}

// 定义任务
func RunSpotJobs(db *gorm.DB) {
	cronJob := cron.New()
	//添加任务 同步交易对行情
	// spotApi := spotservice.SpotRestApi{}
	// futApi := futureservice.FutRestApi{}
	// _, err := cronJob.AddFunc("@every 10s", func() {
	// 	//BuySellOrderNew(db)
	// spotApi.Ticker()
	// futApi.Ticker()
	// })
	// if err != nil {
	// 	return
	// }

	//定时执行脚本任务
	_, 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 {
		log.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 {
				log.Error("loadApiUser 保存redis：", err)
			}
		}
	}

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

	if err := db.Model(&models.LineApiGroup{}).Find(&groups).Error; err != nil {
		log.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
}
