package model

import (
	"active/constant"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"time"

	"git.jiaxianghudong.com/go/logs"
	"git.jiaxianghudong.com/webs/pkg/rds"
	"gopkg.in/yaml.v2"
)

var InviteBeanConf = &InviteBeanConfig{}
var InviteBeanConf2 = &InviteBeanConfig2{}

var invitebeanExpireAt int32

// 邮件内容
type appDownloadMail struct {
	Title   string    `json:"title" yaml:"title"  config:"title"`
	Content string    `json:"content" yaml:"content"  config:"content"`
	Awards  [][]int32 `json:"awards" yaml:"awards"  config:"awards"`
}

type InviteBeanConfig struct {
	Count               int64           `json:"count" yaml:"count"`
	AwardList           []Award         `json:"award_list" yaml:"award_list"`
	Appdownload_Opentag []string        `json:"appdownload_opentag" yaml:"appdownload_opentag" ` //落地页app下载开放的平台
	Appdownload_Code    string          `json:"appdownload_code" yaml:"appdownload_code"`        //落地页app下载带的标识码
	Appdownload_Mail    appDownloadMail `json:"appdownload_mail" yaml:"appdownload_mail"`        //落地页app下载邮件
}

type InviteBeanConfig2 struct {
	Count               int64           `json:"count" yaml:"count"`
	AwardList2          []Award         `json:"award_list" yaml:"award_list2"`
	Appdownload_Opentag []string        `json:"appdownload_opentag" yaml:"appdownload_opentag" ` //落地页app下载开放的平台
	Appdownload_Code    string          `json:"appdownload_code" yaml:"appdownload_code"`        //落地页app下载带的标识码
	Appdownload_Mail    appDownloadMail `json:"appdownload_mail" yaml:"appdownload_mail"`        //落地页app下载邮件
	Versionupdate_Mail  appDownloadMail `json:"versionupdate_mail" yaml:"versionupdate_mail"`    //版本更新邮件

	Appdownload_Opentag_Jx []string        `json:"appdownload_opentag_jx" yaml:"appdownload_opentag_jx" ` //家乡包落地页app下载开放的平台
	Appdownload_Code_Jx    string          `json:"appdownload_code_jx" yaml:"appdownload_code_jx"`        //家乡包落地页app下载带的标识码
	Appdownload_Mail_Jx    appDownloadMail `json:"appdownload_mail_jx" yaml:"appdownload_mail_jx"`        //家乡包落地页app下载邮件
}

type InviteRecord struct {
	Record []*Record `json:"record"`
}

type Record struct {
	UserInfo
	Status bool   `json:"status"`
	Reason string `json:"reason"`
	Time   int64  `json:"time"`
}

type Award struct {
	ShareType    int64      `json:"share_type" yaml:"share_type"`
	Count        int64      `json:"count" yaml:"count"`
	IsReceive    bool       `json:"is_receive"`
	Min          int64      `json:"-" yaml:"min"`
	Max          int64      `json:"-" yaml:"max"`
	Data         []Data     `json:"data" yaml:"data"`
	UserInfoList []UserInfo `json:"user_info_list"`
}

//获取奖品信息
type Data struct {
	Id    int64  `json:"id" yaml:"id"` //奖品id
	Count int64  `json:"count" yaml:"count"`
	Tag   string `json:"tag" yaml:"tag"`
	Min   int64  `json:"-" yaml:"min"`
	Max   int64  `json:"-" yaml:"max"`
}

type UserInfo struct {
	UserId   int64  `json:"user_id"`
	Url      string `json:"url"`
	NickName string `json:"nick_name"`
	Sex      int64  `json:"sex"` // 0女1男
}

func (this *InviteBeanConfig) GetConf(file string) {
	yamlFile, err := ioutil.ReadFile(fmt.Sprintf("./yaml/%v", file))
	if err != nil {
		log.Printf("yamlFile.Get err   #%v ", err)
	}

	err = yaml.Unmarshal(yamlFile, this)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}
	return
}

