using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using DefaultNamespace;
using MotionFramework;
using Newtonsoft.Json.Linq;
using ToolsPack;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Timeline;

public enum ToolsPackScene
{
    工具间,
    其他,
    现场堪察
}

public class ToolsPackString
{
    public ModelTypeEnum ModelTypeEnum;
    public string ToolsName;
    public int Index;
}

public class ToolsPackWindowItemBtModel
{
    public string btName;
    public int index;
}


/// <summary>
/// 工具包
/// </summary>
public class ToolsPackManager : ModuleSingleton<ToolsPackManager>, IModule
{
    private Dictionary<string, List<GameObject>> _toolsPack; //在工具间存
    private Dictionary<string, List<Vector3>> _toolsPackBackup;//HQB，记录tool的位置，切换场景后toolsPack的obj会销毁，以position作为标记

    private Dictionary<string, List<ToolsPackString>> _toolsPackString; //只存值
    private Dictionary<string, Texture2D> _toolsPackWindowBtImage; //工具窗口下的按钮图集
    private List<GameObject> _toolsPackWindowItemBts; //工具窗口下创建的按钮集合,点击按钮的X用来删除和新增
    private GameObject _toolsPackWindow;
    private GameObject _toolsPackWindowBt;
    private Transform _canvas;

    private GameObject _toolsPackWindowTemp;

    private ToolsPackScene _toolsPackScene;

    public delegate void StringEventHandler(string message);

    public event StringEventHandler OnStringEvent;

    public List<string> wearTools = new List<string>();

    /// <summary>
    /// HQB检查恢复_toolsPack，因为没有其他的键值，只能先以位置作为键值
    /// </summary>
    public void RecoverToolsPack()
    {
        if (_toolsPack == null || _toolsPack.Count == 0)return;
        // ToolRoomToolsContainer toolRoomToolsContainer = GameObject.FindObjectOfType<ToolRoomToolsContainer>();
        // if (toolRoomToolsContainer == null) return;
        //
        // foreach (var toolItem in _toolsPack)
        // {
        //     for (int i = 0; i < toolItem.Value.Count; i++)
        //     {
        //         if (toolItem.Value[i] == null)
        //         { 
        //             string toolName = toolItem.Key;
        //             Vector3 pos = _toolsPackBackup[toolName][i];
        //             for (int j = 0; j < toolRoomToolsContainer.transform.childCount; j++)
        //             {
        //                 if (toolRoomToolsContainer.transform.GetChild(j).position.Equals(pos))
        //                 {
        //                     toolItem.Value[i] = toolRoomToolsContainer.transform.GetChild(j).gameObject;
        //                     break;
        //                 }
        //             }
        //
        //         }
        //     }
        // }
    }

    // 触发事件的方法
    public void OnTriggerStringEvent(string message)
    {
        if (OnStringEvent != null)
        {
            OnStringEvent(message);
        }
    }

    public void OnCreate(object createParam)
    {
        _toolsPack = new Dictionary<string, List<GameObject>>();
        _toolsPackString = new Dictionary<string, List<ToolsPackString>>();
        _toolsPackWindowItemBts = new List<GameObject>();
        _toolsPackBackup = new Dictionary<string, List<Vector3>>();//HQB初始化

        //加载工具窗口按钮
        _toolsPackWindowBt = Resources.Load<GameObject>("Prefabs/UI_ToolOrMaterialsOrDeviceItem");
        //加载工具窗口
        _toolsPackWindow = Resources.Load<GameObject>("Prefabs/ToolsPackWindow");

        // 从Resources/ToolsPack文件夹加载所有Texture2D资源
        Texture2D[] loadedTextures = Resources.LoadAll<Texture2D>("ToolAndMaterial");
        // 初始化List
        _toolsPackWindowBtImage = new Dictionary<string, Texture2D>();

        // 将加载的Texture2D添加到List中
        foreach (Texture2D texture in loadedTextures)
        {

            Debug.Log(texture.name);
            _toolsPackWindowBtImage.Add(texture.name, texture);
        }

        Debug.Log("已添加工具包模块");
    }

