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

// CreateUnitHistory 创建UnitHistory记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitHistoryService *UnitHistoryService) CreateUnitHistory(unitHistory autocode.UnitHistory) (err error) {
	err = global.GVA_DB.Create(&unitHistory).Error
	return err
}

// DeleteUnitHistory 删除UnitHistory记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitHistoryService *UnitHistoryService) DeleteUnitHistory(unitHistory autocode.UnitHistory) (err error) {
	err = global.GVA_DB.Delete(&unitHistory).Error
	return err
}

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

// UpdateUnitHistory 更新UnitHistory记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitHistoryService *UnitHistoryService) UpdateUnitHistory(unitHistory autocode.UnitHistory) (err error) {
	err = global.GVA_DB.Save(&unitHistory).Error
	return err
}

// GetUnitHistory 根据id获取UnitHistory记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitHistoryService *UnitHistoryService) GetUnitHistory(id uint) (err error, unitHistory autocode.UnitHistory) {
	err = global.GVA_DB.Where("id = ?", id).First(&unitHistory).Error
	return
}

// GetUnitHistoryInfoList 分页获取UnitHistory记录
// Author [piexlmax](https://github.com/piexlmax)
func (unitHistoryService *UnitHistoryService) GetUnitHistoryInfoList(info autoCodeReq.UnitHistorySearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&autocode.UnitHistory{})
	if info.UnitName != "" {
		db.Where("unit_name = ?", info.UnitName)
	}
	if info.Period != "" {
		db.Where("period = ?", info.Period)
	}
	var unitHistorys []autocode.UnitHistory
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Order("created_at desc").Find(&unitHistorys).Error
	return err, unitHistorys, total
}
