package twi

import (
	"courseSign/server/global"
	"courseSign/server/model/common/request"
	"courseSign/server/model/twi"
	twiReq "courseSign/server/model/twi/request"
)

type TwiActTemplateService struct {
}

// CreateTwiActTemplate 创建TwiActTemplate记录
// Author [piexlmax](https://github.com/piexlmax)
func (twiActTemplateService *TwiActTemplateService) CreateTwiActTemplate(twiActTemplate twi.TwiActTemplate) (err error) {
	err = global.GVA_DB.Create(&twiActTemplate).Error
	return err
}

// DeleteTwiActTemplate 删除TwiActTemplate记录
// Author [piexlmax](https://github.com/piexlmax)
func (twiActTemplateService *TwiActTemplateService)DeleteTwiActTemplate(twiActTemplate twi.TwiActTemplate) (err error) {
	err = global.GVA_DB.Delete(&twiActTemplate).Error
	return err
}

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

// UpdateTwiActTemplate 更新TwiActTemplate记录
// Author [piexlmax](https://github.com/piexlmax)
func (twiActTemplateService *TwiActTemplateService)UpdateTwiActTemplate(twiActTemplate twi.TwiActTemplate) (err error) {
	err = global.GVA_DB.Save(&twiActTemplate).Error
	return err
}

// GetTwiActTemplate 根据id获取TwiActTemplate记录
// Author [piexlmax](https://github.com/piexlmax)
func (twiActTemplateService *TwiActTemplateService)GetTwiActTemplate(id uint) (twiActTemplate twi.TwiActTemplate, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&twiActTemplate).Error
	return
}

// GetTwiActTemplateByAid 根据id获取TwiActTemplate记录
// Author [piexlmax](https://github.com/piexlmax)
func (twiActTemplateService *TwiActTemplateService)GetTwiActTemplateByAid(id uint) (list []twi.TwiActTemplate, err error) {
	err = global.GVA_DB.Where("act_id = ?", id).First(&list).Error
	return
}

// GetTwiActTemplateInfoList 分页获取TwiActTemplate记录
// Author [piexlmax](https://github.com/piexlmax)
func (twiActTemplateService *TwiActTemplateService)GetTwiActTemplateInfoList(info twiReq.TwiActTemplateSearch) (list []twi.TwiActTemplate, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&twi.TwiActTemplate{})
    var twiActTemplates []twi.TwiActTemplate
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
    if info.ActId != nil {
        db = db.Where("act_id = ?",info.ActId)
    }
    if info.ActType != nil {
        db = db.Where("act_type = ?",info.ActType)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

	err = db.Limit(limit).Offset(offset).Find(&twiActTemplates).Error
	return  twiActTemplates, total, err
}
