package orchard

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

var OrchardRecordTime = ""

func (this *OrchardUserDay) GetData(tm string, userID string) {

	data := rds.Redis.HGet(fmt.Sprintf(constant.ORCHARDAY, tm), userID).Val()
	if data != "" {
		err := json.Unmarshal([]byte(data), this)
		if err != nil {
			logs.Errorf("redpacket[%s] GetInviteBeanData json err:%v", userID, err)
			return
		}
		timeNow := time.Now().Unix()
		for i := range this.DurationTimeStamp {
			if this.DurationTimeStamp[i] > timeNow {
				this.Countdowns[i] = this.DurationTimeStamp[i] - timeNow
			} else {
				this.Countdowns[i] = 0
			}
		}
	} else {
		this.DurationTimeStamp = make([]int64, len(OrchardConf.WashList))
		this.Countdowns = make([]int64, len(OrchardConf.WashList))
		this.WaterRemainTimes = make([]int64, len(OrchardConf.WashList))
		timeNow := time.Now().Unix()

		for i := range this.DurationTimeStamp {
			this.DurationTimeStamp[i] = timeNow
			this.Countdowns[i] = 0
		}
		this.StealNumber = OrchardConf.StealFruit
		for i := range this.WaterRemainTimes {
			this.WaterRemainTimes[i] = OrchardConf.WashList[i].RemainTimes
		}
		this.Login = true
		this.SetData(tm, userID)
	}
	return
}

func (this *OrchardUserDay) SetData(tm string, userID string) bool {
	data, _ := json.Marshal(this)
	rds.Redis.HSet(fmt.Sprintf(constant.ORCHARDAY, tm), userID, string(data)).Err()
	end, _ := time.Parse("2006-01-02", tm)
	expireAt := end.Add(constant.ADVERTISETIMEOUT)
	log.Printf("---更新施肥数据过期时间: expireAt:%v \n", expireAt)
	rds.Redis.ExpireAt(fmt.Sprintf(constant.ORCHARDAY, tm), expireAt)
	OrchardRecordTime = tm
	return true
}
