package service

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

type LineSymbolGroup struct {
	service.Service
}

// GetPage 获取LineSymbolGroup列表
func (e *LineSymbolGroup) GetPage(c *dto.LineSymbolGroupGetPageReq, p *actions.DataPermission, list *[]models.LineSymbolGroup, count *int64) error {
	var err error
	var data models.LineSymbolGroup
	query := e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			// actions.Permission(data.TableName(), p),
		)
	if c.ExchangeType != "" {
		query = query.Where("exchange_type = ?", c.ExchangeType)
	}

	err = query.
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("LineSymbolGroupService GetPage error:%s \r\n", err)
		return err
	}

	for index := range *list {
		symbols := strings.Split((*list)[index].Symbol, ",")

		(*list)[index].Count = len(symbols)
	}
	return nil
}

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

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

// Insert 创建LineSymbolGroup对象
func (e *LineSymbolGroup) Insert(c *dto.LineSymbolGroupInsertReq) error {
	var err error
	var data models.LineSymbolGroup
	c.Generate(&data)

	symbols := availableSymbols(data.Symbol, c.Type, e)

	if len(symbols) == 0 {
		return errors.New("全部交易对不可用")
	}

	data.Symbol = strings.Join(symbols, ",")
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("LineSymbolGroupService Insert error:%s \r\n", err)
		return err
	}
	return nil
}

// 可用交易对
func availableSymbols(symbols, symbolType string, e *LineSymbolGroup) []string {
	blacks := make([]string, 0)
	newSymbols := make([]string, 0)
	reqSymbols := strings.Split(symbols, ",")
	e.Orm.Model(&models.LineSymbolBlack{}).Where("type=?", symbolType).Select("symbol").Find(&blacks)
	for _, v := range reqSymbols {
		symbol := strings.ToUpper(v)

		//黑名单跳过
		if utility.ContainsStr(blacks, symbol) {
			continue
		}

		//重复跳过
		if utility.ContainsStr(newSymbols, symbol) {
			continue
		}

		newSymbols = append(newSymbols, symbol)
	}
	return newSymbols
}

// Update 修改LineSymbolGroup对象
func (e *LineSymbolGroup) Update(c *dto.LineSymbolGroupUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.LineSymbolGroup{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)
	symbols := availableSymbols(data.Symbol, c.Type, e)

	if len(symbols) == 0 {
		return errors.New("全部交易对不可用")
	}

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

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

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