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

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

	err = e.Orm.Table("org_club").
		Select("id,club_name,created_at,club_contacts,club_contacts_en,club_mobile").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
			cDto.PassDel("org_club"),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("OrgClubService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

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

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

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

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

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

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