using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using GlobalSever.Form;
using MrWu.Debug;
using Server;

namespace GlobalSever.Form
{
    public partial class PlayerLuckTable : ServerTable
    {
        public override string tableText => "幸运玩家";

        public PlayerLuckTable(ServerProxy server)
        {
            this.server = server;
            InitializeComponent();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            string wayId = textBox1.Text;
            if (int.TryParse(textBox2.Text, out int userid))
            {
                string info = LuckPlayerManager.Instance.GetPlayerInfo(wayId, userid);
                textBox3.Text = info;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(Run);
            thread.Start();
        }


        private int[] userids = new int[] { 243601, 243602, 243603, 243604 };

        private void Run()
        {
            FileStream fileStream = new FileStream("fightscoredata.txt", FileMode.Open);
            StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8);

            string wayId = "2a1651c3a1s3d1sa231";
            int fightCnt = 8;
            int fightCntIndex = 0;
            LuckPlayerManager.FightScore[] fightScores = new LuckPlayerManager.FightScore[4];
            for (int i = 0; i < fightScores.Length; i++)
            {
                fightScores[i] = new LuckPlayerManager.FightScore()
                {
                    UserId = userids[i],
                    Value = 0
                };
            }

            StringBuilder stringBuilder = new StringBuilder();

            while (true)
            {
                stringBuilder.Clear();
                string line = streamReader.ReadLine();
                if (line == null)
                {
                    break;
                }

                fightCntIndex++;
                string[] values = line.Split(',');
                int[] scores = new int[4];
                stringBuilder.Append($"原始分数 ");
                for (int i = 0; i < values.Length; i++)
                {
                    scores[i] = int.Parse(values[i]);
                    stringBuilder.Append($"{i}:{scores[i]} ");
                }

                Debug.Info(stringBuilder.ToString());

                //计算发牌
                var tup = LuckPlayerManager.Instance.GetLuckValueIndex(wayId, new List<int>(userids));
                if (tup.Item1 >= 0 || tup.Item2 >= 0)
                {
                    stringBuilder.Clear();
                    Debug.Info($"发牌数据: {tup.Item1} {tup.Item2}");
                    if (tup.Item1 >= 0)
                    {
                        int maxIdx = 0;
                        int maxValue = int.MinValue;
                        for (int i = 0; i < scores.Length; i++)
                        {
                            if (scores[i] > maxValue)
                            {
                                maxValue = scores[i];
                                maxIdx = i;
                            }
                        }

                        //交换
                        if (tup.Item1 != maxIdx)
                        {
                            (scores[maxIdx], scores[tup.Item1]) = (scores[tup.Item1], scores[maxIdx]);
                        }
                    }

                    if (tup.Item2 >= 0)
                    {
                        int minIdx = 0;
                        int minValue = int.MaxValue;

                        for (int i = 0; i < scores.Length; i++)
                        {
                            if (scores[i] < minValue)
                            {
                                minValue = scores[i];
                                minIdx = i;
                            }
                        }

                        //交换
                        if (tup.Item2 != minIdx)
                        {
                            (scores[minIdx], scores[tup.Item2]) = (scores[tup.Item2], scores[minIdx]);
                        }
                    }

                    stringBuilder.Append("发牌后分数: ");
                    for (int i = 0; i < scores.Length; i++)
                    {
                        stringBuilder.Append($"{i}:{scores[i]} ");
                    }

                    Debug.Info(stringBuilder.ToString());
                }

                stringBuilder.Clear();
                stringBuilder.Append($"总局统计 {fightCntIndex}:");
                for (int i = 0; i < fightScores.Length; i++)
                {
                    fightScores[i].Value += scores[i];
                    stringBuilder.Append($"{i}:{fightScores[i].Value}  ");
                }

                Debug.Info(stringBuilder.ToString());

                for (int i = 0; i < values.Length; i++)
                {
                    LuckPlayerManager.Instance.AddOnceFight(wayId, userids[i], scores[i]);
                }

                if (fightCntIndex >= fightCnt)
                {
                    fightCntIndex = 0;
                    //计算封顶
                    Fengding(fightScores);

                    stringBuilder.Clear();
                    stringBuilder.Append("总局分数: ");
                    for (int i = 0; i < fightScores.Length; i++)
                    {
                        stringBuilder.Append($"{i}:{fightScores[i].Value} ");
                    }

                    Debug.Info(stringBuilder.ToString());

                    LuckPlayerManager.Instance.AddScoreRecord(wayId, 20, fightCnt, fightScores);

                    for (int i = 0; i < fightScores.Length; i++)
                    {
                        fightScores[i].Value = 0;
                    }
                }

                Thread.Sleep(1);
            }
        }

