using System;
using System.Collections.Generic;
using System.Linq;
using SGModule.Common.Extensions;
using SGModule.Common.Helper;
using SGModule.ConfigLoader;
using SGModule.NetKit;
using UnityEngine;

namespace RedHotRoast {
    public class ConfigSystem : BaseSystem {
        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); //加载开始打点

            var loginModel = LoginKit.Instance.LoginModel;
            ConfigLoader.Instance.Init(new ConfigInitOptions {
                Setting = loginModel.Setting,
                CdnUrl = loginModel.CdnURL,
                OnComplete = state => {
                    Debug.Log($"配置加载状态{state}");
                    if (state == ConfigLoaderState.Successful) {
                        ReloadConfig();
                    }
                },
                OnError = (errorName, message) => {
                    Debug.LogError($"配置解析错误 {errorName}  错误信息：{message}");
                },
                OnHandleUnmarkedConfig = ParseGameConfig
            });
        }

        /// <summary>
        ///     重新加载配置
        /// </summary>
        /// <param name="json"></param>
        private void ReloadConfig() {
            var CdnURL = "https://asserts.minskyfun.top";
            
            TrackKit.TrackLoginFunnel(LoginFunnelEventType.LoadFinish); //加载完成打点

            TextureHelper.imgUrl = CdnURL + "/" + ConfigSystem.GetCommonConf().ResVersion + "/";
            LiveVideoManager.videoBaseUrl = CdnURL + "/"  + ConfigSystem.GetCommonConf().ResVersion + "/";

            // ParseGameConfig();
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close);
            AppDispatcher.Instance.Dispatch(AppMsg.LoginInit);
            CtrlDispatcher.Instance.Dispatch(CtrlMsg.Game_StartBefore);
            SaveingPotHelper.ResetHistory();
        }


        #region 游戏配置

        private void ParseGameConfig() {
            var gameConfigModel = new GameConfigModel();
            foreach (var key in ConfigLoader.Instance.GetJsonKeys()) {
                if (!key.StartsWith("GameBoard")) {
                    continue;
                }

                // 提取 boardIndex
                var boardIndex = 1;
                var parts = key.Split('_');
                if (parts.Length > 1 && int.TryParse(parts[1], out var parsed)) {
                    boardIndex = parsed;
                }

                // 获取 json 并反序列化
                if (ConfigLoader.Instance.TryGetJsonValue(key, out var gameboardJson)) {
                    try {
                        var gameBoards = gameboardJson.As<List<GameBoard>>();
                        if (gameBoards != null) {
                            gameConfigModel.game_conf[boardIndex] = gameBoards;
                        }
                        else {
                            Log.ConfigLoader.Warning($"GameBoard 配置 {key} 反序列化为空");
                        }
                    }
                    catch (Exception ex) {
                        Log.ConfigLoader.Error($"GameBoard 配置 {key} 反序列化失败: {ex.Message}");
                    }
                }
            }

            ConfigLoader.Instance.AddConfig(gameConfigModel);
        }

        #endregion

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

        public static List<T> GetConfig<T>() where T : class {
            return ConfigLoader.Instance.GetConfig<List<T>>() ?? new List<T>();
        }

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