    public void OnUpdate()
    {
        //Debug.Log("===>ToolsPackManager");//HQB
    }

    public void OnDestroy()
    {
        _toolsPack.Clear();
        _toolsPackBackup.Clear();//HQB
    }

    public void OnGUI()
    {
    }

    public void AddWearTool(string wearToolName)
    {
        if (!wearTools.Contains(wearToolName))
        {
            wearTools.Add(wearToolName);
        }
    }

    public void RemoveWearTool(string wearToolName)
    {
        if (wearTools.Contains(wearToolName))
        {
            wearTools.Remove(wearToolName);
        }
    }

    /// <summary>
    /// 添加到工具包
    /// </summary>
    /// <param name="toolsName"></param>
    /// <param name="toolsGame"></param>
    public void AddToolsPack(string toolsName, GameObject toolsGame)
    {
        if (!_toolsPack.ContainsKey(toolsName))
        {
            _toolsPack.Add(toolsName, new List<GameObject>() { toolsGame });
            _toolsPackBackup.Add(toolsName, new List<Vector3>() { toolsGame.transform.position });//HQB
            _toolsPackString.Add(toolsName, new List<ToolsPackString>()
            {
                new ToolsPackString()
                {
                    ToolsName = toolsName,
                    ModelTypeEnum = toolsGame.GetComponent<ToolsPackGameObjectComponent>().GetModelTypeEnum(),
                    Index = 0
                }
            });
            toolsGame.GetComponent<ToolsPackGameObjectComponent>().SetIndex(0);
        }
        else
        {
            toolsGame.GetComponent<ToolsPackGameObjectComponent>().SetIndex(_toolsPack[toolsName].Count);
            _toolsPack[toolsName].Add(toolsGame);
            _toolsPackBackup[toolsName].Add(toolsGame.transform.position);//HQB
            _toolsPackString[toolsName].Add(
                new ToolsPackString()
                {
                    ToolsName = toolsName,
                    ModelTypeEnum = toolsGame.GetComponent<ToolsPackGameObjectComponent>().GetModelTypeEnum(),
                    Index = _toolsPack[toolsName].Count
                });
        }
    }

    /// <summary>
    /// 删除工具包
    /// </summary>
    /// <param name="toolsName"></param>
    public void DeleteToolsPack(string toolsName, int index)
    {
        int count = _toolsPack[toolsName].Count;
        if (count > 1)
        {
            GameObject g = _toolsPack[toolsName].SingleOrDefault(s => s.GetComponent<ToolsPackGameObjectComponent>().GetIndex() == index);
            ToolsPackString gString = _toolsPackString[toolsName].SingleOrDefault(s => s.Index == index);
            _toolsPack[toolsName].Remove(g);
            _toolsPackString[toolsName].Remove(gString);
            // for (int i = 0; i < _toolsPack[toolsName].Count; i++)
            // {
            //     if (_toolsPack[toolsName][i].GetComponent<ToolsPackGameObjectComponent>().GetIndex() == index)
            //     {
            //         _toolsPack[toolsName].re
            //     }
            // }
        }

        else
        {
            _toolsPack.Remove(toolsName);
            _toolsPackString.Remove(toolsName);
            _toolsPackBackup.Remove(toolsName);//HQB
        }
    }

    public void DeleteStringToolsPack(string toolsName, int index)
    {
        int count = _toolsPackString[toolsName].Count;
        if (count > 1)
        {
            ToolsPackString gString = _toolsPackString[toolsName].SingleOrDefault(s => s.Index == index);
            _toolsPackString[toolsName].Remove(gString);
        }
        else
        {
            _toolsPackString.Remove(toolsName);
        }
    }


    /// <summary>
    /// 获取所有工具包内容
    /// </summary>
    /// <returns></returns>
    public Dictionary<string, List<GameObject>> GetToolsPack()
    {
        if (_toolsPack != null || _toolsPack.Count > 0)//HQB
        { 
            RecoverToolsPack();
        }
        return _toolsPack;
    }

