package service

import (
	"errors"
	"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"
)

type LineSymbolBlack struct {
	service.Service
}

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

	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("LineSymbolBlackService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

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

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

// Insert 创建LineSymbolBlack对象
func (e *LineSymbolBlack) Insert(c *dto.LineSymbolBlackInsertReq) error {
	var err error
	var data models.LineSymbolBlack
	c.Generate(&data)
	//判断是否已经在用这个交易对
	groups := make([]models.LineSymbolGroup, 0)
	sql := "SELECT * FROM line_symbol_group WHERE FIND_IN_SET( ? , symbol) AND type = ? AND deleted_at is NULL;"
	e.Orm.Model(&models.LineSymbolGroup{}).Raw(sql, c.Symbol, c.Type).Scan(&groups)

	for _, group := range groups {
		if group.Id > 0 {
			split := strings.Split(group.Symbol, ",")
			value := utility.RemoveByValue(split, c.Symbol)
			join := strings.Join(value, ",")
			e.Orm.Model(&models.LineSymbolGroup{}).Where("id = ?", group.Id).Update("symbol", join)
		}
	}

	err = e.Orm.Create(&data).Error

	return err
}

func (e *LineSymbolBlack) ReloadSymbol(symbolType string) error {
	symbolService := LineSymbol{Service: e.Service}

	if symbolType == "1" {
		if err := symbolService.ResetSpotSymbol(); err != nil {
			return errors.New("黑名单添加成功 更新现货交易对失败")
		}
	} else if symbolType == "2" {
		if err := symbolService.ResetFuturesSymbol(); err != nil {
			return errors.New("黑名单添加成功 更新合约交易对失败")
		}
	}

	return nil
}

// Update 修改LineSymbolBlack对象
func (e *LineSymbolBlack) Update(c *dto.LineSymbolBlackUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.LineSymbolBlack{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)
	//判断是否已经在用这个交易对
	groups := make([]models.LineSymbolGroup, 0)
	sql := "SELECT * FROM line_symbol_group WHERE FIND_IN_SET( ? , symbol) AND type = ? AND deleted_at is NULL;"
	e.Orm.Model(&models.LineSymbolGroup{}).Raw(sql, c.Symbol, c.Type).Scan(&groups)

	for _, group := range groups {
		if group.Id > 0 {
			split := strings.Split(group.Symbol, ",")
			value := utility.RemoveByValue(split, c.Symbol)
			join := strings.Join(value, ",")
			e.Orm.Model(&models.LineSymbolGroup{}).Where("id = ?", group.Id).Update("symbol", join)
		}
	}

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

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

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