package models

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	jsoniter "github.com/json-iterator/go"
	mhayaTime "github.com/mhaya/extend/time"
	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/internal/constant"
	"github.com/mhaya/game/game_cluster/internal/data"
	"github.com/mhaya/game/game_cluster/internal/guid"
	"github.com/mhaya/game/game_cluster/internal/mdb"
	"github.com/mhaya/game/game_cluster/internal/param"
	initdata "github.com/mhaya/game/game_cluster/internal/third/tg_sign"
	"github.com/mhaya/game/game_cluster/internal/token"
	clog "github.com/mhaya/logger"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"sort"
	"time"
)

type Account struct {
	UserName  string `json:"username" bson:"userName"`
	Platform  string `json:"platform" bson:"platform"`
	Account   string `json:"account" bson:"account"`
	Channel   string `json:"channel" bson:"channel"`
	IsPremium bool   `json:"isPremium" bson:"isPremium"`
	LoginIp   string `json:"loginIp" bson:"loginIp"`
	OpenId    string `json:"openId" bson:"openId"`
	JoinIp    string `json:"joinip" bson:"JoinIp"`
	JoinTime  int64  `json:"jointime" bson:"JoinTime"`
}

type HomeData struct {
	Item         ItemBasePack     `json:"item"`             //道具
	FirstItem    FirstReward      `json:"firstItem"`        //首次登录奖励
	RocketLv     RocketLvProgress `json:"rocketLvProgress"` //币安进度
	Dirty        bool             `json:"dirty" //是否关注tg`
	TotalIcorme  int64            `json:"totalIcorme"`
	BtUserName   string           `json:"btUserName"` //机器人名字
	ChatIDName   string           `json:"chatIDName"` //频道名字
	Avatar       string           `json:"avatar"`     //头像地址
	QuickLink    string           `json:"quickLink"`  //快捷方式链接
	InviteStatus int              `json:"inviteStatus"`
}

type RocketLvProgress struct {
	Max int `json:"max"`
	Cur int `json:"cur"`
}