    /// <summary>
    /// 获取所有工具包内容
    /// </summary>
    /// <returns></returns>
    public Dictionary<string, List<ToolsPackString>> GetToolsPackString()
    {
        return _toolsPackString;
    }

    /// <summary>
    /// 根据名字查询工具包内容
    /// </summary>
    /// <returns></returns>
    public GameObject GetToolsPack(string toolsName, int index)
    {
        List<GameObject> game;
        if (_toolsPack.TryGetValue(toolsName, out game))
        {
            for (int i = 0; i < game.Count; i++)
            {
                int iii = game[i].GetComponent<ToolsPackGameObjectComponent>().GetIndex();
                if (iii == index)
                {
                    return (game[i]);
                }
            }
        }

        return null;
    }

    public Texture2D GetToolsPackWindowBtImage(string gName)
    {
        Texture2D tex;
        if (_toolsPackWindowBtImage.TryGetValue(gName, out tex))
        {
            return tex;
        }

        return null;
    }

    public GameObject GetToolsPackWindow()
    {
        return _toolsPackWindow;
    }

    public void CloseToolsPackWindow()
    {
    }

    public GameObject GetToolsPackWindowBt()
    {
        return _toolsPackWindowBt;
    }

    public GameObject GetToolsPackWindowTemp()
    {
        return _toolsPackWindowTemp;
    }

    public void SetToolsPackWindowTemp(GameObject win)
    {
        _toolsPackWindowTemp = win;
    }

    public Transform GetCanvas()
    {
        if (_canvas == null)
        {
            _canvas = GameObject.Find("Canvas").transform;
        }

        return _canvas;
    }

    public ToolsPackScene GetToolsPackScene()
    {
        return _toolsPackScene;
    }

    public void SetToolsPackScene(ToolsPackScene toolsPackScene)
    {
        _toolsPackScene = toolsPackScene;
    }

    public void AddToolsPackWindowItemBts(GameObject toolGame)
    {
        _toolsPackWindowItemBts.Add(toolGame);
    }

    public void ClearToolsPackWindowItemBts()
    {
        _toolsPackWindowItemBts.Clear();
    }

    /// <summary>
    /// 删除背包里的UI按钮
    /// </summary>
    /// <param name="toolName"></param>
    /// <param name="index"></param>
    public void DeleteToolsPackWindowItemBts(string toolName, int index)
    {
        List<string> list = MotionEngine.GetModule<DataConfigManager>().GetToolsPackData(toolName);
        if (list != null)
        {
            for (int j = 0; j < list.Count; j++)
            {
                for (int i = 0; i < _toolsPackWindowItemBts.Count; i++)
                {
                    ToolsPackWindowItemBtComponent toolspack = _toolsPackWindowItemBts[i].GetComponent<ToolsPackWindowItemBtComponent>();
                    int tooslIndex = toolspack.GetIndex();
                    if (_toolsPackWindowItemBts[i].name == list[j] && tooslIndex == index)
                    {
                        if (toolspack.GetGameNumber() > 1)
                        {
                            toolspack.ReduceGameNumber();
                        }
                        else if (toolspack.GetGameNumber() == 1)
                        {
                            toolspack.ReduceGameNumber();
                            GameObject g = _toolsPackWindowItemBts[i];
                            _toolsPackWindowItemBts.Remove(g);
                            UnityEngine.Object.Destroy(g);

                        }
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < _toolsPackWindowItemBts.Count; i++)
            {
                ToolsPackWindowItemBtComponent toolspack = _toolsPackWindowItemBts[i].GetComponent<ToolsPackWindowItemBtComponent>();

                if (_toolsPackWindowItemBts[i].name == toolName && toolspack.GetIndex() == index)
                {
                    if (toolspack.GetGameNumber() > 1)
                    {
                        toolspack.ReduceGameNumber();
                    }
                    else if (toolspack.GetGameNumber() == 1)
                    {
                        GameObject g = _toolsPackWindowItemBts[i];
                        _toolsPackWindowItemBts.Remove(g);
                        UnityEngine.Object.Destroy(g);
                    }
                }
            }
        }
    }
}