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

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

	err = e.Orm.Table("org_season as os").
		Joins("left join org_league as ol on os.league_id=ol.id").
		Select("os.id, os.league_id, ol.league_name, os.season_name, os.total_rounds, os.start_time,"+
			"os.end_time, os.status").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
			cDto.PassDel("os"),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("OrgSeasonService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

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

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

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

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

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

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