using System;
using System.IO;
using BingoBrain.Core;
using UnityEngine;
using BingoBrain.Asset;
using BingoBrain.HotFix;
using System.Collections.Generic;
using Newtonsoft.Json;
using BingoBrain;
using System.Linq;

namespace BingoBrain
{
    public class ConfigSystem : BaseSystem
    {
        private static Dictionary<Type, object> configData = new();

        public ConfigSystem(bool isAutoInit = true)
        {
            if (isAutoInit)
            {
                Init();
            }
        }

        public sealed override void Init()
        {
            base.Init();
            AddListener();
        }

        private void AddListener()
        {
            NetworkDispatcher.Instance.AddListener(ExternalInfo.GetConfig, OnRequestGetConfig);
        }

        private void RemoveListener()
        {
            NetworkDispatcher.Instance.RemoveListener(ExternalInfo.GetConfig, OnRequestGetConfig);
        }

        private void OnRequestGetConfig(object obj)
        {
            // var configFileName = "BingoJson";
            // var configFileSavePath = $"{Application.streamingAssetsPath}/Config/";
            // var assetHotFixFilePath = $"{configFileSavePath}{configFileName}.txt";
            // if (File.Exists(assetHotFixFilePath))
            // {
            //     ParseConfig(File.ReadAllText(assetHotFixFilePath));
            //     UICtrlDispatcher.Instance.Dispatch(SkinInfo.CheckReadyUI_Close);
            //     AppDispatcher.Instance.Dispatch(CsjInfoC.LoginInit);
            // }
            // else
            // {
            //     IsfvKit.StartCoroutine(CachKit.GetTextFromUrl($"{Application.streamingAssetsPath + "/Config/BingoJson.txt"}", configFileName,
            //         content =>
            //         {
            //             ParseConfig(content);
            //             UICtrlDispatcher.Instance.Dispatch(SkinInfo.CheckReadyUI_Close);
            //             AppDispatcher.Instance.Dispatch(CsjInfoC.LoginInit);
            //             CtrlDispatcher.Instance.Dispatch(CtrlMsg.Game_StartBefore);
            //         }, configFileSavePath));
            // }


            GameHelper.PostFunnelLogin("loadBegin");
            var loginData = GameHelper.GetLoginModel();

            var configFileName = "BingoJson";
            var configFileSavePath = $"{Application.persistentDataPath}/Config/";
            var assetHotFixFilePath = $"{configFileSavePath}{configFileName}.txt";
            var configFileNameKey = "configFileName";

            var CDNConfigFileName = loginData.setting;
            string savedCfgName = PlayerPrefs.GetString(configFileNameKey);
            bool needDownloadConfigFile = false;

            if (!string.IsNullOrEmpty(CDNConfigFileName))
            {
                //如果本地Player Prefs里没有保存配置文件名
                if (string.IsNullOrEmpty(savedCfgName))
                {
                    // Debug.Log("[UNITY] No config file name saved.");
                    needDownloadConfigFile = true;
                }
                else
                {
                    // Debug.Log($"[UNITY] Saved config name: {savedCfgName}, CDN config name: {CDNConfigFileName}");
                    //与CDN上的对比名称
                    if (!savedCfgName.Equals(CDNConfigFileName))
                    {
                        needDownloadConfigFile = true;
                    }
                }
            }
            //Debug.Log($"[UNITY] needDownloadConfigFile: {needDownloadConfigFile}");
            //默默地拉去新配置
            //  Debug.Log("kkkkkkkkkkkkkkkkkkkkkk" + needDownloadConfigFile);
            //  Debug.Log("kkkkkkkkkkkkkkkkkkkkkk" + savedCfgName);

            if (needDownloadConfigFile)
            {
                IsfvKit.StartCoroutine(CachKit.GetTextFromUrl($"{NetworkKit.CDNUrl}config/{CDNConfigFileName}",
                    configFileName, (content) =>
                    {
                        PlayerPrefs.SetString(configFileNameKey, CDNConfigFileName);
                        ParseConfig(content);
                        //CtrlDispatcher.Instance.Dispatch(CtrlMsg.NewConfigRead);
                    }, configFileSavePath));
            }
            //检查设备本地是否有配置文件
            if (File.Exists(assetHotFixFilePath))
            {
                //  Debug.Log($"[UNITY] Load config from datapath: {assetHotFixFilePath}");
                ParseConfig(File.ReadAllText(assetHotFixFilePath));
                // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close);
                AppDispatcher.Instance.Dispatch(CsjInfoC.LoginInit);
                GameHelper.PostFunnelLogin("loadFinish");

            }
            else  //没有就从StreamingAssets读取
            {
                var path = $"{Application.streamingAssetsPath}/Config/{configFileName}.txt";
#if UNITY_IOS
                path = "file://" + path;
#endif
                // Debug.Log($"[UNITY] Load config from streaming asset: {path}");
                IsfvKit.StartCoroutine(CachKit.GetTextFromUrl(path, configFileName, content =>
                {
                    ParseConfig(content);
                    // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close);
                    AppDispatcher.Instance.Dispatch(CsjInfoC.LoginInit);
                    GameHelper.PostFunnelLogin("loadFinish");
                }, configFileSavePath));
            }
        }

