using GameData;
using Game.Player;
using GameDAL.Game;
using MrWu.Debug;
using Server;
using Server.Data;
using Server.DB.Sql;
using Server.MQ;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using ActorCore;
using GameDAL;
using MrWu.Basic;
using GameDAL.FriendRoom;
using GameMessage;
using MrWu.DB;
using NetWorkMessage;
using ObjectModel.Game;
using Server.Config;
using Server.Core;
using Server.DB.Redis;

namespace GlobalSever.Form
{
    public partial class GameTestTable : ServerTable
    {
        /// <summary>
        /// 
        /// </summary>
        public override string tableText => "游戏测试";

        private UILog _uiLog;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="server"></param>
        public GameTestTable(ServerProxy server)
        {
            this.server = server;
            InitializeComponent();
            _uiLog = new UILog(textBox1);
        }

        /// <summary>
        /// 启动
        /// </summary>
        public override void Start()
        {
            GameManager.instance.noCheckAddDesk = checkBox1.Checked;
            base.Start();
        }

        #region 管理

        //同桌测试
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (isStart)
            {
                GameManager.instance.noCheckAddDesk = checkBox1.Checked;
                _uiLog.Debug($"排队同桌测试:{checkBox1.Checked}");
            }
        }

        /// <summary>
        /// 强制下线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button15_Click(object sender, EventArgs e)
        {
            int userId = 0;
            int.TryParse(tirenUserId.Text, out userId);
            if (userId <= 0) return;
            GameMessageManager.Instance.ForceOffLine(userId, true);
        }

        #endregion

        private void button12_Click(object sender, EventArgs e)
        {
            long key = Debug.StartTiming();
            for (int i = 0; i < 10000; i++)
            {
                PlayerDataChange pdc = PlayerDataChange.Create(243630);
                pdc.moneyChange = 10;
                ReferencePool.Recycle(pdc);
            }

            Debug.Info($"加钱耗时:{Debug.GetRunTime(key)}");

            key = Debug.StartTiming();
            for (int i = 0; i < 10000; i++)
            {
                PlayerDataChange pdc = new PlayerDataChange();
                pdc.userid = 243630;
                pdc.moneyChange = 10;
            }

            GC.Collect();
            Debug.Info($"创建耗时:{Debug.GetRunTime(key)}");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            /*
            if (isStart &&  GameManager.instance.tings.Length > 1) {
                textBox2.Text = GameManager.instance.tings[1].ToString();
            }
            */
        }


        private void button17_Click(object sender, EventArgs e)
        {
            try
            {
                int.TryParse(txtRoomid.Text, out var roomid);
                if (roomid <= 0) return;
                var b = GameManager.instance.DeleFriendRoom(roomid, out var msg);
                _uiLog.Debug($"解散桌子结果roomid:{roomid} result:{b} msg:{msg}");
            }
            catch (Exception e1)
            {
                _uiLog.Debug($"解散桌子报错:{e1.Message} {e1.StackTrace}");
            }
        }

        private int[] Text2Array(string value)
        {
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    return Array.Empty<int>();
                }

                string[] values = value.Split(',');
                int[] result = new int[values.Length];
                for (int i = 0; i < values.Length; i++)
                {
                    if (int.TryParse(values[i], out var v))
                    {
                        result[i] = v;
                    }
                }

                return result;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        private void button12_Click_1(object sender, EventArgs e)
        {
            TestManager.Instance.Statics();
        }

        private void button18_Click_1(object sender, EventArgs e)
        {
            TestManager.Instance.ClearData();
        }

        private void button21_Click(object sender, EventArgs e)
        {
            ActivityPropManager.Instance.AddActivityPropData(243633, ActivityPropType.MenPiao, 5);
            Debug.Info($"添加门票!");
        }

        private void button22_Click(object sender, EventArgs e)
        {
            List<ActivityPropData> activityPropDatas =
                ActivityPropManager.Instance.DecActivityPropData(243633, ActivityPropType.MenPiao, 10);
            if (activityPropDatas == null)
            {
                Debug.Error("门票不足!");
            }
            else
            {
                foreach (var data in activityPropDatas)
                {
                    Debug.Info($"消耗门票:{data.PropName} {data.Count}");
                }
            }
        }

        private void button23_Click(object sender, EventArgs e)
        {
            DateTime weekday = ActivityPropDataInfo.GetNowWeekSunDay();
            ActivityPropManager.Instance.AddActivityPropData(243633, ActivityPropType.MenPiao,
                weekday.ToString("yyyyMMdd"), 3);
            Debug.Info("添加上周门票!");
        }

