package unit

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	mhayaHttp "github.com/mhaya/extend/http"
	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/internal/constant"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"github.com/mhaya/game/game_cluster/internal/param"
	mhayaLogger "github.com/mhaya/logger"
	"math/rand"
	"strconv"
	"sync"
	"time"
)

var (
	maxRobotNum       = 1000 // 运行x个机器人
	url               = "http://127.0.0.1:20000"
	url2              = "http://127.0.0.1:20001" // web node
	addr              = "127.0.0.1:10011"        // 网关地址(正式环境通过区服列表获取)
	serverId    int32 = 10001                    // 测试的游戏服id
	pid               = "2126001"                // 测试的sdk包id
	printLog          = false                    // 是否输出详细日志
)

// 邀请排行榜机器人
func InviteRankRobot(account *param.LoginReq, wg *sync.WaitGroup) {
	defer wg.Done()
	// 注册邀请人账号
	_, userName := RegisterAndLogin(url, account)
	//
	//params := map[string]interface{}{
	//	"parentName": userName,
	//}
	// 注册被邀请人账号并填写邀请
	RegisterAndLogin(url, account)

	time.Sleep(time.Duration(rand.Int31n(10)) * time.Millisecond)

	//Invite(url, params, token)

	//设置邀请榜单
	models.SetRank(constant.RankSourceInvite, 0, userName, 1)
}

func BuildAccount(total int) []*param.LoginReq {
	accounts := make([]*param.LoginReq, 0)
	for i := 1; i <= total; i++ {
		str := strconv.Itoa(i)
		accounts = append(accounts, &param.LoginReq{
			Pid:      2,
			OpenID:   str,
			Platform: "ios",
			Channel:  "tg",
		})
	}
	return accounts
}

// 注册并登录
func RegisterAndLogin(url string, val *param.LoginReq) (string, string) {
	token := RegisterDevAccount(url, val)
	if token == "" {
		return "", ""
	}
	params := map[string]interface{}{
		"nickName": "guest" + val.OpenID,
	}
	userName := Login(url, params, token)

	time.Sleep(time.Duration(rand.Int31n(2)) * time.Millisecond)
	return token, userName
}

func RegisterDevAccount(url string, val *param.LoginReq) string {
	requestURL := fmt.Sprintf("%s/auth", url)

	params := map[string]interface{}{
		"pid":      val.Pid,
		"openid":   val.OpenID,
		"platform": val.Platform,
		"channel":  val.Channel,
	}

	jsonBytes, _, err := mhayaHttp.PostJSON(requestURL, params)
	if err != nil {
		mhayaLogger.Warn(err)
		return ""
	}

	rsp := &code.Result{}
	err = jsoniter.Unmarshal(jsonBytes, rsp)
	if err != nil {
		mhayaLogger.Warn(err)
		return ""
	}
	if rsp.Code == 0 {
		mhayaLogger.Debugf("register account = %v, result = %v", val.OpenID, rsp)
		return rsp.Data.(string)
	}
	return ""
}

func Login(url string, params map[string]interface{}, token string) string {
	requestURL := fmt.Sprintf("%s/login", url)
	jsonBytes, err := mhayaHttp.PostJSONWithHeader(requestURL, params, token)
	if err != nil {
		mhayaLogger.Warn(err)
		return ""
	}

	rsp := &code.Result{}
	err = jsoniter.Unmarshal(jsonBytes, rsp)
	if err != nil {
		mhayaLogger.Warn(err)
		return ""
	}

	mhayaLogger.Debugf("Login OK")

	m := rsp.Data.(map[string]interface{})
	i := m["userName"]
	return i.(string)
}
