using Server.Pack;
using Server.Data;
using GameData;
using MrWu.Debug;
using Game.Player;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using GameDAL.FriendRoom;
using Server.Core;
using GameMessage;

namespace Server
{
    /// <summary>
    /// 朋友房管理
    /// </summary>
    public partial class FriendRoomManager
    {
        /// <summary>
        /// 处理加入到某个朋友房的桌子
        /// </summary>
        public class DoJoinFriendRoom
        {
            /// <summary>
            /// 是否加入成功
            /// </summary>
            public bool result;

            /// <summary>
            /// 如果加入失败，失败提示
            /// </summary>
            public string errinfo;

            /// <summary>
            /// 错误码
            /// </summary>
            public int errorCode;

            /// <summary>
            /// 房间所在的模块,当房间不在本模块时有值
            /// </summary>
            public ServerNode desknode;

            /// <summary>
            /// 包头
            /// </summary>
            public readonly PackHead head;

            /// <summary>
            /// 加入房间的包裹
            /// </summary>
            public readonly JoinRoom jpk;

            /// <summary>
            /// 如果是竞技比赛房间,是否要询问,竞技比赛该玩家可不可以加入该房间
            /// </summary>
            public readonly bool checkClub;

            /// <summary>
            /// 是否自动进入房间
            /// </summary>
            public readonly bool isAuto;

            /// <summary>
            /// 是否是竞技比赛
            /// </summary>
            public readonly bool isClub;

            /// <summary>
            /// 玩家所在俱乐部
            /// </summary>
            public int ClubId;

            /// <summary>
            /// 玩家的俱乐部分数
            /// </summary>
            public double Score;

            public bool IsTestPack;

            public List<int> SeatmateLimitList;
            
            /// <summary>
            /// 处理朋友房的加入
            /// </summary>
            /// <param name="head">包头</param>
            /// <param name="jpk">包</param>
            /// <param name="checkClub">检查竞技比赛</param>
            /// <param name="jfr"></param>
            /// <param name="isClub"></param>
            public DoJoinFriendRoom(PackHead head, JoinRoom jpk, JoinFriendRoom jfr, bool checkClub = false,
                bool isClub = false)
            {
                this.head = head;
                this.jpk = jpk;
                this.checkClub = checkClub;
                this.isAuto = jfr == null ? false : jfr.isAuto == 1;
                this.isClub = isClub;
                this.ClubId = jfr == null ? 0 : jfr.ClubId;
                this.Score = jfr == null ? 0 : jfr.Score;
                SeatmateLimitList = jfr?.SeatmateLimitList ?? new List<int>();
            }

            /// <summary>
            /// 没有这个房间的处理
            /// </summary>
            void NoDesk(string weiyima, int roomnum)
            {
                this.result = false;
                errinfo = "无此房间，请重试!";
                errorCode = MessageErrCode.ClubJoinDeskNotDesk;
                /*
                if (!isAuto)
                {
                    Debug.Error("无此房间号:" + weiyima + "," + roomnum + "," + isClub);
                    //没有这个房间号
                    SendManager.SendErrorInfo_Socket(head.userid, 0, 4, head.GetModuleUtil());
                }
                else
                {
                    Debug.Warning("自动进入，进不去,退出游戏!");
                    var tmp = PlayerCollection.instance.FindPlayer_Userid(head.userid);
                    if (tmp == null)
                    {
                        Debug.Error("玩家加入房间时 -找不到玩家:" + tmp.userid);
                    }
                    else
                        GameManager.instance.QuitGame(tmp, "NoDesk");
                }
                */
            }

            void InDesk()
            {
                PlayerDataAsyc pl = PlayerCollection.Instance.FindPlayerByUserId(head.userid);
                if (pl == null)
                {
                    result = false;
                    errinfo = "请求失败,请稍后再试!";
                    Debug.Error("服务器错误登录了却没找到人:" + head.userid);
                    PlayerFun.UnLockPlayer(head.userid, GameBase.instance.myUtil, false);
                    return;
                }

                int rmnum;
                pl.ClubId = this.ClubId;
                pl.ClubScore = this.Score;
                if (int.TryParse(jpk.roomNum, out rmnum)
                    && instance.ting.InTing(pl, instance.room.id, ref errinfo, ref errorCode,rmnum, jpk.pwd, isClub))
                {
                    Desk dsk = instance.FindDesk(pl.friendRoomNum);
                    if (dsk == null)
                    {
                        Debug.Error("服务器错误!dsk not find");
                    }
                    else
                    {
                        dsk.SendPlayersinfo(2, pl.userid, pl.nickname);
                    }

                    result = true;

                    #if DEBUG
                    pl.IsTest = IsTestPack;
                    #endif
                }
                else
                {
                    Debug.Error($"InTing Error errorCode:{errorCode} errinfo:{errinfo}");
                    result = false;
                    GameManager.instance.QuitGame(pl, "InDesk", false);
                }
            }

