using System;
using System.Collections.Generic;
using GameData;
using GameDAL.Game;
using MrWu.DB;
using MrWu.Debug;
using Server.Core;
using Server.DB.Redis;
using Server.DB.Sql;
using StackExchange.Redis;
using GameData.Club;

namespace Server
{
    public class TestManager : SingleInstance<TestManager>
    {
        /// <summary>
        /// 
        /// </summary>
        private const int DBIdx = 6;

#if DEBUG
        public const bool isTest = true;
#else
        public const bool isTest = false;
#endif

        private IDatabase _db;

        public IDatabase db
        {
            get
            {
                if (_db == null)
                {
                    _db = redisManager.GetDataBase(DbStyle.main, DBIdx);
                }

                return _db;
            }
        }

        /// <summary>
        /// 添加游戏战斗数据
        /// </summary>
        public void AddGameFightData(FightScore fightScore)
        {
            if (!isTest)
            {
                return;
            }

            for (int i = 0; i < fightScore.scores.Length; i++)
            {
                FightScore.Player player = fightScore.scores[i];
                string key = $"FightDataStatics:{player.clubId}:{player.userid}";

                IBatch batch = db.CreateBatch();
                batch.HashIncrementAsync(key, "playCnt", 1);
                batch.HashIncrementAsync(key, "Score", (int)(player.score * 100));
                batch.Execute();
            }
        }

        public void Statics()
        {
            List<RedisKey> keys = redisManager.Keys("FightDataStatics:*", DBIdx);
            Dictionary<int, ClubData> datas = new Dictionary<int, ClubData>(); // 俱乐部参与人次

            for (int i = 0; i < keys.Count; i++)
            {
                string key = keys[i];
                string[] keyStr = key.Split(':');
                int clubid = int.Parse(keyStr[1]);
                int userid = int.Parse(keyStr[2]);

                if (!datas.ContainsKey(clubid))
                {
                    datas.Add(clubid, new ClubData()
                    {
                        ClubId = clubid,
                    });
                }

                var values = db.HashGetAll(key);
                UserData userData = new UserData();
                for (int j = 0; j < values.Length; j++)
                {
                    if (values[j].Name == "playCnt")
                    {
                        userData.playCnt += (int)values[j].Value;
                        datas[clubid].Cnt += (int)values[j].Value;
                    }
                    else if (values[j].Name == "Score")
                    {
                        userData.score = (long)values[j].Value;
                    }
                }
                datas[clubid].Score.Add(userid, userData);
            }

            
            foreach (var key in datas.Keys)
            {
                decimal zongScore = 0;
                Dictionary<int, UserData> playerValue = datas[key].Score;
                foreach (var item in playerValue.Keys)
                {
                    int roomRate = datas[key].Score[item].playCnt * 6;
                    decimal score = (decimal)datas[key].Score[item].score / 100;
                    zongScore += (score - roomRate);
                    Debug.Info($"玩家:{item},房费:{roomRate},输赢:{score},总分:{score - roomRate}");
                }
                
                Debug.Info($"Club:{key} 参与人次:{datas[key].Cnt} 收益:{datas[key].Cnt * 5} 总分:{zongScore}");
            }
        }

        public void ClearData()
        {
            List<RedisKey> keys = redisManager.Keys("FightDataStatics:*", DBIdx);
            db.KeyDelete(keys.ToArray());
        }

        /// <summary>
        /// 俱乐部数据
        /// </summary>
        private class ClubData
        {
            /// <summary>
            /// 俱乐部ID
            /// </summary>
            public int ClubId;

            /// <summary>
            /// 参与人次
            /// </summary>
            public int Cnt;

            /// <summary>
            /// 玩家的分
            /// </summary>
            public Dictionary<int, UserData> Score = new Dictionary<int, UserData>();
        }

        private class UserData
        {
            /// <summary>
            /// 参与人次
            /// </summary>
            public int playCnt;

            /// <summary>
            /// 玩家得分
            /// </summary>
            public long score;
        }


        /// <summary>
        /// 更新新门票
        /// </summary>
        public bool UpdateUserMenPiao(int userid)
        {
            try
            {
                // 新增逻辑：根据数据库中的menpiao数量使用ActivityPropManager.Instance.AddTicket新增门票
                var selectSql = $"SELECT [menpiao] FROM [tbDaoju2023] WHERE userid = {userid}";
                var currentMenpiaoInDB = 0;
                var result = dbbase.gamedb.ExecuteTable(selectSql);
                if (result != null && result.Rows.Count > 0)
                {
                    currentMenpiaoInDB = (int)result.Rows[0]["menpiao"];
                }
                // 如果当前数据库中的数量大于0，则补充差值
                if (currentMenpiaoInDB > 0)
                {
                    ActivityPropManager.Instance.AddActivityPropData(userid,ActivityPropType.MenPiao,currentMenpiaoInDB);
                    string sql = $"if exists(select userid from tbDaoju2023 where userid={userid}) begin update tbDaoju2023 set menpiao=0 where userid={userid} end;";
                    return GameDB.Instance.ExceSql(dbbase.gamedb, sql) == 1;
                }
                return true;
            }
            catch (Exception e)
            {
                Debug.Error($"更新门票出错 msg:{e.Message} code:{e.StackTrace}");
                return false;
            }

        }
    }
}