package autocode

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/autocode"
	autoCodeReq "github.com/flipped-aurora/gin-vue-admin/server/model/autocode/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type UnitUserService struct {
}

// CreateUnitUser 创建UnitUser记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitUserService *UnitUserService) CreateUnitUser(unitUser autocode.UnitUser) (err error) {
	err = global.GVA_DB.Create(&unitUser).Error
	return err
}

// DeleteUnitUser 删除UnitUser记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitUserService *UnitUserService) DeleteUnitUser(unitUser autocode.UnitUser) (err error) {
	err = global.GVA_DB.Delete(&unitUser).Error
	return err
}

// DeleteUnitUserByIds 批量删除UnitUser记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitUserService *UnitUserService) DeleteUnitUserByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]autocode.UnitUser{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateUnitUser 更新UnitUser记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitUserService *UnitUserService) UpdateUnitUser(unitUser autocode.UnitUser) (err error) {
	err = global.GVA_DB.Save(&unitUser).Error
	return err
}

// GetUnitUser 根据id获取UnitUser记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitUserService *UnitUserService) GetUnitUser(id uint) (err error, unitUser autocode.UnitUser) {
	err = global.GVA_DB.Where("id = ?", id).First(&unitUser).Error
	return
}

func (unitUserService *UnitUserService) GetUnitUsers(id *int) (err error, unitUser []autocode.UnitUser) {
	err = global.GVA_DB.Where("unit_id = ?", id).Find(&unitUser).Error
	return
}

// GetUnitUserInfoList 分页获取UnitUser记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitUserService *UnitUserService) GetUnitUserInfoList(info autoCodeReq.UnitUserSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&autocode.UnitUser{})
	var unitUsers []autocode.UnitUser
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&unitUsers).Error
	return err, unitUsers, total
}
