package airDrop

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

type RedPackageTxService struct {
}

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

// DeleteRedPackageTx 删除RedPackageTx记录
// Author [piexlmax](https://github.com/piexlmax)
func (redPackageTxService *RedPackageTxService)DeleteRedPackageTx(redPackageTx airDrop.RedPackageTx) (err error) {
	err = global.GVA_DB.Delete(&redPackageTx).Error
	return err
}

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

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

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

// GetRedPackageTxInfoList 分页获取RedPackageTx记录
// Author [piexlmax](https://github.com/piexlmax)
func (redPackageTxService *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 redPackageTxs []airDrop.RedPackageTx
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
    if info.Pid > 0 {
    	db = db.Where("pid = ?",info.Pid)
	}
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }
	if info.OrderKey != "" {
		var OrderStr string
		// 设置有效排序key 防止sql注入
		// 感谢 Tom4t0 提交漏洞信息
		orderMap := make(map[string]bool, 1)
		orderMap["id"] = true
		if orderMap[info.OrderKey] {
			if info.Desc {
				OrderStr = info.OrderKey + " desc"
			} else {
				OrderStr = info.OrderKey
			}
		} else { // didn't matched any order key in `orderMap`
			return list, total, err
		}
		err = db.Limit(limit).Offset(offset).Order(OrderStr).Find(&redPackageTxs).Error
	} else {
		err = db.Limit(limit).Offset(offset).Find(&redPackageTxs).Error
	}

	return  redPackageTxs, total, err
}