            /// <summary>
            /// 开始处理
            /// </summary>
            /// <returns></returns>
            public async Task Start()
            {
                if (this.jpk == null)
                {
                    Debug.Error("客户端发包错误!");
                    this.result = false;
                    errinfo = "请求失败！";
                    errorCode = MessageErrCode.ClubJoinDeskUnknow;
                    return;
                }

                int roomnum;
                if (!int.TryParse(jpk.roomNum, out roomnum))
                {
                    Debug.Warning("房间号不是数字:" + jpk.roomNum);
                    this.result = false;
                    errinfo = "请求失败!";
                    errorCode = MessageErrCode.ClubJoinDeskNumError;
                    return;
                }

                var desk = instance.FindDesk(int.Parse(jpk.roomNum));
                if ((!isClub && desk != null && desk.deskinfo != null && desk.deskinfo.creatStyle == 5))
                {
                    Debug.Warning("房间号无效，加入失败!");
                    //xu add 修改玩家输入房号不能加入俱乐部的桌子 2021年1月5日
                    result = false;
                    errinfo = "房间号无效，加入失败！";
                    errorCode = MessageErrCode.ClubJoinDeskNumError;
                    return;
                }

                if (isClub)
                {
                    /*
                     * 0731 --over
                     * 上次写了一个脚本，里面有个方法是检查玩家是否属于禁止同桌的组
                     * 这里调用下，如果不能加入
                     * 则运行下面这段代码
                     * result = false;
                       errinfo = "反作弊检查，禁止加入房间!";
                       yield break;
                     *
                     *
                     * */
                    if (desk != null && desk.deskinfo != null && desk.deskinfo.creatStyle == 5)
                    {
                        int[] user = new int[desk.deskinfo.nowPlayerCnt];
                        int idx = 0;
                        for (int i = 0; i < desk.deskinfo.pls.Length; i++)
                        {
                            if (desk.deskinfo.pls[i] != null)
                            {
                                user[idx++] = desk.deskinfo.pls[i].userid;
                            }
                        }

                        if (!ClubSeatmate.CheckSeatmate(SeatmateLimitList, user))
                        {
                            Debug.Warning("反作弊检查，禁止加入房间!");
                            result = false;
                            errinfo = "反作弊检查，禁止加入房间!";
                            errorCode = MessageErrCode.ClubJoinDeskNotAllowed;
                            return;
                        }
                    }

                    if (checkClub)
                    {
                        //如果要检查玩家是否可以加入该竞技比赛房间
                        //检查之后再回来

                        if (desk != null && desk.deskinfo != null && desk.deskinfo.creatStyle == 5)
                        {
                            //竞技比赛房间房间
                            CheckClub checkclub = new CheckClub(head.userid, desk.deskinfo.creatUserid);
                            await checkclub.Start();
                            if (!checkclub.result)
                            {
                                Debug.Warning("禁止加入房间!");
                                result = false;
                                errinfo = checkclub.errinfo;
                                errorCode = MessageErrCode.ClubJoinDeskNotAllowed;
                                return;
                            }
                        }
                    }
                }

                string weiyima = null;
                ServerNode node = null;

                //没有这个房间
                if (!Room.GetWeiyima(roomnum, ref weiyima, ref node))
                {
                    Debug.Warning("没有这个房间!");
                    NoDesk(weiyima, roomnum);
                }
                else
                {
                    //有这个房间
                    if (GlobalManager.instance.myUtil.Equals(node))
                    {
                        LoginInfo loginInfo = LoginInfo.Create(head.userid, true, head.GetUtil(), head.ip,jpk.deviceinfo,head.clientVer,head);
                        await LoginManager.Instance.Start(loginInfo);

                        bool result = loginInfo.Result;
                        loginInfo.Dispose();
                        loginInfo = null;
                        //登录成功
                        if (result)
                        {
                            Debug.Info($"加入桌子:{roomnum}");
                            InDesk();
                        }
                        else
                        {
                            Debug.Warning($"请求失败，请稍后再试!");
                            result = false;
                            errorCode = MessageErrCode.ClubJoinDeskUnknow;
                            //errinfo = "请求失败,请稍后再试!";
                        }


                        /*
                        bool isLogin = isAuto;
                        if (!isLogin)
                        {
                            GameManager.Login login = new GameManager.Login(head.userid, true, head.GetModuleUtil(), head.ip, jpk.deviceinfo, head.clientVer);
                            yield return login.Start();
                            isLogin = login.result;
                        }
                        //本模块的房间
                        if (isLogin)
                        {//登录成功
                            InDesk();
                        }
                        else
                        {

                        }
                        */
                    }
                    else
                    {
                        Debug.Log("kkkkk");
                        result = false;
                        desknode = node;

                        /*
                        //其他模块的房间 RPC 去配置模块拿游戏名称，发送给客户端..
                        if (isAuto)
                        {
                            Debug.Error("怎么可能，自动进入的房间怎么会是其他模块管理的!");
                            yield break;
                        }
                        bool isDie = ServerHeart.instanece.IsDie(node.id, node.nodeNum);
                        Coroutine.StartCoroutine(instance.SendGameTip(head, isDie, node.id));
                        */
                    }
                }

                return;
            }
        }
    }
}