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

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

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

// Get 获取SysLoginLog对象
func (e *SysLoginLogService) Get(d *dto.SysLoginLogGetReq, loginLogModel *model.SysLoginLog, p *actions.DataPermission) error {
	err := e.Orm.
		Scopes(actions.Permission(loginLogModel.TableName(), p)).
		First(loginLogModel, 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
}

// Remove 删除SysLoginLog
func (e *SysLoginLogService) Remove(c *dto.SysLoginLogDeleteReq, p *actions.DataPermission) error {
	var err error
	var data model.SysLoginLog

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