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

namespace Server
{
    /// <summary>
    /// 朋友房管理
    /// </summary>
    public partial class FriendRoomManager
    {
        /// <summary>
        /// 创建朋友房
        /// </summary>
        public class CreateRoom
        {
            /// <summary>
            /// 包头
            /// </summary>
            public readonly PackHead head;

            public readonly bool isClub;

            /// <summary>
            /// 创建id
            /// </summary>
            public readonly int createid;

            /// <summary>
            /// 创建房间包
            /// </summary>
            public readonly CreateRoomPack crp;

            /// <summary>
            /// 是否检测正在处理
            /// </summary>
            public readonly bool isCheckDoing;
            
            /// <summary>
            /// 游戏配置
            /// </summary>
            public Server.Config.GameConfig config
            {
                get { return GameManager.instance.config; }
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="head"></param>
            /// <param name="createid"></param>
            /// <param name="crp"></param>
            /// <param name="isCheckDoing"></param>
            public CreateRoom(PackHead head, int createid, CreateRoomPack crp, bool isClub,bool isCheckDoing)
            {
                this.head = head;
                this.createid = createid;
                this.crp = crp;
                this.isClub = isClub;
                this.isCheckDoing = isCheckDoing;
            }

            ///
            public async Task Start()
            {
                /*
             * 创建房间要满足的条件
             * 1.没在游戏中,
             * (被锁信息,房间号信息,)
             * 2.房间号足够,房卡足够。
             * 3.规则正确
             * 4.本游戏开启了朋友房的设置
             * 5.服务器支持到的客户端版本。
             * */

                int userid = head.userid;
                if (isCheckDoing && DoingUserIds.Contains(userid))
                {
                    Debug.Error($"正在处理别的事务:{head.userid}");
                    GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskDoing);
                    return;
                }
                try
                {
                    if (isCheckDoing)
                    {
                        DoingUserIds.Add(userid);
                    }

                    //房间数据
                    var data = crp.deskinfo;

                    //得到房间号
                    int roomnum = int.Parse(data.roomNum);
                    if (roomnum <= 0 || roomnum > Room.MaxCnt)
                    {
                        Debug.Error("房间号越界,不应该出现的情况!!!");
                        GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskUnknow);
                        return;
                    }

                    Debug.Log("创建房间:" + crp.deskinfo.rule.interceptpos);
                    //赋值强制解散时间
                    data.wartimeOutDis = DateTime.Now.AddHours(config.FriendDeskWarTimeOut);
                    data.jointimeOutDis = DateTime.Now.AddMinutes(config.FriendStarWarTimeOut);

                    if (!instance.ting.CheckFriendGz(data.rule.roomrule))
                    {
                        //检查规则是否可以创建

                        Debug.Error("创建朋友房规则错误!");
                        if (!isClub)
                            GeneralSendPack.SendErrorInfo_Socket(createid, 2, 20, head.GetUtil());
                        else
                            SendManager.SendErrotInfo_Http(head, 2, 20);
                        
                        GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskWayRuleError);
                        return;
                    }

                    Debug.Info("创建房间:" + roomnum);
                    //如果是玩家开房间
                    //1.普通开房间  需先登录
                    // Debug.Info("普通开房间!");

                    /* 这个ip 不准，先不处理
                    if (string.IsNullOrEmpty(head.ip))
                    {
                        Debug.Error("玩家创建房间时，玩家的ip 是空!!!");
                    }
                    */

                    //玩家登录,

                    bool isCreate = crp.isAuto == 1;
                    Debug.Info($"isCreate:{isCreate}");
                    if (!isCreate)
                    {
                        PlayerDataAsyc pl = PlayerCollection.Instance.FindPlayerByUserId(head.userid);

                        if (pl == null)
                        {
                            Debug.Info("Create Pl null!");
                            LoginInfo loginInfo = LoginInfo.Create(head.userid, true, head.GetUtil(), head.ip,
                                crp.deviceInfo, head.clientVer, head);
                            await LoginManager.Instance.Start(loginInfo);
                            isCreate = loginInfo.Result;
                            loginInfo.Dispose();
                        }
                        else
                        {
                            Debug.Info("Create Pl is not null!");
                            //把锁纠正
                            if (pl.state != (int)PlayerState.INGame)
                            {
                                Debug.Error("状态不是在游戏中，不能创建朋友房!");
                                GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskUnknow);
                                return;
                            }

                           PlayerLockInfo lockInfo =  PlayerFun.GetPlayerLockInfo(pl.userid);
                           if (!GameBase.instance.myUtil.Equals(lockInfo.util)) //不是锁在本模块
                           {
                               GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskInOtherGame);
                               return;
                           }

