package service

import (
	"errors"

	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"

	"go-admin/app/operate/models"
	"go-admin/app/operate/service/dto"
	"go-admin/common/actions"
	cDto "go-admin/common/dto"
)

type OrgAd struct {
	service.Service
}

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

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

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

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

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

// Update 修改OrgAd对象
func (e *OrgAd) Update(c *dto.OrgAdUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.OrgAd{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

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

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

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