/********************************
 *
 * 作者:徐高庆
 * 创建时间: 2024年5月27日15:05:28
 * 
 ********************************/
using GameData;
using MrWu.Debug;
using PdkFriendServer.Logic;
using Server;
using Server.Pack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MessagePack;

using GameMessage.PaoDeKuaiF;
using Server.Core;
using Server.Data;
using MessageHelper = Server.MessageHelper;

namespace PdkFriendServer.GlobalManager
{
    public class PdkGameDo : GameDo
    {
        /// <summary>
        /// 跑得快朋友房主要逻辑
        /// </summary>
        PdkGameMain Main;

        /// <summary>
        /// 计时器
        /// </summary>
        int timeNum;

        public Desk desk = null;

        public PdkGameDo(Desk desk) : base(desk)
        {
            Main = new PdkGameMain(this);
            this.desk = desk;
        }

        public override void DoZyxPack(GamePack data)
        {

            PdkLogicInfo logicInfo;
            if (data.IsBinary)
            {
                logicInfo = MessagePackHelper.Deserialize<PdkLogicInfo>(data.Data);
            }
            else
            {
                if (data.JsonData.Length < 10)
                { //托管包
                    byte[] tgData = JsonPack.GetData<byte[]>(data.JsonData);
                    Debug.Info("收到托管包" + data.JsonData.Length);
                    if (tgData[1] == 0)
                    {
                        Main.GamePack.Info.PlayTuoGauan[tgData[0]] = tgData[1];
                        desk[tgData[0]].SetDeposit( tgData[1] == 1 ? true : false);
                    }
                    return;
                }
                
                logicInfo = JsonPack.GetData<PdkLogicInfo>(data.JsonData);
            }
            
            var b = Main.CheckPack(logicInfo);
            if (!b)
            {
                Debug.Warning("客户端包内容检查不过。收包错误");
                return;
            }
            
            //正式连客户端以后要屏蔽这些代码。return
            switch (Main.GamePack.Info.GameZT) //只要客户端输入的值
            {
                case 3://包庄
                    Main.GamePack.Info.BaoZhuang[logicInfo.WhoPlay - 1] = logicInfo.BaoZhuang[logicInfo.WhoPlay - 1];
                    break;
                case 4: //打牌
                    Main.GamePack.Info.ActivePlayCard = logicInfo.ActivePlayCard;
                    Main.TimeNum = 0; //重置time计时器
                    break;
            }
            Debug.Info("收到子游戏包GameDo!");
            this.Main.GameDo();
        }

        public override void StartWar()
        {
            timeNum = 0;
            base.StartWar();
            Main.GameStart();
        }

        public void SendGamePack()
        {
            var str = JsonPack.GetJson(Main.GamePack);
            int len = desk.Count;
            PlayerDataAsyc tmppl;
            
            byte[] data = MessageHelper.MessagePackSerialize(this.Main.GamePack);
            for (int i = 0; i < Main.GamePack.Info.PlayNum; i++)
            {
                tmppl = desk[i];
                if (tmppl==null||tmppl.isRobot)continue;
                if (tmppl.ClientVer > 46)
                {
                    ClearOtherCard(tmppl.seat, data,false);
                }
                else
                {
                    byte[] datastr= Encoding.UTF8.GetBytes(str);
                    ClearOtherCard(tmppl.seat, datastr,true);
                }
            }
            
            SaveGameData(data);
            SaveHuiFang(0, str);
        }

        /// <summary>
        /// 发包前清空不是自己手里的牌
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="packData"></param>
        void ClearOtherCard(int pos, byte[] packData,bool isOld)
        {            
            try
            {
                if (Main.GamePack.Info.OverPos > 0)
                {//如果是游戏结束的话就不清空玩家牌了，因为最后要亮玩家手牌
                    SendPack(pos, packData);
                    return;
                }
                var pack = isOld ? JsonPack.GetData<PdkGamePack>(Encoding.UTF8.GetString(packData)) 
                    : MessagePackHelper.Deserialize<PdkGamePack>(packData);
                for (int i = 0; i < Main.GamePack.Info.PlayNum; i++)
                {
                    if (i == pos) continue;
                    for (int j = 0; j < pack.CardPack.Cards[i].CardInfos.Length; j++)
                    {
                        if (pack.CardPack.Cards[i].CardInfos[j].GameState == 0) continue; //打下去的牌不清空
                        pack.CardPack.Cards[i].CardInfos[j] = new TCardInfoPdkF();
                    }
                }
                //var str = JsonPack.GetJson(pack);
                SendPack(pos, packData);
            }
            catch (Exception e)
            {
                Debug.Error($"发包前清空不是自己手里的牌,msg:{e.Message} code:{e.StackTrace}");
                SendPack(pos, packData);
            }
        }

        public void SaveGameData(byte[] data)
        {
            SaveData(data);
        }

        public override void LoadMem(byte[] data,bool isOld)
        {
            Main.SetFriendGz();
            if (isOld)
            {
                Main.GamePack = JsonPack.GetData<PdkGamePack>(Encoding.UTF8.GetString(data));
            }
            else
            {
                Main.GamePack = MessageHelper.MessagePackDeserialize<PdkGamePack>(data);
            }
            Main.LoadInit();

        }

        public override void LoadMemSuccess()
        {
            Main.SetOperation();
        }

        public void GameOver()
        {
            for (int i = 0; i < Main.GamePack.Info.PlayNum; i++)
            {
                var num = Main.GamePack.Info.Score[i];
                SetPlayer(i, 8, num, string.Empty);
            }
            SendGamePack();
            WarOver();
        }

        public override void Reconnect(int seat)
        {
            if (seat < 0)
            {
                int len = desk.Count;
                PlayerDataAsyc tmppl;
                byte[] data = MessagePackHelper.Serialize(this.Main.GamePack);
                for (int i = 0; i < len; i++)
                {
                    tmppl= desk[i];
                    if(tmppl==null||tmppl.isRobot)continue;
                    if (desk[seat].ClientVer > 46)
                    {
                        // 新客户端 MessagePack
                        ClearOtherCard(seat, data,false);
                    }
                    else
                    {
                        // 老的客户端 Encding
                        byte[] datastr= Encoding.UTF8.GetBytes(JsonPack.GetJson(this.Main.GamePack));
                        ClearOtherCard(seat, datastr,true);
                    }
                }
            }else if(seat < desk.PlayerCnt)
            {
                if (desk[seat] == null)
                {
                    Debug.Error("逻辑错误!------{0},PlayerCnt:{1}", seat, desk.PlayerCnt);
                    return;
                }
            
                byte[] data = MessagePackHelper.Serialize(this.Main.GamePack);
                if (!desk[seat].isRobot)
                {
                    if (desk[seat].ClientVer > 46)
                    {
                        // 新客户端 MessagePack
                        ClearOtherCard(seat, data,false);
                    }
                    else
                    {
                        // 老的客户端 Encding
                        byte[] datastr= Encoding.UTF8.GetBytes(JsonPack.GetJson(this.Main.GamePack));
                        ClearOtherCard(seat, datastr,true);
                    }
                }
            }
            else
            {
                Debug.Warning("发包位置大于桌子人数!" + seat + "," + desk.PlayerCnt);
            }

        }

        public override void OnTime(int interval)
        {
            //200毫秒一次，一秒执行5次          
            timeNum++;
            if (timeNum >= 5)
            {
                timeNum = 0;
                this.Main.DoTime();
            }
        }


        public override void WarOver()
        {
            desk.WarOver();
            isFighting = false;
        }

        public Desk GetDesk()
        {
            return this.desk;
        }
    }
}
