package service

import (
	"errors"
	"fmt"

	"github.com/bytedance/sonic"
	"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"
	"go-admin/common/const/rediskey"
	cDto "go-admin/common/dto"
	"go-admin/common/helper"
)

type LineReduceStrategy struct {
	service.Service
}

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

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

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

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

// 根据id获取对象
func (e *LineReduceStrategy) GetById(id int) (models.LineReduceStrategy, error) {
	result := models.LineReduceStrategy{}
	key := fmt.Sprintf(rediskey.ReduceStrategy, id)
	str, _ := helper.DefaultRedis.GetString(key)

	if str != "" {
		sonic.Unmarshal([]byte(str), &result)
	}

	if result.Id == 0 {
		if err := e.Orm.Model(&models.LineReduceStrategy{}).First(&result, id).Error; err != nil {
			return result, err
		}
	}

	return result, nil
}

// Insert 创建LineReduceStrategy对象
func (e *LineReduceStrategy) Insert(c *dto.LineReduceStrategyInsertReq) error {
	var err error
	var data models.LineReduceStrategy
	var count int64

	e.Orm.Model(&models.LineReduceStrategy{}).Where("name = ?", c.Name).Count(&count)
	if count > 0 {
		err = errors.New("策略名称重复")
		return err
	}

	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("LineReduceStrategyService Insert error:%s \r\n", err)
		return err
	}

	e.saveCache(data)

	return nil
}

// Update 修改LineReduceStrategy对象
func (e *LineReduceStrategy) Update(c *dto.LineReduceStrategyUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.LineReduceStrategy{}
	var count int64

	e.Orm.Model(&models.LineReduceStrategy{}).Where("name = ? AND id !=?", c.Name, c.GetId()).Count(&count)
	if count > 0 {
		err = errors.New("策略名称重复")
		return err
	}

	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

	err = e.Orm.Transaction(func(tx *gorm.DB) error {
		if errr := tx.Delete(&models.LineReduceStrategyItem{}, "reduce_strategy_id =?", c.GetId()).Error; errr != nil {
			return errr
		}

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

		return nil
	})

	e.saveCache(data)

	return err
}

func (e *LineReduceStrategy) saveCache(data models.LineReduceStrategy) {
	str, _ := sonic.MarshalString(data)

	if str != "" {
		key := fmt.Sprintf(rediskey.ReduceStrategy, data.Id)

		if errr := helper.DefaultRedis.SetString(key, str); errr != nil {
			e.Log.Errorf("LineReduceStrategyService SetString error:%s \r\n", errr)
		}
	}
}

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

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

	key := fmt.Sprintf(rediskey.ReduceStrategy, data.Id)
	helper.DefaultRedis.DeleteString(key)
	return nil
}
