package service

import (
	"errors"
	"fmt"
	"go-admin/common/global"
	"go-admin/common/helper"
	ext "go-admin/config"
	models2 "go-admin/models"
	"go-admin/pkg/utility"
	"sort"

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

	"go-admin/app/admin/models"
	"go-admin/app/admin/service/dto"
	"go-admin/common/actions"
	cDto "go-admin/common/dto"
)

type LinePriceLimit struct {
	service.Service
}

// GetPage 获取LinePriceLimit列表
func (e *LinePriceLimit) GetPage(c *dto.LinePriceLimitGetPageReq, p *actions.DataPermission, list *[]models.LinePriceLimit, count *int64) error {
	var err error
	var data models.LinePriceLimit
	tx := e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		)

	if c.StartRange != "" {
		tx = tx.Where("`range` >= ?", utility.StringToFloat64(c.StartRange))
	}
	if c.EndRange != "" {
		tx = tx.Where("`range` <= ?", utility.StringToFloat64(c.EndRange))
	}
	err = tx.Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("LinePriceLimitService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取LinePriceLimit对象
func (e *LinePriceLimit) Get(d *dto.LinePriceLimitGetReq, p *actions.DataPermission, model *models.LinePriceLimit) error {
	var data models.LinePriceLimit

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetLinePriceLimit error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建LinePriceLimit对象
func (e *LinePriceLimit) Insert(c *dto.LinePriceLimitInsertReq) error {
	var err error
	var data models.LinePriceLimit
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("LinePriceLimitService Insert error:%s \r\n", err)
		return err
	}
	return nil
}

// Update 修改LinePriceLimit对象
func (e *LinePriceLimit) Update(c *dto.LinePriceLimitUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.LinePriceLimit{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("LinePriceLimitService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// Remove 删除LinePriceLimit
func (e *LinePriceLimit) Remove(d *dto.LinePriceLimitDeleteReq, p *actions.DataPermission) error {
	var data models.LinePriceLimit

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveLinePriceLimit error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// UpRange 更新涨跌幅
func (e *LinePriceLimit) UpRange() error {
	var client *helper.BinanceClient
	if ext.ExtConfig.ProxyUrl != "" {
		client, _ = helper.NewBinanceClient("", "", "", "http://127.0.0.1:7890")
	} else {
		client, _ = helper.NewBinanceClient("", "", "", "")
	}
	request, httpCode, err := client.SendSpotRequest("/api/v3/ticker/24hr", "GET", map[string]string{})
	if err != nil {
		return errors.New(fmt.Sprintf("获取现货交易对涨跌幅失败 err:%s", err.Error()))
	}

	if httpCode != 200 {
		return errors.New(fmt.Sprintf("获取现货交易对涨跌幅失败 http code:%d", httpCode))
	}
	spotTicker24HrAll := make([]dto.Ticker24Hr, 0)
	spotTicker24Hr := make([]dto.Ticker24Hr, 0)

	if err := sonic.Unmarshal(request, &spotTicker24HrAll); err != nil {
		logger.Error("反序列化报错", err)
		return err
	}

	for _, hr := range spotTicker24HrAll {
		tradeSet, _ := helper.GetObjString[models2.TradeSet](helper.DefaultRedis, fmt.Sprintf(global.TICKER_SPOT, global.EXCHANGE_BINANCE, hr.Symbol))
		if tradeSet.Currency != "" && tradeSet.Coin != "" {
			spotTicker24Hr = append(spotTicker24Hr, hr)
		}
	}
	sort.Slice(spotTicker24Hr, func(i, j int) bool {
		return utility.StringToFloat64(spotTicker24Hr[i].PriceChangePercent) > utility.StringToFloat64(spotTicker24Hr[j].PriceChangePercent)
	})

	limits := make([]models.LinePriceLimit, 0)
	for _, hr := range spotTicker24Hr {
		var status string
		if utility.StringToFloat64(hr.PriceChangePercent) > 0 {
			status = "1"
		} else {
			status = "2"
		}
		limit := models.LinePriceLimit{
			Symbol:          hr.Symbol,
			Type:            "1",
			DirectionStatus: status,
			Range:           utility.StringToDecimal(hr.PriceChangePercent),
		}
		limits = append(limits, limit)
	}
	err = e.Orm.Transaction(func(tx *gorm.DB) error {

		err2 := tx.Model(&models.LinePriceLimit{}).Where("type = ?", "1").Unscoped().Delete(&models.LinePriceLimit{}).Error
		if err2 != nil {
			return errors.New(fmt.Sprintf("删除现货交易对涨跌幅失败 err:%d", err))
		}

		err = tx.Model(&models.LinePriceLimit{}).Create(&limits).Error
		if err != nil {
			return errors.New(fmt.Sprintf("更新现货交易对涨跌幅失败 err:%d", err))
		}
		return nil
	})
	if err != nil {
		return err
	}

	//更新合约涨跌幅
	futuresRequest, code, err := client.SendFuturesRequest("/fapi/v1/ticker/24hr", "GET", map[string]string{})
	if err != nil {
		return errors.New(fmt.Sprintf("获取合约交易对涨跌幅失败 err:%s", err.Error()))
	}

	if code != 200 {
		return errors.New(fmt.Sprintf("获取合约交易对涨跌幅失败 http code:%d", code))
	}
	futTicker24HrAll := make([]dto.FutTicker24Hr, 0)
	futTicker24Hr := make([]dto.FutTicker24Hr, 0)
	sonic.Unmarshal(futuresRequest, &futTicker24HrAll)
	for _, hr := range futTicker24HrAll {
		tradeSet, _ := helper.GetObjString[models2.TradeSet](helper.DefaultRedis, fmt.Sprintf("%s:%s", global.TICKER_FUTURES, hr.Symbol))
		if tradeSet.Currency != "" && tradeSet.Coin != "" {
			futTicker24Hr = append(futTicker24Hr, hr)
		}
	}
	sort.Slice(futTicker24Hr, func(i, j int) bool {
		return utility.StringToFloat64(futTicker24Hr[i].PriceChangePercent) > utility.StringToFloat64(futTicker24Hr[j].PriceChangePercent)
	})

	futLimits := make([]models.LinePriceLimit, 0)
	for _, hr := range futTicker24Hr {
		var status string
		if utility.StringToFloat64(hr.PriceChangePercent) > 0 {
			status = "1"
		} else {
			status = "2"
		}
		limit := models.LinePriceLimit{
			Symbol:          hr.Symbol,
			Type:            "2",
			DirectionStatus: status,
			Range:           utility.StringToDecimal(hr.PriceChangePercent),
		}
		futLimits = append(futLimits, limit)
	}

	err = e.Orm.Transaction(func(tx *gorm.DB) error {

		err2 := tx.Model(&models.LinePriceLimit{}).Where("type = ?", "2").Unscoped().Delete(&models.LinePriceLimit{}).Error
		if err2 != nil {
			return errors.New(fmt.Sprintf("删除现货交易对涨跌幅失败 err:%d", err))
		}

		err = tx.Model(&models.LinePriceLimit{}).Create(&futLimits).Error
		if err != nil {
			return errors.New(fmt.Sprintf("更新现货交易对涨跌幅失败 err:%d", err))
		}
		return nil
	})
	if err != nil {
		return err
	}
	return nil
}
