package model

import (
	"active/constant"
	"encoding/json"
	"time"

	"git.jiaxianghudong.com/go/logs"
)

//PreferentialData 特惠礼包存储数据
type PreferentialData struct {
	PayTime    string `yaml:"pay_time" json:"pay_time"`
	Continuous int    `yaml:"continuous" json:"continuous"`
}

//PreferenceTh 特惠礼包
type PreferenceTh struct {
	Th1 []int `json:"th_1"`
	Th2 []int `json:"th_2"`
	Th3 []int `json:"th_3"`
	Th4 []int `json:"th_4"`
}

// //PreferenceDay 特惠连续天数
// type PreferenceDay struct {
// 	Level1 int `json:"levle_1"` //1 待领取  3已领取  5未能领取
// 	Level2 int `json:"levle_2"`
// 	Level3 int `json:"levle_3"`
// }

//PreferenceRspData 特惠参数
type PreferenceRspData struct {
	LastTag string        `json:"last_pay_th"`
	Data    *PreferenceTh `json:"data"`
}

//GetPreferenceDay 获取连续日数领取状态
func (pd *PreferentialData) GetPreferenceDay() []int {

	if pd.PayTime != "" {

		if time.Now().Format("2006-01-02") == pd.PayTime {
			//今日参与
			return GetPayTodayStaus(pd.Continuous)
		} else if time.Unix(time.Now().Unix()-86400, 0).Format("2006-01-02") == pd.PayTime {
			//昨日参与
			return GetPayYesterDayStaus(pd.Continuous)
		}
	}

	//未参与,前天之前参与重新计算
	return []int{1, 5, 5}
}

//GetPayTodayStaus 获取状态
func GetPayTodayStaus(continuous int) []int {

	if continuous == 1 {
		return []int{3, 5, 5}
	} else if continuous == 2 {
		return []int{3, 3, 5}
	}

	return []int{3, 3, 3}
}

//GetPayYesterDayStaus 获取昨日状态
func GetPayYesterDayStaus(continuous int) []int {

	if continuous == 1 {
		return []int{3, 1, 5}
	}

	return []int{3, 3, 1}
}

//GetPreferential 获取存储
func (pd *PreferentialData) GetPreferential(data string) {
	if len(data) > 0 {
		err := json.Unmarshal([]byte(data), &pd)
		if err != nil {
			logs.Errorf("GetPreferential: json data:%s err:%v", data, err)
		}
	}
}

//GetPreference 获取特惠等级数据
func GetPreference(userRedisInfo map[string]string) *PreferenceRspData {
	pt := &PreferenceTh{}
	for _, tag := range constant.PreferenceGoods {
		pd := &PreferentialData{}
		pd.GetPreferential(userRedisInfo[tag])

		switch tag {
		case "th_1":
			pt.Th1 = pd.GetPreferenceDay()
		case "th_2":
			pt.Th2 = pd.GetPreferenceDay()
		case "th_3":
			pt.Th3 = pd.GetPreferenceDay()
		case "th_4":
			pt.Th4 = pd.GetPreferenceDay()
		}
	}

	lastTag := "th_1"
	if v, ok := userRedisInfo["last_pay_th"]; ok {
		lastTag = v
	}

	return &PreferenceRspData{
		Data:    pt,
		LastTag: lastTag,
	}
}
