package airDrop

import (
	"courseSign/server/global"
	"courseSign/server/model/airDrop"
	"courseSign/server/model/common/request"
    airDropReq "courseSign/server/model/airDrop/request"
    "gorm.io/gorm"
)

type RedPackageService struct {
}

// CreateRedPackage 创建RedPackage记录
// Author [piexlmax](https://github.com/piexlmax)
func (红包Service *RedPackageService) CreateRedPackage(红包 airDrop.RedPackage) (err error) {
	err = global.GVA_DB.Create(&红包).Error
	return err
}

// DeleteRedPackage 删除RedPackage记录
// Author [piexlmax](https://github.com/piexlmax)
func (红包Service *RedPackageService)DeleteRedPackage(红包 airDrop.RedPackage) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
	    if err := tx.Model(&airDrop.RedPackage{}).Where("id = ?", 红包.ID).Update("deleted_by", 红包.DeletedBy).Error; err != nil {
              return err
        }
        if err = tx.Delete(&红包).Error; err != nil {
              return err
        }
        return nil
	})
	return err
}

// DeleteRedPackageByIds 批量删除RedPackage记录
// Author [piexlmax](https://github.com/piexlmax)
func (红包Service *RedPackageService)DeleteRedPackageByIds(ids request.IdsReq,deleted_by uint) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
	    if err := tx.Model(&airDrop.RedPackage{}).Where("id in ?", ids.Ids).Update("deleted_by", deleted_by).Error; err != nil {
            return err
        }
        if err := tx.Where("id in ?", ids.Ids).Delete(&airDrop.RedPackage{}).Error; err != nil {
            return err
        }
        return nil
    })
	return err
}

// UpdateRedPackage 更新RedPackage记录
// Author [piexlmax](https://github.com/piexlmax)
func (红包Service *RedPackageService)UpdateRedPackage(红包 airDrop.RedPackage) (err error) {
	err = global.GVA_DB.Save(&红包).Error
	return err
}

// GetRedPackage 根据id获取RedPackage记录
// Author [piexlmax](https://github.com/piexlmax)
func (红包Service *RedPackageService)GetRedPackage(id uint) (红包 airDrop.RedPackage, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&红包).Error
	return
}

// GetRedPackageInfoList 分页获取RedPackage记录
// Author [piexlmax](https://github.com/piexlmax)
func (红包Service *RedPackageService)GetRedPackageInfoList(info airDropReq.RedPackageSearch) (list []airDrop.RedPackage, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&airDrop.RedPackage{})
    var 红包s []airDrop.RedPackage
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

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