package comcode

import (
	"active/constant"
	"errors"
	"fmt"
	"log"
	"strconv"
	"time"

	"git.jiaxianghudong.com/webs/pkg/rds"
	"gorm.io/gorm"
)

type Comcode struct {
	Id         int64  `json:"id" gorm:"column:id"`
	Code       string `json:"code" gorm:"column:code"`
	AwardsId   int    `json:"awards_id" gorm:"column:awards_id"`
	CreateTime string `json:"create_time" gorm:"column:create_time"`
	OpenTime   int64  `json:"open_time" gorm:"column:open_time"`
	EndTime    int64  `json:"end_time" gorm:"column:end_time"`
	UserId     int64  `json:"user_id" gorm:"column:user_id"`
	activeId   string `gorm:"-"`
}

func (c *Comcode) GetActiveId() string {
	return c.activeId
}

func (this *Comcode) SetActiveId(activeId string) {
	this.activeId = activeId
}

func (this Comcode) TableName() string {
	return fmt.Sprintf("common_code_%v", this.activeId)
}

func (this *Comcode) OneComcode(code string, db *gorm.DB) error {
	return db.Table(this.TableName()).Where("code = ?", code).First(this).Error
}

func (this *Comcode) CreateOne(db *gorm.DB) error {
	var count int64
	db.Table(this.TableName()).Where("awards_id = ? and user_id=?", this.AwardsId, this.UserId).Count(&count)
	if count > 0 {
		return errors.New("count>0")
	}
	db.Table(this.TableName()).Create(this)
	return nil
}

func (this *Comcode) UpdateUserId(db *gorm.DB) error {
	return db.Table(this.TableName()).Where("code = ?", this.Code).Updates(map[string]interface{}{
		"user_id":   this.UserId,
		"used_time": time.Now().Format("2006-01-02 15:04:05"),
	}).Error
}

func (this *Comcode) CountByUserid(db *gorm.DB, userid int64) (count int64) {
	db.Table(this.TableName()).Where("user_id = ? and awards_id = ?", userid, this.AwardsId).Count(&count)
	return count
}

func (this *Comcode) CountByUseridAndDate(db *gorm.DB, userid int64, date time.Time) (count int64) {
	db.Table(this.TableName()).Where("user_id = ? and awards_id = ? and DATE(used_time) = ?",
		userid, this.AwardsId, date.Format("2006-01-02")).Count(&count)
	return count
}

func GetLimitData(activeId string, userId string, tm string) int {
	data := rds.Redis.HGet(fmt.Sprintf(constant.ComCodeLimt, tm), fmt.Sprintf("%v%v", activeId, userId)).Val()
	if data == "" {
		return 0
	} else {
		number, err := strconv.Atoi(data)
		if err != nil {
			return 0
		}
		return number
	}
}

func SetLimitData(activeId string, userId string, tm string, data int) bool {
	rds.Redis.HSet(fmt.Sprintf(constant.ComCodeLimt, tm), fmt.Sprintf("%v%v", activeId, userId), fmt.Sprintf("%v", data))
	end, _ := time.Parse("2006-01-02", tm)
	expireAt := end.Add(25 * time.Hour)
	log.Printf("---更新领取兑换卷过期时间: expireAt:%v \n", expireAt)
	rds.Redis.ExpireAt(fmt.Sprintf(constant.ComCodeLimt, tm), expireAt)
	return true
}

func (this *Comcode) JudgeExp(timeUnix int64) bool {
	if this.OpenTime != 0 && timeUnix < this.OpenTime {
		return false
	}
	if this.EndTime != 0 && timeUnix > this.EndTime {
		return false
	}
	return true
}
