package scratchcard

import (
	"active/internal/model/goldbrick"
	"encoding/json"
	"fmt"
	"git.jiaxianghudong.com/go/logs"
	"git.jiaxianghudong.com/webs/pkg/rds"
	"git.jiaxianghudong.com/webs/pkg/xgorm"
	"gorm.io/gorm/clause"
	"log"
	"strconv"
	"sync/atomic"
	"time"
)

var ScratchCard int32

var ScratchCardDate = ""

type UserInfo struct {
	UserData
	AwardList []ScratchCardAward `json:"award_list"`
	//IsWatch   int64              `json:"is_watch"`
}

type UserData struct {
	Id         int64             `json:"id" gorm:"id"`
	UserId     int64             `json:"user_id" gorm:"user_id"`
	PlayerName string            `json:"player_name" gorm:"player_name"`
	PlayerImg  string            `json:"player_img" gorm:"player_img"`
	PlayerSex  int64             `json:"player_sex" gorm:"player_sex"`
	CardNumber int               `json:"card_number" gorm:"card_number"`
	Flush      bool              `json:"flush" gorm:"flush"`
	FriendList []ScratchCardHelp `json:"friend_list" gorm:"-"`
	FriendJson string            `json:"-" gorm:"friend_json"`
	UpdateTime int64             `json:"update_time" gorm:"update_time"`
}

func (this UserData) TableName() string {
	return "scratch_card_user"
}

//设置userdata的值
func (this *UserData) SetData(userID string, tm string, endTm string) bool {
	data, _ := json.Marshal(this)
	rds.Redis.Set(fmt.Sprintf(DATAUSER, tm, userID), string(data), 2*time.Hour)
	db := xgorm.NewConn(goldbrick.GoldBrickGorm)
	db.Save(this)
	if atomic.CompareAndSwapInt32(&ScratchCard, 0, 1) {
		end, _ := time.Parse("2006-01-02 15:04:05", endTm)
		expireAt := end.Add(TIMEOUT)
		log.Printf("---更新scratch-card: expireAt:%v \n", expireAt)
		//rds.Redis.ExpireAt(fmt.Sprintf(DATAUSER, tm), expireAt)
		rds.Redis.ExpireAt(fmt.Sprintf(AWARDUSERCARD, tm), expireAt)
		rds.Redis.ExpireAt(fmt.Sprintf(ITEMSUSER, tm), expireAt)
		rds.Redis.ExpireAt(fmt.Sprintf(GEITEMSLIST, tm), expireAt)
	}

	return true
}

func (this *UserData) GetData(userID string, tm string, name string, img string, sex int64) {
	data := rds.Redis.Get(fmt.Sprintf(DATAUSER, tm, userID)).Val()
	//ln(data)
	if data != "" {
		err := json.Unmarshal([]byte(data), this)
		if err != nil {
			logs.Errorf("redpacket[%s] GetData json err:%v", userID, err)
		}
	}
	db := xgorm.NewConn(goldbrick.GoldBrickGorm)
	if data == "" || this.Flush == true {
		this.Flush = false
		userid, _ := strconv.ParseInt(userID, 10, 64)
		//fmt.Println("tm",tm)
		timestamp, _ := time.Parse("20060102150405", tm)
		db.Table(this.TableName()).Where("user_id = ?", userid).First(this)
		if this.Id == 0 || this.UpdateTime < timestamp.Unix() {
			this.UserId = userid
			this.CardNumber = 0
			this.PlayerName = name
			this.PlayerImg = img
			this.PlayerSex = sex
			this.FriendJson = ""
			this.UpdateTime = time.Now().Unix()

			db.Clauses(clause.OnConflict{
				Columns:   []clause.Column{{Name: "user_id"}},
				DoUpdates: clause.AssignmentColumns([]string{"player_name", "player_img", "player_sex", "card_number", "friend_json"}),
			}).Create(this)

		}
		this.Flush = false
		this.FriendList = make([]ScratchCardHelp, 0)
		db.Table(ScratchCardHelp{}.TableName()).Where("date >= ? and help_userid = ?", timestamp.Unix(), userid).Order("date desc").Limit(10).Find(&this.FriendList)
	}

	if name != "" || img != "" {
		this.PlayerName = name
		this.PlayerSex = sex
		this.PlayerImg = img
	}
}

func (this *UserInfo) GetAwardList(tm string) {
	db := xgorm.NewConn(goldbrick.GoldBrickGorm)
	data := rds.Redis.Get(fmt.Sprintf(GEITEMSLIST, tm)).Val()
	if data == "" {
		timestamp, _ := time.Parse("20060102150405", tm)
		db.Table(ScratchCardAward{}.TableName()).Where("date >= ?", timestamp.Unix()).Order("date desc,level desc").Limit(20).Find(&this.AwardList)
		for i := range this.AwardList {
			json.Unmarshal([]byte(this.AwardList[i].Item), &this.AwardList[i].Items)
		}
		this.SetAwardList(tm)
	} else {
		err := json.Unmarshal([]byte(data), &this.AwardList)
		if err != nil {
			logs.Errorf(" GetData json err:%v", err)
		}
	}

}

func (this *UserInfo) SetAwardList(tm string) {
	data, _ := json.Marshal(this.AwardList)
	rds.Redis.Set(fmt.Sprintf(GEITEMSLIST, tm), string(data), TIMEOUT)
}

func ChangeDaySTL(tm string) {

	end, _ := time.Parse("2006-01-02", tm)
	expireAt := end.Add(DAYTIMEOUT)
	rds.Redis.ExpireAt(fmt.Sprintf(ITEMLIMITDAY, tm), expireAt)
	rds.Redis.ExpireAt(fmt.Sprintf(HELPLIMITDAY, tm), expireAt)
	rds.Redis.ExpireAt(fmt.Sprintf(SCRATCHFREEONE, tm), expireAt)
	rds.Redis.ExpireAt(fmt.Sprintf(FREEDRAWCARDDAY, tm), expireAt)
	rds.Redis.ExpireAt(fmt.Sprintf(DAYGETITEMLIMIT, tm), expireAt)
	ScratchCardDate = tm

}
