package main

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	mhayaHttp "github.com/mhaya/extend/http"
	mhayaTime "github.com/mhaya/extend/time"
	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/internal/param"
	mhayaLogger "github.com/mhaya/logger"
	pomeloClient "github.com/mhaya/net/parser/pomelo/client"
	"math/rand"
	"strconv"
	"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 main() {

	accounts := make(map[string]*param.LoginReq)
	for i := 1; i <= maxRobotNum; i++ {
		str := strconv.Itoa(i)
		accounts[str] = &param.LoginReq{
			Pid:      2,
			OpenID:   str,
			Platform: "ios",
			Channel:  "tg_sign",
		}
	}
	var Url = ""
	for _, val := range accounts {
		k := rand.Intn(2)
		if k == 1 {
			Url = url2
		} else {
			Url = url
		}
		fmt.Println(Url)
		time.Sleep(200 * time.Millisecond)
		go RunRobot(Url, val)
	}

}

var Player = []string{"28q1PjXEh3M", "28q1PjY2LSm", "28q1PjYpgFW", "28q1PjYLLvw", "28qeTc4cwBj", "28q1RgBeGYq", "28q1PjYLLvx", "28qfgUzvh67", "28qeLPTxn79", "28qfBVzrRqm", "28qf5VTadno", "28qfdrK9yVN", "28qg8W7Lbmh"}

func RunRobot(url string, val *param.LoginReq) {
	token := RegisterDevAccount(url, val)
	if token == "" {
		return
	}
	params := map[string]interface{}{
		"nickName": "guest" + val.OpenID,
	}
	Login(url, params, token)

	time.Sleep(time.Duration(rand.Int31n(2)) * time.Millisecond)
	num1 := rand.Intn(12)
	params = map[string]interface{}{
		"parentName": Player[num1],
	}
	time.Sleep(time.Duration(rand.Int31n(10)) * time.Millisecond)
	//Invite(url, params, token)

	timer := time.NewTimer(time.Duration(rand.Int31n(2)) * time.Second)
	go func(url string, token string) {
		select {
		case <-timer.C:
			num := rand.Intn(20) + 1
			params = map[string]interface{}{
				"multi": num,
			}
			Roll(url, params, token)

			num = rand.Intn(2) + 1
			params = map[string]interface{}{
				"tp": num,
			}
			Lottery(url, params, token)

		}

	}(url, token)

}

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) {
	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")

}

func Roll(url string, params map[string]interface{}, token string) {
	requestURL := fmt.Sprintf("%s/roll", 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("roll  parms =%v", params)
}

func Lottery(url string, params map[string]interface{}, token string) {
	requestURL := fmt.Sprintf("%s/lottery", 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("Lottery %v", params)
}

func Invite(url string, params map[string]interface{}, token string) {
	requestURL := fmt.Sprintf("%s/invite", 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("Invite %v", params)
}

func RunRobot1(url, pid, userName, password, addr string, serverId int32, printLog bool) *Robot {
	// 创建客户端
	cli := New(
		pomeloClient.New(
			pomeloClient.WithRequestTimeout(10*time.Second),
			pomeloClient.WithErrorBreak(true),
		),
	)
	cli.PrintLog = printLog

	// 登录获取token
	if err := cli.GetToken(url, pid, userName, password); err != nil {
		mhayaLogger.Error(err)
		return nil
	}

	// 根据地址连接网关
	if err := cli.ConnectToTCP(addr); err != nil {
		mhayaLogger.Error(err)
		return nil
	}

	if cli.PrintLog {
		mhayaLogger.Infof("tcp connect %s is ok", addr)
	}

	// 随机休眠
	cli.RandSleep()

	// 用户登录到游戏节点
	err := cli.UserLogin(serverId)
	if err != nil {
		mhayaLogger.Warn(err)
		return nil
	}

	if cli.PrintLog {
		mhayaLogger.Infof("user login is ok. [user = %s, serverId = %d]", userName, serverId)
	}

	//cli.RandSleep()

	// 查看是否有角色
	err = cli.PlayerSelect()
	if err != nil {
		mhayaLogger.Warn(err)
		return nil
	}

	//cli.RandSleep()

	// 创建角色
	err = cli.ActorCreate()
	if err != nil {
		mhayaLogger.Warn(err)
		return nil
	}

	//cli.RandSleep()

	// 角色进入游戏
	err = cli.ActorEnter()
	if err != nil {
		mhayaLogger.Warn(err)
		return nil
	}

	elapsedTime := cli.StartTime.DiffInMillisecond(mhayaTime.Now())
	mhayaLogger.Debugf("[%s] is enter to game. elapsed time:%dms", cli.TagName, elapsedTime)

	//cli.Disconnect()

	return cli
}