                           //不是锁在朋友房,要改成朋友房
                           if (!lockInfo.isFriend)
                           {
                               lockInfo.isFriend = true;

                               if (!PlayerFun.EditorLockPlayer(pl.userid,lockInfo))
                               {
                                   Debug.Error("修改锁失败!");
                                   //没有修改成功，那么这个用户可能已经下线了，不处理
                                   GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskUnknow);
                                   return;
                               }
                               Debug.Error("修改锁成功，继续创建朋友房!");
                           }
                           
                            isCreate = true;
                        }
                        //Debug.Log($"是否登录成功:{isCreate}");
                    }

                    //Debug.Log($"-isCreate:{isCreate}");
                    if (isCreate)
                    {
                        Debug.Info("开始创建!");
                        
                        PlayerDataAsyc pl = PlayerCollection.Instance.FindPlayerByUserId(head.userid);
                        if (pl == null)
                        {
                            Debug.Error("登陆成功却未获得玩家数据!" + head.userid);
                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskUnknow);
                            return;
                        }

                        if (pl.friendRoomNum > 0)
                        {
                            Debug.Error($"已经在朋友房，怎么还来创建桌子!{head.userid},{pl.friendRoomNum}");
                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskUnknow);
                            return;
                        }

                        pl.ClubId = this.crp.ClubId;
                        pl.ClubScore = this.crp.Score;
                        #if DEBUG
                        pl.IsTest = this.crp.IsTestPack;
                        #endif
                        if (data.rule.RuleEx == null)
                        {
                            data.rule.RuleEx = new DeskRuleEx();
                        }

                        //登陆成功
                        data.fangka =
                            data.rule.RuleEx
                                .CreateRoomCardNum; // data.rule.warCnt / GameManager.instance.config.cardPan;
                        bool r = true;

                        int checkResult = instance.ting.CheckDeskInfo(pl, data);

                        //Debug.Log("555555");
                        Debug.Info($"检查结果:{checkResult}");
                        if (checkResult == 1)
                        {
                            //可以创建
                            data.Init(ServerConfigManager.Instance.MaxVer);
                            Debug.Info("毫秒值:" + data.CreateTime.Millisecond);
                            Debug.Log("可以创建!");

                            if (data.creatStyle != 5)
                                data.creatUserid = pl.userid;

                            if (Room.CreateRoom(data, GameBase.instance.myUtil))
                            {
                                //先处理redis数据
                                Debug.Info("redis数据处理成功!");

                                //纠正被锁信息
                                
                                if (data.creatStyle == 5)
                                {
                                    if (string.IsNullOrEmpty(data.weiyima))
                                        Debug.Error("创建的玩法唯一码竟然是空!!!");
                                    //保存桌子信息

                                    WayManager.instance.SaveWayDesk(data.creatUserid, data.wayid, data.weiyima);
                                    Debug.Log("--------新增桌子!");
                                    WayManager.instance.WayDeskChangeSend(data.creatUserid, data.wayid, data.weiyima,
                                        0);
                                    //WayRoom.instance.Add(data.creatUserid, data.wayid, data.weiyima.ToString());
                                }

                                Debug.Info($"创建房间之前的房卡数据:{pl.fangka}   cccddd:{pl.ClubId}");
                                string errinfo = string.Empty;
                                int errorCode = 0; //错误码
                                if (instance.CreateDesk(pl, data, ref errinfo,ref errorCode) == 1)
                                {
                                    //处理内存
                                    r = true; //扣除房卡
                                    if (isClub)
                                    {
                                        GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.Success);
                                        if (crp.TaskId <= 0)
                                        {
                                            head.transfer = ServerPackAgreement.ReConnection;
                                            head.packlx = ServerPackAgreement.TransFerHttp;
                                            head.otherInt = new int[] { ServerConfigManager.Instance.ClientId };
                                            GlobalMQ.instance.DeliveryOne(head.GetUtil(),
                                                GlobalMQ.CreateMessage(head, null), true);
                                        }
                                    }
                                }
                                else
                                {
                                    //创建出错!
                                    
                                    Debug.Error("创建房间出现问题....房卡数据....");
                                    //清空被占用的数据
                                    Room.DeleteRoom(data);
                                    //没成功就要把桌子信息删除
                                    Debug.Error("桌子删除!!!");
                                    if (isClub)
                                    {
                                        WayManager.instance.DelDeskInfo(data.creatUserid, data.wayid, data.weiyima);
                                        WayManager.instance.WayDeskChangeSend(data.creatUserid, data.wayid,
                                            data.weiyima, 1);
                                    }
                                    
                                    if (crp.isAuto != 1)
                                    {
                                        if (crp.TaskId <= 0)
                                        {
                                            if (string.IsNullOrEmpty(errinfo))
                                            {
                                                if (!isClub)
                                                    GeneralSendPack.SendErrorInfo_Socket(pl.userid, 2, 24, pl.socketUtil);
                                                else
                                                    SendManager.SendErrotInfo_Http(head, 2, 24);
                                            }
                                            else
                                            {
                                                if (!isClub)
                                                    GeneralSendPack.SendErrorInfo_Socket(pl.userid, 2, errinfo, pl.socketUtil);
                                                else
                                                    SendManager.SendErrotInfo_Http(head, 2, errinfo);
                                            }
                                        }
                                        else
                                        {
                                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,errorCode);
                                        }
                                    }

                                    r = false;
                                    //玩家 进入失败,清空房间数据
                                    //房卡返还
                                    
                                }
                            }
                            else
                            {
                                if (crp.isAuto != 1)
                                {
                                    if (crp.TaskId <= 0)
                                    {
                                        if (!isClub)
                                            GeneralSendPack.SendErrorInfo_Socket(pl.userid, 2, 24, pl.socketUtil);
                                        else
                                            SendManager.SendErrotInfo_Http(head, 2, 24);
                                    }
                                    else
                                    {
                                        GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskUnknow);
                                    }
                                }

                                r = false;
                            }
                        }
                        else
                        {
                            SendTip(pl.userid, pl.socketUtil, crp.isAuto != 1, checkResult);
                            r = false;
                        }

                        if (!r)
                        {
                            // 创建失败 退出游戏
                            GameManager.instance.QuitGame(pl, "CreateFail", false);
                        }
                    }
                }
                finally
                {
                    if(isCheckDoing)
                    {
                        DoingUserIds.Remove(userid);
                    }
                }
            }

            /// <summary>
            /// 发送提示
            /// </summary>
            private void SendTip(int userid, ServerNode socket, bool isError, int type)
            {
                //if (isError) {
                //    SendManager.SendErrorInfo_Socket(userid, 2, 60, socket);
                //} else {
                //-4,-5逻辑问题 - 6房卡不足创建失败 - 7未检测到ip - 8必须微信登录或绑定 - 9 必须微信绑定 - 10没有定位信息 - 11没有设备信息
                switch (type)
                {
                    case -4:
                    case -5:
                        if (crp.TaskId <= 0)
                        {
                            if (!isClub)
                                //创建失败,请稍后再试!
                                GeneralSendPack.SendErrorInfo_Socket(userid, 2, 24, socket);
                            else
                                SendManager.SendErrotInfo_Http(head, 2, 24);
                        }
                        else
                        {
                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskUnknow);
                        }
                        break;
                    case -6:
                        if (crp.TaskId <= 0)
                        {
                            if (!isClub)
                                //房卡不足
                                GeneralSendPack.SendErrorInfo_Socket(userid, 2, 21, socket);
                            else
                                SendManager.SendErrotInfo_Http(head, 2, 24);
                        }
                        else
                        {
                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskCardNotEnough);
                        }
                        break;
                    case -7:
                        if (crp.TaskId <= 0)
                        {
                            if (!isClub)
                                //未检测到ip
                                GeneralSendPack.SendErrorInfo_Socket(userid, 2, 56, socket);
                            else
                                SendManager.SendErrotInfo_Http(head, 2, 56);
                        }
                        else
                        {
                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskIpEmpty);
                        }
                        break;
                    case -8:
                    case -9:
                        if (crp.TaskId <= 0)
                        {
                            if (!isClub)
                                //微信用户才可创建!
                                GeneralSendPack.SendErrorInfo_Socket(userid, 2, 57, socket);
                            else
                                SendManager.SendErrotInfo_Http(head, 2, 57);
                        }
                        else
                        {
                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskNotWeChatAccount);
                        }

                        break;
                    case -10: //没有定位信息
                        if (crp.TaskId <= 0)
                        {
                            if (!isClub)
                                GeneralSendPack.SendErrorInfo_Socket(userid, 2, 58, socket);
                            else
                                SendManager.SendErrotInfo_Http(head, 2, 58);
                        }
                        else
                        {
                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskNotPosition);
                        }
                        break;
                    case -11: //没有设备信息
                        if (crp.TaskId<= 0)
                        {
                            if (!isClub)
                                GeneralSendPack.SendErrorInfo_Socket(userid, 2, 59, socket);
                            else
                                SendManager.SendErrotInfo_Http(head, 2, 59);
                        }
                        else
                        {
                            GeneralSendPack.SendJoinDeskResult(crp.TaskId,MessageErrCode.ClubJoinDeskImeiEmpty);
                        }
                        break;
                    default:
                        Debug.ImportantLog($"创建房间失败，未解析的错误码：{type}");
                        break;
                }
                //}
            }
        }
    }
}