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

// CreateRedPackageTx 创建RedPackageTx记录
// Author [piexlmax](https://github.com/piexlmax)
func (txService *RedPackageTxService) CreateRedPackageTx(tx airDrop.RedPackageTx) (err error) {
	err = global.GVA_DB.Create(&tx).Error
	return err
}

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

// DeleteRedPackageTxByIds 批量删除RedPackageTx记录
// Author [piexlmax](https://github.com/piexlmax)
func (txService *RedPackageTxService)DeleteRedPackageTxByIds(ids request.IdsReq,deleted_by uint) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
	    if err := tx.Model(&airDrop.RedPackageTx{}).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.RedPackageTx{}).Error; err != nil {
            return err
        }
        return nil
    })
	return err
}

// UpdateRedPackageTx 更新RedPackageTx记录
// Author [piexlmax](https://github.com/piexlmax)
func (txService *RedPackageTxService)UpdateRedPackageTx(tx airDrop.RedPackageTx) (err error) {
	err = global.GVA_DB.Save(&tx).Error
	return err
}

// GetRedPackageTx 根据id获取RedPackageTx记录
// Author [piexlmax](https://github.com/piexlmax)
func (txService *RedPackageTxService)GetRedPackageTx(id uint) (tx airDrop.RedPackageTx, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&tx).Error
	return
}

// GetRedPackageTxInfoList 分页获取RedPackageTx记录
// Author [piexlmax](https://github.com/piexlmax)
func (txService *RedPackageTxService)GetRedPackageTxInfoList(info airDropReq.RedPackageTxSearch) (list []airDrop.RedPackageTx, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&airDrop.RedPackageTx{})
    var txs []airDrop.RedPackageTx
    // 如果有条件搜索 下方会自动创建搜索语句
    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(&txs).Error
	return  txs, total, err
}