func (ac *Account) AccountRegisterOrLogin(req *param.LoginReq) (*Account, int32) {
	var account Account
	ctx := context.Background()
	acc, err := mdb.RDB.Get(ctx, fmt.Sprintf("%v:%v", constant.CNameAccount, req.OpenID)).Bytes()
	if err != nil && err != redis.Nil {
		clog.Debugf("[Account] AccountRegisterOrLogin error: %v", err)
	}
	findFilter := bson.M{"openId": req.OpenID}
	if len(acc) > 0 {
		err = jsoniter.Unmarshal(acc, &account)
		if err != nil {
			clog.Debugf("[Account] unmarshal AccountRegisterOrLogin data error: %v", err)
			return nil, code.LoginError
		}
	} else {
		err = mdb.MDB.Collection(constant.CNameAccount).FindOne(context.Background(), findFilter).Decode(&account)
		if err != nil && err != mongo.ErrNoDocuments {
			clog.Errorf("Failed to AccountRegisterOrLogin select err request: %v  err = %v", req, err.Error())
			return nil, code.LoginError
		}
	}

	// todo 测试代码
	curLvID, _ := mdb.RDB.Get(context.Background(), constant.RocketLvKey).Int()
	if curLvID < 100 {
		curLvID = 100
		mdb.RDB.Set(context.Background(), constant.RocketLvKey, curLvID, 0)
	}

	user := initdata.GetUserInfo(req.Sign)

	//设置IP 规则
	num, ok := SetPlayerBlacklistIpRecord(req.IP, req.OpenID)
	if ok {
		clog.Errorf("Failed to SetPlayerBlacklistIpRecord err request: %v,num:%v", req, num)
		return nil, code.LoginError
	}

	if account.OpenId != "" {
		if account.Platform == "on" {
			//统计新注册
			SetAppointDailyRecordNewUserRegisterHash(req.Platform, req.Channel, account.UserName, account.JoinIp, mhayaTime.CreateFromTimestamp(account.JoinTime).Unix(), DailyRecordNewRegistered)
		}
		if (len(user.Username) > 0 && account.Account != user.Username) || user.IsPremium != account.IsPremium || req.IP != account.LoginIp || account.Platform != req.Platform {
			account.Account = user.Username
			account.IsPremium = user.IsPremium
			account.LoginIp = req.IP
			account.Platform = req.Platform
			mdb.MDB.Collection(constant.CNameAccount).UpdateOne(context.Background(), findFilter, bson.M{"$set": bson.M{"platform": req.Platform, "account": user.Username, "isPremium": user.IsPremium, "loginIp": req.IP}})

			jsonData, _ := jsoniter.Marshal(&account)
			err = mdb.RDB.Set(context.Background(), fmt.Sprintf("%v:%v", constant.CNameAccount, account.OpenId), jsonData, time.Hour*3*24).Err()
		}

		return &account, code.OK
	}

	devAccountTable := &Account{
		UserName:  guid.Next(),
		OpenId:    req.OpenID,
		Platform:  req.Platform,
		Channel:   req.Channel,
		Account:   user.Username,
		IsPremium: user.IsPremium,
		LoginIp:   req.IP,
		JoinIp:    req.IP,
		JoinTime:  mhayaTime.Now().Unix(),
	}
	player := NewPlayer(token.New(req.Pid, req.OpenID, devAccountTable.UserName, "", "", ""))
	jsonData, err := jsoniter.Marshal(&player)
	if err != nil {
		clog.Errorf("Failed to AccountRegisterOrLogin request: %v  err = %v", devAccountTable, err.Error())
		return nil, code.LoginError
	}
	err = mdb.RDB.Set(ctx, fmt.Sprintf("%v:%v", constant.CNamePlayer, req.OpenID), jsonData, time.Hour*3*24).Err()
	if err != nil {
		clog.Errorf("Failed to AccountRegisterOrLogin request: %v  err = %v", devAccountTable, err.Error())
		return nil, code.LoginError
	}

	jsonData, err = jsoniter.Marshal(&devAccountTable)
	if err != nil {
		clog.Errorf("Failed to AccountRegisterOrLogin  request: %v  err = %v", devAccountTable, err.Error())
		return nil, code.LoginError
	}

	err = mdb.RDB.Set(context.Background(), fmt.Sprintf("%v:%v", constant.CNameAccount, devAccountTable.OpenId), jsonData, time.Hour*3*24).Err()
	if err != nil {
		clog.Errorf("Failed to AccountRegisterOrLogin request: %v  err = %v", devAccountTable, err.Error())
		return nil, code.LoginError
	}

	_, err = mdb.MDB.Collection(constant.CNameAccount).InsertOne(context.Background(), devAccountTable)
	if err != nil {
		clog.Errorf("Failed to AccountRegisterOrLogin request: %v  err = %v", devAccountTable, err.Error())
		return nil, code.LoginError
	}

	//统计新注册
	SetDailyRecordNewUserRegisterHash(req.Platform, req.Channel, devAccountTable.UserName, req.IP, DailyRecordNewRegistered)

	// 新用户触发币安升级逻辑
	// 当前级别
	lvID, _ := mdb.RDB.Get(context.Background(), constant.RocketLvKey).Int()
	userNum := mdb.RDB.IncrBy(context.Background(), constant.TotalUserKey, 1).Val()
	/*	// 当前用户数
		userNum, _ := mdb.MDB.Collection(constant.CNamePlayer).CountDocuments(context.Background(), bson.M{})*/

	roConfig := data.RocketLvConfig.GetAll()

	// 当前经验
	var curExperience int64
	// 当前升级所需经验
	var curLvNeed int64

	keys := []int{}
	for _, row := range roConfig {
		keys = append(keys, row.ID)
	}
	sort.Ints(keys)

	for _, id := range keys {
		lvRow := roConfig[id]
		if id == lvID {
			curLvNeed = int64(lvRow.LvNeed)
			break
		}
		curExperience += int64(lvRow.LvNeed)
	}

	//curLvID, _ := mdb.RDB.Get(context.Background(), constant.RocketLvKey).Int()
	//if curLvID < 100 {
	//	curLvID = 100
	//}

	if userNum-curExperience >= curLvNeed {
		// 触发升级

		// 并发控制
		if lvID == curLvID {
			mdb.RDB.Set(context.Background(), constant.RocketLvKey, curLvID+1, 0)
		}
	}

	return devAccountTable, code.OK
}
