package apis

import (
	"errors"
	"fmt"
	"go-admin/common/global"
	"go-admin/common/helper"
	"go-admin/config/serverinit"
	models2 "go-admin/models"
	"go-admin/pkg/utility"
	"go-admin/services/binanceservice"
	"go-admin/services/cacheservice"
	"strings"

	"github.com/bytedance/sonic"
	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"

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

type LineSymbol struct {
	api.Api
}

// GetPage 获取交易对管理列表
// @Summary 获取交易对管理列表
// @Description 获取交易对管理列表
// @Tags 交易对管理
// @Param symbol query string false "交易对"
// @Param baseAsset query string false "基础货币"
// @Param quoteAsset query string false "计价货币"
// @Param type query string false "交易对类型"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.LineSymbol}} "{"code": 200, "data": [...]}"
// @Router /api/v1/line-symbol [get]
// @Security Bearer
func (e LineSymbol) GetPage(c *gin.Context) {
	req := dto.LineSymbolGetPageReq{}
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]models.LineSymbol, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取交易对管理失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Export 导出交易对列表
// @Summary 导出交易对列表
// @Description 导出交易对列表
// @Tags 交易对列表
// @Param type query string false "类型:1=现货,2=合约"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/line-symbol-group/export [get]
func (e LineSymbol) Export(c *gin.Context) {
	req := dto.LineSymbolGetPageReq{}
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	err = s.ExportExcel(c, p, &req)

	if err != nil {
		e.Error(500, err, fmt.Sprintf("导出交易对列表失败，\r\n失败信息 %s", err.Error()))
		return
	}
}

// GetAll 获取所有交易对名
func (e LineSymbol) GetAll(c *gin.Context) {
	req := dto.LineSymbolGetListReq{}
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	datas, err := s.GetAll(&req)

	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(datas, "查询成功")
}

// Get 获取交易对管理
// @Summary 获取交易对管理
// @Description 获取交易对管理
// @Tags 交易对管理
// @Param id path int false "id"
// @Success 200 {object} response.Response{data=models.LineSymbol} "{"code": 200, "data": [...]}"
// @Router /api/v1/line-symbol/{id} [get]
// @Security Bearer
func (e LineSymbol) Get(c *gin.Context) {
	req := dto.LineSymbolGetReq{}
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var object models.LineSymbol

	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &object)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取交易对管理失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.OK(object, "查询成功")
}

// Insert 创建交易对管理
// @Summary 创建交易对管理
// @Description 创建交易对管理
// @Tags 交易对管理
// @Accept application/json
// @Product application/json
// @Param data body dto.LineSymbolInsertReq true "data"
// @Success 200 {object} response.Response	"{"code": 200, "message": "添加成功"}"
// @Router /api/v1/line-symbol [post]
// @Security Bearer
func (e LineSymbol) Insert(c *gin.Context) {
	req := dto.LineSymbolInsertReq{}
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c))

	err = s.Insert(&req)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("创建交易对管理失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.OK(req.GetId(), "创建成功")
}