        private void Fengding(LuckPlayerManager.FightScore[] fightScores)
        {
            for (int i = 0; i < fightScores.Length; i++)
            {
                fightScores[i].Value *= 20;
            }

            //输的超出部分，赢的人贴
            int loseMaxGet = 0;
            int yuloseMaxGet = 0;
            //权重
            int[] winWeight = new int[4];

            //最后一个赢钱的人
            int lastWinCnt = 0;

            int totalWinCnt = 0;
            for (int i = 0; i < fightScores.Length; i++)
            {
                if (fightScores[i].Value < -2000)
                {
                    loseMaxGet = loseMaxGet - ((int)fightScores[i].Value + 2000); //这个是多输的钱
                    fightScores[i].Value = -2000;
                }

                if (fightScores[i].Value > 0)
                {
                    winWeight[i] = (int)fightScores[i].Value;
                    totalWinCnt += winWeight[i];
                    lastWinCnt = i;
                }
            }

            if (loseMaxGet > 0)
            {
                yuloseMaxGet = loseMaxGet;
                for (int i = 0; i < fightScores.Length; i++)
                {
                    if (fightScores[i].Value > 0) //分摊 多输的钱
                    {
                        if (i == lastWinCnt)
                        {
                            fightScores[i].Value -= yuloseMaxGet;
                        }
                        else //算权重
                        {
                            int weight = (int)(winWeight[i] / (float)totalWinCnt * loseMaxGet);
                            fightScores[i].Value -= weight; //摊费
                            yuloseMaxGet = yuloseMaxGet - weight; //剩余多少摊费
                        }
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (float.TryParse(textBox4.Text, out float beilv) && int.TryParse(textBox8.Text, out int fightCnt) &&
                int.TryParse(textBox5.Text, out int balanceValue))
            {
                if (LuckPlayerManager.Instance.AddBalanceRange(beilv, fightCnt, balanceValue))
                {
                    textBox7.Text = $"添加平衡参数 倍率:{beilv} 值:{balanceValue}";
                }
                else
                {
                    textBox7.Text = "添加失败，已存在平衡参数!";
                }
            }
            else
            {
                textBox7.Text = "添加失败，参数错误!";
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (int.TryParse(textBox6.Text, out int userid))
            {
                if (LuckPlayerManager.Instance.AddBalancePlayer(userid))
                {
                    textBox7.Text = $"添加玩家成功 userid:{userid}";
                }
                else
                {
                    textBox7.Text = "添加失败，没有对应倍率的平衡参数!";
                }
            }
            else
            {
                textBox7.Text = "添加失败，参数错误!";
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (int.TryParse(textBox6.Text, out int userid))
            {
                List<string> logs = LuckPlayerManager.Instance.FindBalancePlayer(userid);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < logs.Count; i++)
                {
                    stringBuilder.Append(logs[i]);
                }

                textBox7.Text = stringBuilder.ToString();
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            StringBuilder stringBuilder = new StringBuilder();
            //查询平衡设置
            foreach (var balanceRange in LuckPlayerManager.Instance.GetAllBalanceRange())
            {
                stringBuilder.AppendLine(
                    $"倍率:{balanceRange.BeiLv}，局数:{balanceRange.MaxFightCnt},平衡参数:{balanceRange.BalanceValue}");
            }

            textBox7.Text = stringBuilder.ToString();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (float.TryParse(textBox4.Text, out float beilv) && int.TryParse(textBox8.Text, out int fightCnt))
            {
                if (LuckPlayerManager.Instance.RemoveBalanceRange(beilv, fightCnt))
                {
                    textBox7.Text = $"移除配置成功 倍率:{beilv} fightCnt:{fightCnt}";
                }
                else
                {
                    textBox7.Text = "移除失败，没有对应倍率的平衡参数!";
                }
            }
            else
            {
                textBox7.Text = "移除失败，参数错误!";
            }
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            //修改平衡参数
            if (float.TryParse(textBox4.Text, out float beilv) && int.TryParse(textBox8.Text, out int fightCnt) &&
                int.TryParse(textBox5.Text, out int balanceValue))
            {
                if (LuckPlayerManager.Instance.SetBalanceRange(beilv, fightCnt, balanceValue))
                {
                    textBox7.Text = $"设置平衡参数成功 倍率:{beilv} fightCnt:{fightCnt} balanceValue:{balanceValue}";
                }
                else
                {
                    textBox7.Text = "移除失败，没有对应倍率的平衡参数!";
                }
            }
            else
            {
                textBox7.Text = "移除失败，参数错误!";
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (int.TryParse(textBox6.Text, out int userid))
            {
                if (LuckPlayerManager.Instance.RemoveBalancePlayer(userid))
                {
                    textBox7.Text = $"移除玩家成功 userid:{userid}";
                }
                else
                {
                    textBox7.Text = "移除玩家失败!";
                }
            }
            else
            {
                textBox7.Text = "添加失败，参数错误!";
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (int.TryParse(textBox6.Text, out int userid))
            {
                List<Tuple<LuckPlayerManager.BalanceRange, LuckPlayerManager.BalancePlayer>> players =
                    LuckPlayerManager.Instance.GetBalancePlayers(userid);

                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < players.Count; i++)
                {
                    stringBuilder.AppendLine(
                        $"倍率：{players[i].Item1.BeiLv} 局数: {players[i].Item1.MaxFightCnt} 平衡数:{players[i].Item1.BalanceValue} 玩家:{userid} 累计分:{players[i].Item2.Score}");
                }

                textBox7.Text = stringBuilder.ToString();
            }
            else
            {
                textBox7.Text = "添加失败，参数错误!";
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            if (float.TryParse(textBox4.Text, out float beilv) && int.TryParse(textBox8.Text, out int fightCnt) &&
                int.TryParse(textBox6.Text, out int userid) && int.TryParse(textBox9.Text, out int score))
            {
                LuckPlayerManager.Instance.AddSessionFightScore(beilv, fightCnt, userid, score, false);
                textBox7.Text = "修改成功!";
            }
            else
            {
                textBox7.Text = "添加失败，参数错误!";
            }
        }
    }
}