package service

import (
	"cold-delivery/common/actions"
	cDto "cold-delivery/common/dto"
	"cold-delivery/common/global"
	"errors"
	"gogs.baozhida.cn/zoie/OAuth-core/service"
	"gorm.io/gorm"

	"cold-delivery/app/admin/model"
	"cold-delivery/app/admin/service/dto"
)

type SysOperaLog struct {
	service.Service
}

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

	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("Service GetSysOperaLogPage error: %s", err.Error())
		return global.GetFailedErr
	}
	return nil
}

// Get 获取SysOperaLog对象
func (e *SysOperaLog) Get(d *dto.SysOperaLogGetReq, operaLogModel *model.SysOperaLog, p *actions.DataPermission) error {
	err := e.Orm.
		Scopes(actions.Permission(operaLogModel.TableName(), p)).
		First(operaLogModel, d.GetId()).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return global.GetNotFoundOrNoPermissionErr
		}
		return global.GetFailedErr
	}
	return nil
}

// Insert 创建SysOperaLog对象
func (e *SysOperaLog) Insert(operaLogModel *model.SysOperaLog) error {
	var err error
	var data model.SysOperaLog

	err = e.Orm.Model(&data).
		Create(operaLogModel).Error
	if err != nil {
		e.Log.Errorf("Service InsertSysOperaLog error: %s", err.Error())
		return global.CreateFailedErr
	}
	return nil
}

// Remove 删除SysOperaLog
func (e *SysOperaLog) Remove(d *dto.SysOperaLogDeleteReq, p *actions.DataPermission) error {
	var err error
	var data model.SysOperaLog

	db := e.Orm.
		Scopes(actions.Permission(data.TableName(), p)).
		Delete(&data, d.GetId())
	if err = db.Error; err != nil {
		e.Log.Errorf("Service RemoveSysOperaLog error: %s", err.Error())
		return global.DeleteFailedErr
	}
	if db.RowsAffected == 0 {
		return global.DeleteNotFoundOrNoPermissionErr
	}
	return nil
}
