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 UnitPlaceService struct {
}

// CreateUnitPlace 创建UnitPlace记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitPlaceService *UnitPlaceService) CreateUnitPlace(unitPlace autocode.UnitPlace) (err error) {
	err = global.GVA_DB.Create(&unitPlace).Error
	return err
}

// DeleteUnitPlace 删除UnitPlace记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitPlaceService *UnitPlaceService) DeleteUnitPlace(unitPlace autocode.UnitPlace) (err error) {
	err = global.GVA_DB.Delete(&unitPlace).Error
	return err
}

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

// UpdateUnitPlace 更新UnitPlace记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitPlaceService *UnitPlaceService) UpdateUnitPlace(unitPlace autocode.UnitPlace) (err error) {

	err = global.GVA_DB.Save(&unitPlace).Error
	return err
}

// GetUnitPlace 根据id获取UnitPlace记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitPlaceService *UnitPlaceService) GetUnitPlace(id uint) (err error, unitPlace autocode.UnitPlace) {
	err = global.GVA_DB.Where("id = ?", id).First(&unitPlace).Error
	return
}

func (unitPlaceService *UnitPlaceService) GetUnitPlaces(id *int) (err error, unitPlaces []autocode.UnitPlace) {
	err = global.GVA_DB.Where("unit_id = ?", id).Find(&unitPlaces).Error
	return
}

// GetUnitPlaceInfoList 分页获取UnitPlace记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitPlaceService *UnitPlaceService) GetUnitPlaceInfoList(info autoCodeReq.UnitPlaceSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&autocode.UnitPlace{})
	if info.UnitId != nil && *info.UnitId != 0 {
		db.Where("unit_id = ?", info.UnitId)
	}

	var unitPlaces []autocode.UnitPlace
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&unitPlaces).Error
	return err, unitPlaces, total
}