        private void ParseConfig(string json)
        {
            Debug.Log(json);
            if (json == null)
            {
                return;
            }

            if (!json.StartsWith("{"))
            {
                json = Base64Kit.Decode(json, NetworkMsg.Identifier);
            }

            var dictionary = Havva.ToObject<Dictionary<string, object>>(json);
            ParseGameConfig(dictionary);
                                CtrlDispatcher.Instance.Dispatch(CtrlMsg.Game_StartBefore);
            ModuleBoardk.Instance.AllModuleReadData();
        }

        #region 游戏配置
        public static List<GameUrls> light_weblist = new List<GameUrls>();
        public static List<GameUrls> dark_weblist = new List<GameUrls>();
        private List<GameUrls> data_new;
        public static string web_through_str;
        private void GetGameConfig<T, TK>(IReadOnlyDictionary<string, object> dictionary)
        {
            if (dictionary.TryGetValue(typeof(TK).Name.ToString(), out var config))
            {
                // Debug.Log(typeof(T));
                // Debug.Log(config);
                if (typeof(T) == typeof(CommonModel))
                {
                    Debug.Log(config);
                }
                var data = Havva.ToObject<List<TK>>(config.ToString());
                object[] para = { data };
                var o = (T)Activator.CreateInstance(typeof(T));
                typeof(T).GetMethod("SetDataList")?.Invoke(o, para);
                configData[typeof(T)] = o;

                if (typeof(T) == typeof(GameUrlsModel))
                {

                    light_weblist.Clear();
                    dark_weblist.Clear();
                    web_through_str = "";
                    data_new = Havva.ToObject<List<GameUrls>>(config.ToString());
                    List<int> type_list = new List<int>();
                    for (int i = 0; i < data_new.Count; i++)
                    {

                        if (data_new[i].webType == 2)
                        {
                            if (GameHelper.IsGiftSwitch() && (data_new[i].isMagic == 1)) light_weblist.Add(data_new[i]);
                            else if (!GameHelper.IsGiftSwitch() && (data_new[i].isMagic == 0)) light_weblist.Add(data_new[i]);
                        }
                        else
                        {
                            dark_weblist.Add(data_new[i]);
                            if (!type_list.Contains(data_new[i].wvType))
                            {
                                web_through_str += data_new[i].wvthrough;
                                web_through_str += "|";
                                type_list.Add(data_new[i].wvType);
                            }
                        }

                    }

                    web_through_str.Remove(web_through_str.Length - 1);

                    Debug.Log(light_weblist.Count);
                    Debug.Log(dark_weblist.Count);
                    Debug.Log("////////////////////////");
                }

            }
        }

        private void GetGameConfData(IReadOnlyDictionary<string, object> dictionary)
        {
            var GameConfigModel = new GameConfigModel();

            foreach (var item in dictionary)
            {
                if (item.Key.StartsWith("GameBoard"))
                {
                    string[] parts = item.Key.Split('_');

                    int boardIndex;
                    if (parts.Length > 1 && int.TryParse(parts[1], out boardIndex))
                    {
                        // 成功解析出数字
                        // Debug.Log($"boardIndex==== {boardIndex}");
                    }
                    else
                    {
                        boardIndex = 1;
                    }

                    if (dictionary.TryGetValue(item.Key, out var gameboard))
                    {

                        if (!GameConfigModel.game_conf.ContainsKey(boardIndex))
                        {
                            GameConfigModel.game_conf.Add(boardIndex, null);
                        }

                        GameConfigModel.game_conf[boardIndex] = SerializeUtil.ToObject<List<GameBoard>>(gameboard.ToString());

                    }
                }
            }
            configData[typeof(GameConfigModel)] = GameConfigModel;
        }


        private void GetSingleConfig<T>(IReadOnlyDictionary<string, object> dictionary, string configName)
        {
            if (dictionary.TryGetValue(configName, out var config))
            {
                var model = Havva.ToObject<T>(config.ToString());
                configData[typeof(T)] = model;
            }
        }

