using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using UnityEngine;

namespace Data
{
    public class InitResource:Utils.Singleton<InitResource>
    {
        
        static readonly string[] dataSetFilePath = { "Data", "Mod" };
        const string coreNamespace = "Data";
        
        public Dictionary<string, Dictionary<string, Define>> defines = new();
        
        public void Init()
        {
            foreach (var path in dataSetFilePath)
            {
                // 获取程序所在的目录路径
                var appDirectory = AppDomain.CurrentDomain.BaseDirectory;

                // 构建Data目录的完整路径
                var dataDirectory = Path.Combine(appDirectory, path);
                try
                {
                    // 检查目录是否存在
                    if (Directory.Exists(dataDirectory))
                    {
                        // 获取目录下的所有子文件夹
                        var subDirectories = Directory.GetDirectories(dataDirectory);
                        // 遍历并输出每个子文件夹的名称
                        foreach (var dir in subDirectories)
                        {
                            var xmlFiles = Directory.GetFiles(dir, "*.xml", SearchOption.AllDirectories);
                            foreach (var xmlFile in xmlFiles)
                            {
                                LoadXmlData(xmlFile);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError($"发生错误: {ex.Message}");
                }
            }
            
        }
        public void LoadXmlData(string xmlFilePath)
        {
            // 检查文件是否存在
            if (!File.Exists(xmlFilePath))
            {
                Debug.LogWarning($"XML文件不存在: {xmlFilePath}");
                return;
            }
            XDocument xdoc = XDocument.Load(xmlFilePath);
            // 解析Define节点
            XElement rootElement = xdoc.Root;

            if (rootElement != null)
            {
                if (rootElement.Name == "Define")
                {
                    foreach (var element in rootElement.Elements())
                    {
                        var def = LoadDefine(element);
                        var className = element.Name.ToString();
                        var name = element.Element("defName")?.Value;
                        if (def != null && !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(className))
                        {
                            defines.TryAdd(className, new Dictionary<string, Define>());
                            defines[className][name] = (Define)def;
                        }
                    }
                }
            }

        }
        public object LoadDefine(XElement xElement)
        {
            var className = xElement.Name.ToString();
            var assembly = Assembly.GetExecutingAssembly();

            Type type;
            if (!className.Contains('.'))
            {
                // 尝试拼接默认命名空间   
                var fullClassName = coreNamespace + className;
                type = assembly.GetType(fullClassName);

                // 如果拼接命名空间后仍找不到，尝试直接查找（可能是全局命名空间下的类）
                
                if (type == null)
                {
                    type = assembly.GetType(className);
                }
            }
            else
            {
                // 直接查找
                type = assembly.GetType(className);
            }

            if (type == null)
            {
                Debug.LogError($"未定义的类型: {className}");
                return null;
            }

            var constructor = type.GetConstructor(Type.EmptyTypes);
            if (constructor == null)
            {
                Debug.LogError($"{className} 必须包含无参构造函数");
                return null;
            }

            // 3. 创建实例
            object instance;
            try
            {
                instance = Activator.CreateInstance(type);
            }
            catch (Exception ex)
            {
                Debug.LogError($"创建 {className} 实例失败: {ex.Message}");
                return null;
            }

            // 4. 检查是否继承自 Define
            if (instance is not Define define)
            {
                Debug.LogError($"{className} 必须继承自 Define");
                return null;
            }

            if (define.Init(xElement))
            {
                return define;
            }
            // 获取类的所有字段（不包括私有字段）
            var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);

            // 遍历字段并尝试从 XElement 中赋值
            foreach (var field in fields)
            {
                // 查找对应的 XElement 子元素
                var element = xElement.Element(field.Name);
                if (element != null)
                {
                    try
                    {
                        // 将子元素的值转换为目标类型并赋值
                        object value = Convert.ChangeType(element.Value, field.FieldType);
                        field.SetValue(define, value);
                    }
                    catch (Exception ex)
                    {
                        Debug.LogWarning($"Error setting field {field.Name}: {ex.Message}");
                    }
                }
            }
            return define;
        }

        public static void SetField(object obj, string fieldName, object value)
        {
            Type type = obj.GetType();
            FieldInfo field = type.GetField(fieldName);

            if (field != null)
            {
                field.SetValue(obj, Convert.ChangeType(value, field.FieldType));
            }
            else
            {
                Console.WriteLine($"Field '{fieldName}' not found.");
            }
        }
    }
}