func (this *InviteBeanConfig2) GetConf(file string) {
	yamlFile, err := ioutil.ReadFile(fmt.Sprintf("./yaml/%v", file))
	if err != nil {
		log.Printf("yamlFile.Get err   #%v ", err)
	}

	err = yaml.Unmarshal(yamlFile, this)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}
	//log.Printf("%+v \n", *this)
	return
}

type InviteBeanList struct {
	List []InviteBean `json:"list"`
}

type InviteBean struct {
	IsReceive    bool       `json:"is_receive"`
	UserInfoList []UserInfo `json:"user_info_list"`
}

//获得储存信息数据
func GetInviteBeanData(UserID string, tm string, endTm string) *InviteBeanList {

	//log.Println("key:",fmt.Sprintf(constant.INVITEBEANDATA,tm),UserID)
	data := rds.Redis.HGet(fmt.Sprintf(constant.INVITEBEANDATA, tm), UserID).Val()
	inviteBeanList := &InviteBeanList{}
	if data != "" { //有值状态下
		err := json.Unmarshal([]byte(data), inviteBeanList)
		if err != nil {
			logs.Errorf("redpacket[%s] GetInviteBeanData json err:%v", UserID, err)
			return inviteBeanList
		}
	} else { //如果没有值的话
		//log.Println("new ",UserID)
		for _ = range InviteBeanConf.AwardList {
			inviteBeanList.List = append(inviteBeanList.List, InviteBean{})
		}
	}
	return inviteBeanList
}

func GetInviteRecord(userID string, tm string) *InviteRecord {
	data := rds.Redis.HGet(fmt.Sprintf(constant.INVITERECORD, tm), userID).Val()
	inviteRecord := &InviteRecord{}
	if data != "" { //有值状态下
		json.Unmarshal([]byte(data), inviteRecord)
	}
	return inviteRecord
}

func (this *InviteRecord) SetInviteRecord(userID string, tm string, endTm string) {
	data, _ := json.Marshal(this)
	rds.Redis.HSet(fmt.Sprintf(constant.INVITERECORD, tm), userID, string(data))
	end, _ := time.Parse("2006-01-02 15:04:05", endTm)
	expireAt := end.Add(constant.REBATEDATATIMEOUT)
	rds.Redis.ExpireAt(fmt.Sprintf(constant.INVITERECORD, tm), expireAt)

}

//设置数据值
func (this *InviteBeanList) SetInviteBeanData(UserID string, tm string, endTm string) bool {
	data, _ := json.Marshal(this)
	rds.Redis.HSet(fmt.Sprintf(constant.INVITEBEANDATA, tm), UserID, string(data))

	//if atomic.CompareAndSwapInt32(&invitebeanExpireAt, 0, 1) {

	end, _ := time.Parse("2006-01-02 15:04:05", endTm)
	expireAt := end.Add(constant.REBATEDATATIMEOUT)

	//	log.Printf("---更新领取百万豆数据过期时间: expireAt:%v \n", expireAt)

	rds.Redis.ExpireAt(fmt.Sprintf(constant.INVITEBEANDATA, tm), expireAt)
	rds.Redis.ExpireAt(fmt.Sprintf(constant.INVITEBEANUSER, tm), expireAt)

	//log.Printf("---更新领取百万豆被邀请人数据过期时间: expireAt:%v \n", expireAt)

	//}
	return true
}

//得到受邀用户id值，来判断是否被邀请过了
func GetInviteBeanUser(UserID string, tm string) string {
	data := rds.Redis.HGet(fmt.Sprintf(constant.INVITEBEANUSER, tm), UserID).Val()
	return data
}

//设置收到邀请的人数
func SetInviteBeanUser(UserID string, tm string, endTm string) bool {

	rds.Redis.HSet(fmt.Sprintf(constant.INVITEBEANUSER, tm), UserID, "1") //
	return true
}