        private void button20_Click(object sender, EventArgs e)
        {
            List<ActivityPropData> datas = ActivityPropManager.Instance.GetActivityPropDatas(243633);
            Debug.Info("得到数据");
            foreach (var data in datas)
            {
                Debug.Info($"id:{data.Id} name:{data.PropName} count:{data.Count}");
            }

            ActivityPropData[] datas1 =
                ActivityPropManager.Instance.GetActivityPropDatas(243633, ActivityPropType.MenPiao);
            Debug.Info("得到门票数据");
            foreach (var data in datas1)
            {
                Debug.Info($"id:{data.Id} name:{data.PropName} count:{data.Count}");
            }
        }

        private void button24_Click(object sender, EventArgs e)
        {
            string key = ActorNetManager.Instance.GetInnerNetKey(new ActorId(11, 0, 0));
            string keyValue = redisManager.db.StringGet(key);
            Debug.Info($"获取到值:{key} {keyValue}");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _uiLog.Clear();
        }

        private bool TryParse()
        {
            TestUserId = 0;
            if (!int.TryParse(textBox2.Text, out TestUserId))
            {
                _uiLog.Debug("userid 格式不正确!");
                return false;
            }

            if (TestUserId < 0)
            {
                _uiLog.Debug("userid 不能为负数!");
                return false;
            }

            TestPropType = 0;
            if (!int.TryParse(textBox5.Text, out TestPropType))
            {
                _uiLog.Debug("道具类型格式不正确!");
                return false;
            }

            if (TestPropType < 0)
            {
                _uiLog.Debug("道具类型不能为负数!");
                return false;
            }

            TestPropNum = 0;
            if (!int.TryParse(textBox3.Text, out TestPropNum))
            {
                _uiLog.Debug("数量格式不正确!");
                return false;
            }

            return true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!TryParse())
            {
                return;
            }

            PropManager.UserPropData userPropData = PropManager.Instance.GetUserPropData(TestPropNum);
            if (TestPropNum < 0)
            {
                if (userPropData.GetPropCount((PropType)TestPropType) + TestPropNum < 0)
                {
                    _uiLog.Debug("道具不足扣除失败!");
                    return;
                }
            }

            userPropData.AddProp((PropType)TestPropType, TestPropNum, "管理添加");
            PropManager.Instance.SaveUserPropDataRedis(userPropData.UserId, false);
            RefreshPropData(userPropData);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            int userid = 0;
            if (!int.TryParse(textBox2.Text, out userid))
            {
                _uiLog.Debug("userid 格式不正确!");
                return;
            }

            if (userid < 0)
            {
                _uiLog.Debug("userid 不能为负数");
                return;
            }

