package service

import (
	"errors"
	"fmt"
	"go-admin/pkg/utility"
	"strings"

	"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"
	"go-admin/common/global"
)

type LineDirection struct {
	service.Service
}

// GetPage 获取LineDirection列表
func (e *LineDirection) GetPage(c *dto.LineDirectionGetPageReq, p *actions.DataPermission, list *[]models.LineDirection, count *int64) error {
	var err error
	var data models.LineDirection

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			// actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("LineDirectionService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

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

	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 GetLineDirection error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

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

	err := e.Orm.Model(&data).
		Where("symbol =? AND type =?", d.Symbol, d.SymbolType).
		First(model).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在")
		e.Log.Errorf("Service GetLineDirection error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

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

// Update 修改LineDirection对象
func (e *LineDirection) Update(c *dto.LineDirectionUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.LineDirection{}
	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("LineDirectionService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

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

	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 RemoveLineDirection error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// AddDirection 新增预估方向
func (e *LineDirection) AddDirection(req dto.AddDirectionReq) error {
	var accountInfo models.LineAccountSetting
	e.Orm.Model(&models.LineAccountSetting{}).Where("user_name = ?", req.AccountName).Find(&accountInfo)
	if accountInfo.Id <= 0 || accountInfo.Password != req.Password {
		return errors.New("账号密码错误请重新输入")
	}

	req.BuyPoint1 = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(req.BuyPoint1, "，", "."), "。", "."), " ", "")
	req.BuyPoint2 = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(req.BuyPoint2, "，", "."), "。", "."), " ", "")
	req.BuyPoint3 = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(req.BuyPoint3, "，", "."), "。", "."), " ", "")
	req.SellPoint1 = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(req.SellPoint1, "，", "."), "。", "."), " ", "")
	req.SellPoint2 = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(req.SellPoint2, "，", "."), "。", "."), " ", "")
	req.SellPoint3 = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(req.SellPoint3, "，", "."), "。", "."), " ", "")

	req.Symbol = utility.ReplaceSuffix(strings.ReplaceAll(req.Symbol, " ", ""), "4小时", "USDT")
	req.Symbol = strings.ReplaceAll(req.Symbol, "1小时", "USDT")
	req.Symbol = strings.ReplaceAll(req.Symbol, "1日", "USDT")
	req.Symbol = strings.ReplaceAll(req.Symbol, "四小时", "USDT")
	req.Symbol = strings.ReplaceAll(req.Symbol, "一小时", "USDT")
	req.Symbol = strings.ReplaceAll(req.Symbol, "一日", "USDT")

	symbolType := utility.StringToInt(req.Type)

	direction := models.LineDirection{
		Symbol:     req.Symbol,
		Type:       int64(symbolType),
		BuyPoint1:  req.BuyPoint1,
		BuyPoint2:  req.BuyPoint2,
		BuyPoint3:  req.BuyPoint3,
		SellPoint1: req.SellPoint1,
		SellPoint2: req.SellPoint2,
		SellPoint3: req.SellPoint3,
		Direction:  req.Direction,
		AiAnswer:   req.AiAnswer,
	}
	var directionInfo models.LineDirection
	e.Orm.Model(&models.LineDirection{}).Where("symbol = ? AND type = ?", req.Symbol, symbolType).Find(&directionInfo)
	if directionInfo.Id > 0 {
		e.Orm.Model(&models.LineDirection{}).Where("id = ?", directionInfo.Id).Delete(&models.LineDirection{})
	}
	err := e.Orm.Model(&models.LineDirection{}).Create(&direction).Error
	if err != nil {
		return fmt.Errorf("生成数据失败 err:%s", err)
	}

	return nil
}

// 重新统计aicoin 分组
func (e *LineDirection) ReloadGroup() error {
	directions := make([]models.LineDirection, 0)
	groups := make([]models.LineSymbolGroup, 0)
	spotSymbols := make(map[string][]string)
	futSymbols := make(map[string][]string)
	groupNames := make([]string, 0)

	if err := e.Orm.Model(&models.LineDirection{}).Find(&directions).Error; err != nil {
		return err
	}
	for _, v := range directions {
		if v.Type == 1 {
			spotSymbols[v.Direction] = append(spotSymbols[v.Direction], v.Symbol)
		} else {
			futSymbols[v.Direction] = append(futSymbols[v.Direction], v.Symbol)
		}
	}

	for key, item := range spotSymbols {
		groupName := fmt.Sprintf("现货-%s", key)

		group := models.LineSymbolGroup{
			ExchangeType: global.EXCHANGE_BINANCE,
			GroupName:    groupName,
			Type:         "1",
			GroupType:    "1",
			Symbol:       strings.Join(item, ","),
		}

		groupNames = append(groupNames, groupName)
		groups = append(groups, group)
	}

	for key, item := range futSymbols {
		groupName := fmt.Sprintf("合约-%s", key)

		group := models.LineSymbolGroup{
			ExchangeType: global.EXCHANGE_BINANCE,
			GroupName:    groupName,
			Type:         "2",
			GroupType:    "1",
			Symbol:       strings.Join(item, ","),
		}

		groupNames = append(groupNames, groupName)
		groups = append(groups, group)
	}

	err := e.Orm.Transaction(func(tx *gorm.DB) error {
		if err2 := tx.Delete(&models.LineSymbolGroup{}, "group_name in ?", groupNames).Error; err2 != nil {
			return err2
		}
		if err2 := tx.Create(&groups).Error; err2 != nil {
			return err2
		}

		return nil
	})

	return err
}
