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

// CreatePlace 创建Place记录
// Author [piexlmax](https://github.com/piexlmax)
func (placeService *PlaceService) CreatePlace(place autocode.Place) (err error) {
	err = global.GVA_DB.Create(&place).Error
	return err
}

// DeletePlace 删除Place记录
// Author [piexlmax](https://github.com/piexlmax)
func (placeService *PlaceService) DeletePlace(place autocode.Place) (err error) {
	err = global.GVA_DB.Delete(&place).Error
	return err
}

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

// UpdatePlace 更新Place记录
// Author [piexlmax](https://github.com/piexlmax)
func (placeService *PlaceService) UpdatePlace(place autocode.Place) (err error) {
	err = global.GVA_DB.Save(&place).Error
	return err
}

func (placeService *PlaceService) FindPlaceSum(placeIds []string) (total int) {
	global.GVA_DB.Model(&autocode.Place{}).Select("SUM(unit_max_integral) as total").Where("id in ?", placeIds).Pluck("total", &total)
	return
}

// GetPlace 根据id获取Place记录
// Author [piexlmax](https://github.com/piexlmax)
func (placeService *PlaceService) GetPlace(id uint) (err error, place autocode.Place) {
	err = global.GVA_DB.Where("id = ?", id).First(&place).Error
	return
}

// GetPlaceInfoList 分页获取Place记录
// Author [piexlmax](https://github.com/piexlmax)
func (placeService *PlaceService) GetPlaceInfoList(info autoCodeReq.PlaceSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&autocode.Place{})
	if info.Type != nil {
		db.Where("type=?", info.Type)
	}
	if info.OrganCode != "" {
		db.Where("organ_code=?", info.OrganCode)
	}
	if info.Name != "" {
		db.Where("`name` LIKE ?", "%"+info.Name+"%")
	}
	var places []autocode.Place
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&places).Error
	return err, places, total
}