        private void ParseGameConfig(IReadOnlyDictionary<string, object> dictionary)
        {
            GetSingleConfig<CommonModel>(dictionary, "Common");

            GetGameConfig<AdRewardModel, AdReward>(dictionary);
            GetGameConfig<TaskListModel, TaskList>(dictionary);
            GetGameConfig<Out101Model, Out101>(dictionary);
            GetGameConfig<Out102Model, Out102>(dictionary);
            GetGameConfig<FlopModel, Flop>(dictionary);
            GetGameConfig<QBLOXModel, QBLOX>(dictionary);
            GetGameConfig<PropModel, Prop>(dictionary);
            GetGameConfig<TurntableModel, Turntable>(dictionary);
            GetGameConfig<SignDailyModel, SignDaily>(dictionary);
            GetGameConfig<BingoProbModel, BingoProb>(dictionary);
            GetGameConfig<MakeupModel, makeup>(dictionary);
            GetGameConfig<CardRedeemNewModel, cardRedeemNew>(dictionary);
            GetGameConfig<GameUrlsModel, GameUrls>(dictionary);
            GetGameConfig<exBrPoolModel, exBrPool>(dictionary);

            GetGameConfig<PaidcoinsModel, Paidcoins>(dictionary);
            GetGameConfData(dictionary);
            GetGameConfig<PassingTaskModel, PassingTasks>(dictionary);
            GetGameConfig<DurationtasksModel, Durationtasks>(dictionary);
            GetGameConfig<PassportrewardsModel, Passportrewards>(dictionary);
            GetGameConfig<RewardNumModel, rewardNum>(dictionary);
            GetGameConfig<SmallrewardNumModel, SmallrewardNum>(dictionary);
            GetGameConfig<LargerewardNumModel, LargerewardNum>(dictionary);
            GetGameConfig<PaidgiftModel, Paidgift>(dictionary);
            GetGameConfig<exBrPoolModel_2, exBrPool_2>(dictionary);
            GetGameConfig<MakeupModel_2, makeup_2>(dictionary);
            GetGameConfig<MultigiftModel, Multigift>(dictionary);

            GetGameConfig<ExchangeDesModel, ExchangeDescriptors>(dictionary);//兑换
//            Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig<ExchangeDesModel>().dataList));
            exBrPoolModel.config_name_list = ConfigSystem.GetConfig<exBrPoolModel>().dataList[0].user_name.Split(",").ToList();
            exBrPoolModel.config_money_list = ConfigSystem.GetConfig<exBrPoolModel>().dataList[0].amount.Split(",").ToList();
            exBrPoolModel_2.config_name_list = ConfigSystem.GetConfig<exBrPoolModel_2>().dataList[0].user_name.Split(",").ToList();
            exBrPoolModel_2.config_money_list = ConfigSystem.GetConfig<exBrPoolModel_2>().dataList[0].amount.Split(",").ToList();

            //   exBrPoolModel.getFaqData();
            if (PreferencesMgr.Instance.ActiveMissions != null)
            {
                for (int i = 0; i < PreferencesMgr.Instance.ActiveMissions.Count; i++)
                {
                    // Debug.Log(JsonConvert.SerializeObject(PreferencesMgr.Instance.ActiveMissions[i]));
                    // Debug.Log(JsonConvert.SerializeObject(GameHelper.GetConfig<TaskListModel>().GetData(i + 1)));
                    TaskList config = GameHelper.GetConfig<TaskListModel>().GetData(i + 1);
                    PreferencesMgr.Instance.ActiveMissions[i].MaxProgress = config.taskNum;
                    PreferencesMgr.Instance.ActiveMissions[i].RewardId = config.rewardID;
                    PreferencesMgr.Instance.ActiveMissions[i].IsMulti = config.isMulti;
                    if (!PreferencesMgr.Instance.FinishTaskList.Contains(i + 1))
                    {
                        PreferencesMgr.Instance.ActiveMissions[i].RewardSum = config.rewardFirst;
                    }
                    else
                    {
                        PreferencesMgr.Instance.ActiveMissions[i].RewardSum = config.reward[GameHelper.GetDynamicIndex(i + 1)];
                    }
                }

            }
            if (PreferencesMgr.Instance.DailyBonusItemLst != null)
            {
                for (int i = 0; i < PreferencesMgr.Instance.DailyBonusItemLst.Count; i++)
                {
                    // Debug.Log(JsonConvert.SerializeObject(PreferencesMgr.Instance.DailyBonusItemLst[i]));
                    // Debug.Log(JsonConvert.SerializeObject(GameHelper.GetConfig<SignDailyModel>().GetData(i + 1)));
                    SignDaily config = GameHelper.GetConfig<SignDailyModel>().GetData(i + 1);
                    PreferencesMgr.Instance.DailyBonusItemLst[i].id = config.item1;
                    PreferencesMgr.Instance.DailyBonusItemLst[i].quantity = config.quantity[0];
                    PreferencesMgr.Instance.DailyBonusItemLst[i].isDouble = config.isMulti;
                    PreferencesMgr.Instance.DailyBonusItemLst[i].cont_index = config.cont_index;
                }

            }
            Debug.Log(SaveData.GetSaveobject());
            if (SaveData.GetSaveobject().ExchangeProcessMode < 0)
            {
                SaveData.GetSaveobject().ExchangeModeToggle = ConfigSystem.GetConfig<CommonModel>().ExchangeModeToggle;
                SaveData.GetSaveobject().ExchangeProcessMode = ConfigSystem.GetConfig<CommonModel>().ExchangeProcessMode;
                SaveData.GetSaveobject().CHProcessMode = ConfigSystem.GetConfig<CommonModel>().CHProcessMode;
            }
            // Debug.Log("888888888888888888");
        }

        #endregion

        public static T GetConfig<T>()
        {
            return configData.TryGetValue(typeof(T), out var value) ? (T)value : default;
        }

        public override void Dispose()
        {
            base.Dispose();
            RemoveListener();
        }
    }


}