            PropManager.UserPropData userPropData = PropManager.Instance.GetUserPropData(userid);
            RefreshPropData(userPropData);
        }

        private void RefreshPropData(PropManager.UserPropData userPropData)
        {
            StringBuilder stringBuilder = new StringBuilder();

            foreach (var kv in userPropData.PropDic)
            {
                stringBuilder.AppendLine($"{kv.Key,-12} {kv.Value,-12}");
            }

            foreach (var kv in userPropData.PropChangeDic)
            {
                stringBuilder.AppendLine($"Change{kv.Key,-12} {kv.Value,-12}");
            }

            textBox4.Text = stringBuilder.ToString();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TryParse();
            Thread thread = new Thread(ThreadStart);
            thread.Start();
        }

        private int TestUserId;

        private int TestPropType;

        private int TestPropNum;

        private void ThreadStart()
        {
            if (TestUserId <= 0 || TestPropType <= 0 || TestPropNum == 0)
            {
                _uiLog.Debug("开启失败，参数错误!");
                return;
            }

            while (true)
            {
                PropManager.UserPropData userPropData = PropManager.Instance.GetUserPropData(TestUserId);
                userPropData.AddProp((PropType)TestPropType, TestPropNum, "测试添加");
                PropManager.Instance.SaveUserPropDataRedis(userPropData.UserId, false);
                Thread.Sleep(1000);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string wayid = textBox6.Text;
            string roomweiyima = textBox7.Text;
            Desk.SendFightScore(roomweiyima, wayid);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (isChangeing)
            {
                return;
            }

            isPause = false;
            Thread thread = new Thread(FightRecordChange);
            thread.Start();
        }

        private bool isPause = false;

        private bool isChangeing = false;

        private string fileIds = "fileid.txt";

        private void FightRecordChange()
        {
            //找到最早一个id

            isChangeing = true;

            int currentId = 0;
            if (File.Exists(fileIds))
            {
                string idx = File.ReadAllText(fileIds);
                if (!int.TryParse(idx, out currentId))
                {
                    currentId = 0;
                }
            }

            string weiyima = string.Empty;

            while (true)
            {
                try
                {
                    try
                    {
                        string sql = @$"SELECT *
FROM club_FightRecord
WHERE weiyima = (
    SELECT TOP (1) weiyima
    FROM club_FightRecord
    WHERE id > {currentId}
      AND weiyima <> '{weiyima}'
      AND endtime > '2026-03-11 08:00:00'
) ORDER BY id ASC;";
                        
                        DataSet ds = new DataSet();
                        GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
                        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            if (!ChangeFightRecord(ds, ref weiyima,ref currentId))
                            {
                                _uiLog.Debug("写入中断!");
                                File.WriteAllText(fileIds, currentId.ToString());
                                break;
                            }
                            _uiLog.Debug($"转换完成:{currentId} {weiyima}");
                            //查相同的唯一码
                            // currentId = (int)ds.Tables[0].Rows[0]["id"];
                            // weiyima = ds.Tables[0].Rows[0]["weiyima"].ToString();
                        }
                        else
                        {
                            _uiLog.Debug($"转换结束");
                            File.WriteAllText(fileIds, currentId.ToString());
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.Error($"转换出错:{e.Message}");
                    }

                    if (isPause)
                    {
                        File.WriteAllText(fileIds, currentId.ToString());
                        break;
                    }

                    Thread.Sleep(1000);
                }
                catch (Exception e)
                {
                    _uiLog.Debug($"执行报错:{e.Message}");
                    break;
                }
            }


            //处理完就保存

            isChangeing = false;
        }

        private bool isExisClubFightRecord(string weiyima)
        {
            string sql = $"select * from ClubFightRecord where weiyima = '{weiyima}'";
            DataSet ds = new DataSet();
            GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
            return ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0;
        }

        private const string ClubRecordMapSql =
            @"insert into ClubRecordMap(ClubId,Weiyima,FightTime)
			            values(@clubId,@weiyima,@fightTime);";

        private const string ClubUserRecordMapSql =
            @"insert into ClubUserRecordMap(ClubId,UserId,Weiyima,FightTime)
			            values(@clubId,@userId,@weiyima,@fightTime);";

        private const string clubRecordSql =
            @"insert into ClubFightRecord(wayid,weiyima,gameserid,roomnum,warcnt,startTime,endtime,scores,CardNum,style)
			            values(@wayid,@weiyima,@gameserid,@roomnum,@warcnt,@startTime,@endtime,@Scores,@CardNum,@style);";

        private bool ChangeFightRecord(DataSet ds,ref string weiyima,ref int currentId)
        {
            if (ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
            {
                _uiLog.Debug($"没有找到战绩:");
                return false;
            }

            HashSet<int> clubids = new HashSet<int>();
            foreach (DataRow item in ds.Tables[0].Rows)
            {
                clubids.Add((int)item["clubid"]);
                //必须比我当前的id大
                
            }

            foreach (DataRow item in ds.Tables[0].Rows)
            {
                int nowCurrentId = (int)item["id"];
                if (nowCurrentId > currentId)
                {
                    currentId = nowCurrentId;
                    break;
                }
            }

            DataRow row = ds.Tables[0].Rows[0];
            weiyima = row["weiyima"].ToString();
            if (isExisClubFightRecord(weiyima))
            {
                _uiLog.Debug($"存在战绩:{weiyima} {currentId}");
                return true;
            }
            
            
            int roomnum = (int)row["roomnum"];
            int warCnt = (int)row["warcnt"];
            string wayid = row["wayid"].ToString(); //未使用
            int game_serid = (int)row["gameserid"];
            string json = row["scores"].ToString();
            FightScore.Player[] scores = JsonPack.GetData<FightScore.Player[]>(json);
            DateTime startTime = DateTime.Parse(row["startTime"].ToString());
            DateTime endTime = DateTime.Parse(row["endtime"].ToString());
            int cardNum = 0;
            int style = 0;
            if (row["CardNum"] != DBNull.Value)
            {
                cardNum = (int)row["CardNum"];
            }

            if (row["style"] != DBNull.Value)
            {
                style = (short)row["style"];
            }

            return true;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            isPause = true;
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            throw new System.NotImplementedException();
        }

        private int rpctestId = 0;

        private async void button6_Click_2(object sender, EventArgs e)
        {
            MainActor mainActor = ActorManager.Instance.Get(ActorTypeId.Main) as MainActor;

            if (mainActor == null)
            {
                _uiLog.Debug("MainActor is null");
                return;
            }

            byte moduleId = 0;
            if (!byte.TryParse(textBox8.Text,out moduleId))
            {
                _uiLog.Debug("请输入正确的moduleId");
            }

            rpctestId++;
            
            ActorId actorId = new ActorId(moduleId, 0, ActorTypeId.Main);
            _uiLog.Debug($"发送的rpcId:{rpctestId}");
            try
            {
                RpcTestResponse rpcTestResponse = (RpcTestResponse)await mainActor.Call(actorId,RpcTestRequest.Create(rpctestId));
                
                _uiLog.Debug($"响应值:{rpcTestResponse.Id} {rpcTestResponse.Message} {rpcTestResponse.Error}");
            }
            catch (Exception exception)
            {
                _uiLog.Debug($"RPC调用出错:{exception}");
            }
            
           
        }
    }
}