using Fantasy;
using Fantasy.Async;
using Fantasy.Network;
using NBC;
using NBF.Fishing2;
using Newtonsoft.Json;
using Log = NBC.Log;

namespace NBF
{
    public static class LoginHelper
    {
        private static Session _session;

        public static async FTask Login(string account)
        {
            _session = Net.CreateSession("127.0.0.1:20001");

            // _session.Scene.AddComponent<UnitUnityComponent>();

            var acc = account;

            // 发送登录的请求给服务器
            var response = (A2C_LoginResponse)await Net.Call(new C2A_LoginRequest()
            {
                Username = acc,
                Password = acc,
                LoginType = 1
            });

            if (response.ErrorCode != 0)
            {
                Log.Error($"登录发生错误{response.ErrorCode}");
                return;
            }

            if (!Game.Main.GetComponent<JWTParseComponent>().Parse(response.ToKen, out var payload))
            {
                return;
            }

            // 根据ToKen返回的Address登录到Gate服务器
            _session = Net.CreateSession(payload.Address);

            // 发送登录请求到Gate服务器
            var loginResponse = (G2C_LoginResponse)await Net.Call(new C2G_LoginRequest()
            {
                ToKen = response.ToKen
            });
            if (loginResponse.ErrorCode != 0)
            {
                Log.Error($"登录发生错误{loginResponse.ErrorCode}");
                return;
            }


            // var role = Game.Main.AddComponent<Role>(loginResponse.RoleId);
            RoleModel.Instance.Id = loginResponse.RoleId;
            Log.Info($"登录到Gate服务器成功！ErrorCode:{loginResponse.ErrorCode}");
            await RoleModel.Instance.GetRoleInfo();
            Log.Info(
                $"获取角色信息成功！roleId={RoleModel.Instance.Id} Room={RoleModel.Instance.RoomCode} RoleInfo={JsonConvert.SerializeObject(RoleModel.Instance.Info)}");
            //获取背包数据
            await RoleModel.Instance.GetBagInfo();
        }
    }
}