package model

import (
	"active/constant"
	"active/tools"
	"encoding/json"
	"fmt"
	"git.jiaxianghudong.com/go/logs"
	"git.jiaxianghudong.com/webs/pkg/rds"
	"log"
	"time"
)

var AdvertiseBeanConf = &AdvertiseBeanConfig{}

var AdvertiseBeanRecordTime = ""

type AdvertiseBeanConfig struct {
	Times  int64 `json:"times" yaml:"times"`
	Total  int64 `json:"total" yaml:"total"`
	Second int64 `json:"second" yaml:"second"`
	List   []struct {
		Ball int64 `json:"ball" yaml:"ball"`
		Rate int64 `json:"rate" yaml:"rate"`
	} `json:"list" yaml:"list"`
}

func AdvertisePretreatment() {
	tools.ReloadYaml("advertisebean.yaml", AdvertiseBeanConf)
	var rate int64
	for i := range AdvertiseBeanConf.List {
		rate += AdvertiseBeanConf.List[i].Rate
		AdvertiseBeanConf.List[i].Rate = rate
	}
	fmt.Printf("处理后数据 %+v \n", AdvertiseBeanConf)
}

type AdvertiseBeanUserInfo struct {
	OpenTime   int64 `json:"open_time"`   //开启时间
	Times      int64 `json:"times"`       //剩余次数
	BeanNumber int64 `json:"bean_number"` //领取豆豆数
}

func (this *AdvertiseBeanUserInfo) GetData(UserID string, tm string) {
	data := rds.Redis.HGet(fmt.Sprintf(constant.ADVERTISEBEAN, tm), UserID).Val()
	if data != "" {
		err := json.Unmarshal([]byte(data), this)
		if err != nil {
			logs.Errorf("AdvertiseBeanUserInfo[%s]  json err:%v", UserID, err)
		}
	} else {
		this.Times = AdvertiseBeanConf.Times
		//this.OpenTime = time.Now().Unix()
	}
}

func (this AdvertiseBeanUserInfo) SetData(UserID string, tm string) bool {
	data, _ := json.Marshal(this)
	rds.Redis.HSet(fmt.Sprintf(constant.ADVERTISEBEAN, tm), UserID, string(data))

	if AdvertiseBeanRecordTime == "" || AdvertiseBeanRecordTime != tm {
		end, _ := time.Parse("2006-01-02", tm)
		expireAt := end.Add(constant.ADVERTISETIMEOUT)
		log.Printf("---更新看广告领取豆数据过期时间: expireAt:%v \n", expireAt)
		rds.Redis.ExpireAt(fmt.Sprintf(constant.ADVERTISEBEAN, tm), expireAt)
		AdvertiseBeanRecordTime = tm
	}

	return true
}
