package service

import (
	"errors"

    "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 SpiderListenSymbol struct {
	service.Service
}

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

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

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

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

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

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

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

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