using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using SGModule.ConfigLoader;
using SGModule.Net;
using Newtonsoft.Json;
using SGModule.NetKit;
using IgnoreOPS;

namespace ChillConnect
{
    public class ConfigSystem : BaseSystem
    {
        public static List<GameUrls> light_weblist = new List<GameUrls>();
        public static List<GameUrls> dark_weblist = new List<GameUrls>();
        public static string web_through_str;

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

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

        private void AddListener()
        {
            NetworkDispatcher.Instance.AddListener(NetworkMsg.GetConfig, OnGetConfig);
        }

        private void RemoveListener()
        {
            NetworkDispatcher.Instance.RemoveListener(NetworkMsg.GetConfig, OnGetConfig);
        }

        private void OnGetConfig(object obj)
        {
            TrackKit.TrackLoginFunnel(LoginFunnelEventType.LoadBegin);  //加载开始打点
            int type = 0;
            if (obj != null) type = (int)obj;
            var loginModel = LoginKit.Instance.LoginModel;
            ConfigLoader.Instance.Init(loginModel.Setting, loginModel.CdnURL, new List<ConfigModel>() {
                    new CommonModel("Common"),
                    new SignDailyRewardModel("SignDailyReward"),
                    new TurntableModel("turntable"),
                    new RewardNumModel("rewardNum"),
                    new DurationtasksModel("Durationtasks"),
                    new PassingTaskModel("PassingTasks"),
                    new PassportrewardsModel("Passportrewards"),
                    new ADTaskModel("ADTasks"),
                    new SmallrewardNumModel("SmallrewardNum"),
                    new LargerewardNumModel("LargerewardNum"),
                    new PaidcoinsModel("Paidcoins"),
                    new PaidgiftModel("Paidgift"),
                    new OnlineRewardsModel("OnlineRewards"),
                    new MakeupModel("makeup"),
                    new GameUrlsModel("GameUrls"),
                    new exBrPoolModel("exBrPool"),
                    new RankHourRewardsModel("RankHourRewards"),
                    new RankDayRewardsModel("RankDayRewards"),
                    new RankWeekRewardsModel("RankWeekRewards"),
                    new MakeupModel_2("makeup_2"),
                    new exBrPoolModel_2("exBrPool_2"),
                    new MultigiftModel("Multigift"),
                    new ApplePayModel("applePay"),
                  //  new ApplePayModel2("applePay2"),
                    new FAQRuleModel("FAQRule"),
                    new FAQRuleModel1("FAQRule_1"),
                    new MessageBoardModel("MessageBoard"),
                    new MessageBoardModel1("MessageBoard_1"),
                    new LevelAttemptsModel("LevelAttempts"),
                    new TurnOffRewardsModel("TurnOffRewards"),
                    new ExchangeDesModel("ExchangeDescriptors"),
                    new AppOpenAdModel("SplashAD"),
                },
                state =>
                {
                    Debug.Log($"配置加载状态{state}");
                    // Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig<ApplePayModel>().DataList));
                    if (state == ConfigLoaderState.Successful)
                    {
                        if (type == 0)
                        {
                            Debug.Log(GameHelper.NeedShowOpenAd());
                            if (GameHelper.NeedShowOpenAd() && GameHelper.IsGiftSwitch())
                            {
                                GameHelper.ShowOpenAd();
                            }
                            else
                            {
                                GameDispatcher.Instance.Dispatch(GameMsg.CloseMask);
                            }
                        }
                        ReloadConfig();
                    }
                },
                (errorName, message) =>
                {
                    Debug.LogError($"配置解析错误 {errorName}  错误信息：{message}");
                });

        }


        /// <summary>
        /// 重新加载配置
        /// </summary>
        /// <param name="json"></param>
        private void ReloadConfig()
        {
            TrackKit.TrackLoginFunnel(LoginFunnelEventType.LoadFinish);//加载完成打点
            ParseGameConfig();
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close);
            AppDispatcher.Instance.Dispatch(AppMsg.LoginInit);
            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;
            }
            CtrlDispatcher.Instance.Dispatch(CtrlMsg.Game_StartBefore);
            SaveingPotHelper.ResetHistory();
        }


        #region 游戏配置

        private void ParseGameConfig()
        {

            var exBrPoolModel = GetConfig<exBrPoolModel>();
            if (exBrPoolModel != null && exBrPoolModel.DataList.Count > 0)
            {
                exBrPoolModel.config_name_list = exBrPoolModel.DataList[0].user_name.Split(",").ToList();
                exBrPoolModel.config_money_list = exBrPoolModel.DataList[0].amount.Split(",").ToList();
            }

            var exBrPoolModel2 = GetConfig<exBrPoolModel_2>();
            if (exBrPoolModel2 != null && exBrPoolModel2.DataList.Count > 0)
            {
                exBrPoolModel2.config_name_list = exBrPoolModel2.DataList[0].user_name.Split(",").ToList();
                exBrPoolModel2.config_money_list = exBrPoolModel2.DataList[0].amount.Split(",").ToList();
            }
            var LevelAttemptsModel_ = GetConfig<LevelAttemptsModel>();
            if (LevelAttemptsModel_ != null && LevelAttemptsModel_.DataList.Count > 0)
            {
                LevelAttemptsModel_.config_name_list = LevelAttemptsModel_.DataList[0].user_name.Split(",").ToList();
                LevelAttemptsModel_.config_money_list = LevelAttemptsModel_.DataList[0].amount.Split(",").ToList();
            }
            var gameUrlsModel = GetConfig<GameUrlsModel>();
            if (gameUrlsModel != null && gameUrlsModel.DataList.Count > 0)
            {
                light_weblist.Clear();
                dark_weblist.Clear();
                web_through_str = "";

                var allList = gameUrlsModel.DataList;
                List<int> type_list = new List<int>();
                for (int i = 0; i < allList.Count; i++)
                {
                    if (allList[i].webType == 2)
                    {
                        if ((GameHelper.IsGiftSwitch() && allList[i].isMagic == 1) ||
                            (!GameHelper.IsGiftSwitch() && allList[i].isMagic == 0))
                        {
                            light_weblist.Add(allList[i]);
                        }
                    }
                    else
                    {
                        dark_weblist.Add(allList[i]);
                        if (!type_list.Contains(allList[i].wvType))
                        {
                            web_through_str += allList[i].wvthrough;
                            web_through_str += "|";
                            type_list.Add(allList[i].wvType);
                        }
                    }
                }

                web_through_str.Remove(web_through_str.Length - 1);
                gameUrlsModel.DataList = light_weblist;
            }

            var jsonDictionary = ConfigLoader.Instance.JsonDictionary;
            var gameConfigModel = new GameConfigModel("GameBoard");
            foreach (var item in jsonDictionary)
            {
                if (item.Key.StartsWith("GameBoard"))
                {
                    string[] parts = item.Key.Split('_');

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

                    if (jsonDictionary.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());
                    }
                }
            }

            ConfigLoader.Instance.AddConfig(gameConfigModel);
        }

        #endregion

        public static T GetConfig<T>()
        {
            return ConfigLoader.Instance.GetConfig<T>();
        }

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