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

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

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

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

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

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

// Update 修改OrgMatchEvaluateWonderful对象
func (e *OrgMatchEvaluateWonderful) Update(c *dto.OrgMatchEvaluateWonderfulUpdateReq) error {
	var err error
	var data = models.OrgMatchEvaluateWonderful{}
	e.Orm.First(&data, c.GetId())
	c.Generate(&data)

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

// Remove 删除OrgMatchEvaluateWonderful
func (e *OrgMatchEvaluateWonderful) Remove(d *dto.OrgMatchEvaluateWonderfulDeleteReq) error {
	var data models.OrgMatchEvaluateWonderful

	db := e.Orm.Model(&data).
		Where("id not in (?)", d.GetId()).
		Where("match_evaluate_id = ? ", d.EId).
		Delete(&data)
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveOrgMatchEvaluateWonderful error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}