// Update 修改交易对管理
// @Summary 修改交易对管理
// @Description 修改交易对管理
// @Tags 交易对管理
// @Accept application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body dto.LineSymbolUpdateReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "修改成功"}"
// @Router /api/v1/line-symbol/{id} [put]
// @Security Bearer
func (e LineSymbol) Update(c *gin.Context) {
	req := dto.LineSymbolUpdateReq{}
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Update(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("修改交易对管理失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "修改成功")
}

// Delete 删除交易对管理
// @Summary 删除交易对管理
// @Description 删除交易对管理
// @Tags 交易对管理
// @Param data body dto.LineSymbolDeleteReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "删除成功"}"
// @Router /api/v1/line-symbol [delete]
// @Security Bearer
func (e LineSymbol) Delete(c *gin.Context) {
	s := service.LineSymbol{}
	req := dto.LineSymbolDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("删除交易对管理失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "删除成功")
}

// SyncSpotSymbol  同步交易对
func (e LineSymbol) SyncSpotSymbol(c *gin.Context) {
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&s.Service).
		Errors

	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	tradeSets, deleteSymbols := serverinit.SpotCurrencyInit()
	symbols := make([]models.LineSymbol, 0)

	sysConfig := service.SysConfig{Service: s.Service}
	var req = new(dto.SysConfigByKeyReq)
	var resp = new(dto.GetSysConfigByKEYForServiceResp)
	req.ConfigKey = "quote_volume_24hr"
	sysConfig.GetWithKey(req, resp)
	symbolBlack := make([]models.LineSymbolBlack, 0)
	e.Orm.Model(&models.LineSymbolBlack{}).Where("type = 1").Find(&symbolBlack)

	type Ticker struct {
		Symbol string `json:"symbol"`
		Price  string `json:"price"`
	}

	tickerSymbolMaps, _ := cacheservice.GetExchangeTradeSets(global.EXCHANGE_BINANCE, 1)

	for symbol, tradeSet := range tradeSets {
		var lineSymbol models.LineSymbol
		err := e.Orm.Model(&models.LineSymbol{}).Where("symbol = ? AND type = 1", symbol).Find(&lineSymbol).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			continue
		}
		key := fmt.Sprintf(global.TICKER_SPOT, global.EXCHANGE_BINANCE, symbol)

		//判断是否在黑名单里面
		for _, black := range symbolBlack {
			if black.Symbol == symbol {
				helper.DefaultRedis.DeleteString(key)
				deleteSymbols = append(deleteSymbols, symbol)
				continue
			}
		}
		val := helper.DefaultRedis.Get(key).Val()
		var spotTicker24h models2.TradeSet
		sonic.Unmarshal([]byte(val), &spotTicker24h)
		//成交量
		if spotTicker24h.Currency == "USDT" {
			if utility.StringToFloat64(spotTicker24h.QuoteVolume) < utility.StringToFloat64(resp.ConfigValue) {
				helper.DefaultRedis.DeleteString(key)
				deleteSymbols = append(deleteSymbols, symbol)
				continue
			}
		} else {
			var tickerPrice decimal.Decimal
			for _, symbolMap := range tickerSymbolMaps {
				if symbolMap.Symbol == strings.ToUpper(spotTicker24h.Currency+"USDT") {
					tickerPrice, _ = decimal.NewFromString(symbolMap.LastPrice)
				}
			}
			if tickerPrice.GreaterThan(decimal.Zero) {
				mul := decimal.NewFromFloat(utility.StringToFloat64(spotTicker24h.QuoteVolume)).Mul(tickerPrice)
				if mul.LessThan(decimal.NewFromFloat(utility.StringToFloat64(resp.ConfigValue))) {
					helper.DefaultRedis.DeleteString(key)
					deleteSymbols = append(deleteSymbols, symbol)
					continue
				}
			}
		}
		if lineSymbol.Id <= 0 {
			lineSymbol.ExchangeType = global.EXCHANGE_BINANCE
			lineSymbol.Symbol = symbol
			lineSymbol.BaseAsset = tradeSet.Coin
			lineSymbol.QuoteAsset = tradeSet.Currency
			lineSymbol.Switch = "1"
			lineSymbol.Type = "1"
			if lineSymbol.Symbol == "" {
				continue
			}
			symbols = append(symbols, lineSymbol)
		}
	}
	if len(deleteSymbols) > 0 {
		for _, symbol := range deleteSymbols {
			//如果在交易对组里面
			//var symbolGroup []models.LineSymbolGroup
			groups := make([]models.LineSymbolGroup, 0)
			e.Orm.Model(&models.LineSymbolGroup{}).Find(&groups)
			for _, group := range groups {
				if group.Id > 0 && strings.Contains(group.Symbol, symbol) {
					split := strings.Split(group.Symbol, ",")
					value := utility.RemoveByValue(split, symbol)
					join := strings.Join(value, ",")
					e.Orm.Model(&models.LineSymbolGroup{}).Where("id = ?", group.Id).Update("symbol", join)
				}
			}
			e.Orm.Model(&models.LineSymbol{}).Where("symbol = ? AND type = 1 AND exchange_type =?", symbol, global.EXCHANGE_BINANCE).Unscoped().Delete(&models.LineSymbol{})
		}
	}

	if len(symbols) > 0 {
		err = e.Orm.Model(&models.LineSymbol{}).Omit("api_id").Create(&symbols).Error
		if err != nil {
			e.Error(500, err, err.Error())
			return
		}
	}
	e.OK(nil, "操作成功")
}

// SyncFutSymbol 更新合约交易对
func (e LineSymbol) SyncFutSymbol(c *gin.Context) {
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	tradeSets := make(map[string]models2.TradeSet, 0)
	//获取交易对
	err = binanceservice.GetAndReloadSymbols(&tradeSets)
	//获取交易对24小时行情
	deleteSymbols, err := binanceservice.InitSymbolsTicker24h(&tradeSets)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	sysConfig := service.SysConfig{Service: s.Service}
	var req = new(dto.SysConfigByKeyReq)
	var resp = new(dto.GetSysConfigByKEYForServiceResp)
	req.ConfigKey = "quote_volume_24hr"
	sysConfig.GetWithKey(req, resp)
	symbols := make([]models.LineSymbol, 0)
	symbolBlack := make([]models.LineSymbolBlack, 0)

	type Ticker struct {
		Symbol string `json:"symbol"`
		Price  string `json:"price"`
	}

	tickerSymbolMaps, _ := cacheservice.GetExchangeTradeSets(global.EXCHANGE_BINANCE, 2)
	e.Orm.Model(&models.LineSymbolBlack{}).Where("type = 1").Find(&symbolBlack)
	for symbol, tradeSet := range tradeSets {
		var lineSymbol models.LineSymbol
		err := e.Orm.Model(&models.LineSymbol{}).Where("symbol = ? AND type = 2", symbol).Find(&lineSymbol).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			continue
		}
		key := fmt.Sprintf("%s:%s", global.TICKER_FUTURES, symbol)

		//判断是否在黑名单里面
		for _, black := range symbolBlack {
			if black.Symbol == symbol {
				helper.DefaultRedis.DeleteString(key)
				deleteSymbols = append(deleteSymbols, symbol)
				continue
			}
		}
		val := helper.DefaultRedis.Get(key).Val()
		var spotTicker24h models2.TradeSet
		sonic.Unmarshal([]byte(val), &spotTicker24h)
		//成交量
		if spotTicker24h.Currency == "USDT" {
			if utility.StringToFloat64(spotTicker24h.QuoteVolume) < utility.StringToFloat64(resp.ConfigValue) {
				helper.DefaultRedis.DeleteString(key)
				deleteSymbols = append(deleteSymbols, symbol)
				continue
			}
		} else {
			var tickerPrice decimal.Decimal
			for _, symbolMap := range tickerSymbolMaps {
				if symbolMap.Symbol == strings.ToUpper(spotTicker24h.Currency+"USDT") {
					tickerPrice, _ = decimal.NewFromString(symbolMap.LastPrice)
				}
			}
			if tickerPrice.GreaterThan(decimal.Zero) {
				mul := decimal.NewFromFloat(utility.StringToFloat64(spotTicker24h.QuoteVolume)).Mul(tickerPrice)
				if mul.LessThan(decimal.NewFromFloat(utility.StringToFloat64(resp.ConfigValue))) {
					helper.DefaultRedis.DeleteString(key)
					deleteSymbols = append(deleteSymbols, symbol)
					continue
				}
			}
		}

		if lineSymbol.Id <= 0 {
			lineSymbol.ExchangeType = global.EXCHANGE_BINANCE
			lineSymbol.Symbol = symbol
			lineSymbol.BaseAsset = tradeSet.Coin
			lineSymbol.QuoteAsset = tradeSet.Currency
			lineSymbol.Switch = "1"
			lineSymbol.Type = "2"
			if lineSymbol.Symbol == "" {
				continue
			}
			symbols = append(symbols, lineSymbol)
		}
	}

	if len(deleteSymbols) > 0 {
		for _, symbol := range deleteSymbols {
			//如果在交易对组里面
			groups := make([]models.LineSymbolGroup, 0)
			//var symbolGroup []models.LineSymbolGroup
			sql := "SELECT * FROM line_symbol_group WHERE FIND_IN_SET( ? , symbol) AND type = 2 AND exchange_type =? AND deleted_at is NULL;"
			e.Orm.Model(&models.LineSymbolGroup{}).Exec(sql, symbol, global.EXCHANGE_BINANCE).Find(&groups)
			for _, group := range groups {
				if group.Id > 0 {
					split := strings.Split(group.Symbol, ",")
					value := utility.RemoveByValue(split, symbol)
					join := strings.Join(value, ",")
					e.Orm.Model(&models.LineSymbolGroup{}).Where("id = ?", group.Id).Update("symbol", join)
				}
			}
			e.Orm.Model(&models.LineSymbol{}).Where("symbol = ? AND exchange_type =? AND type = 2", symbol, global.EXCHANGE_BINANCE).Unscoped().Delete(&models.LineSymbol{})
		}
	}

	if len(symbols) > 0 {
		err = e.Orm.Model(&models.LineSymbol{}).Omit("api_id").Create(&symbols).Error
		if err != nil {
			e.Error(500, err, err.Error())
			return
		}
	}
	e.OK(nil, "操作成功")
}

// GetSymbol 获取现货和合约都有的交易对
func (e LineSymbol) GetSymbol(c *gin.Context) {
	s := service.LineSymbol{}
	req := dto.LineSymbolGetListReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	data, err := s.GetSymbol(&req)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(data, "操作成功")
}

// GetSameSymbol 获取现货和合约都有的交易对
func (e LineSymbol) GetSameSymbol(c *gin.Context) {
	req := dto.LineSymbolGetPageReq{}
	s := service.LineSymbol{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]models.LineSymbol, 0)
	var count int64

	err = s.GetSamePage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取交易对管理失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
