using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using ArtResource;

namespace EditorArt_Tools
{
    /// <summary>
    /// 批量创建场景资源配置表
    /// </summary>
    public class BatchCreateSceneResources : EditorWindow
    {
        private const string SO_ROOT_PATH = "Assets/Art_SubModule/Art_SO/DecorateScene";
        private const string JSON_ROOT_PATH = "Assets/Art_SubModule/Art_Json/DecorateScene";
        private const string MANIFEST_PATH = "Assets/Art_SubModule/Art_SO/art_table_manifest.json";

        private int startIndex = 15;
        private int endIndex = 50;
        private string prefix = "Scene";
        private string suffix = "Resource";

        [MenuItem("美术工具/批量创建场景资源")]
        public static void ShowWindow()
        {
            var window = GetWindow<BatchCreateSceneResources>("批量创建场景资源");
            window.minSize = new Vector2(400, 300);
            window.Show();
        }

        private void OnGUI()
        {
            EditorGUILayout.LabelField("批量创建场景资源配置表", EditorStyles.boldLabel);
            EditorGUILayout.Space(10);

            EditorGUILayout.HelpBox(
                "将在以下路径创建配置表:\n" +
                $"SO: {SO_ROOT_PATH}\n" +
                $"JSON: {JSON_ROOT_PATH}",
                MessageType.Info);

            EditorGUILayout.Space(10);

            prefix = EditorGUILayout.TextField("前缀:", prefix);
            suffix = EditorGUILayout.TextField("后缀:", suffix);
            startIndex = EditorGUILayout.IntField("起始序号:", startIndex);
            endIndex = EditorGUILayout.IntField("结束序号:", endIndex);

            EditorGUILayout.Space(10);

            if (startIndex > endIndex)
            {
                EditorGUILayout.HelpBox("起始序号不能大于结束序号！", MessageType.Error);
                return;
            }

            int count = endIndex - startIndex + 1;
            EditorGUILayout.HelpBox($"将创建 {count} 个配置表", MessageType.Info);

            EditorGUILayout.Space(10);

            // 预览前几个文件名
            EditorGUILayout.LabelField("文件名预览:", EditorStyles.boldLabel);
            for (int i = 0; i < Mathf.Min(3, count); i++)
            {
                int index = startIndex + i;
                string fileName = $"{prefix}{index}{suffix}";
                EditorGUILayout.LabelField($"  {i + 1}. {fileName}.asset / {fileName}.json");
            }
            if (count > 3)
            {
                EditorGUILayout.LabelField($"  ... (共 {count} 个)");
            }

            EditorGUILayout.Space(20);

            GUI.backgroundColor = Color.green;
            if (GUILayout.Button("开始创建", GUILayout.Height(40)))
            {
                CreateResources();
            }
            GUI.backgroundColor = Color.white;
        }

        private void CreateResources()
        {
            if (startIndex > endIndex)
            {
                EditorUtility.DisplayDialog("错误", "起始序号不能大于结束序号！", "确定");
                return;
            }

            // 确保目录存在
            if (!Directory.Exists(SO_ROOT_PATH))
            {
                Directory.CreateDirectory(SO_ROOT_PATH);
            }
            if (!Directory.Exists(JSON_ROOT_PATH))
            {
                Directory.CreateDirectory(JSON_ROOT_PATH);
            }

            int successCount = 0;
            int skipCount = 0;
            List<string> createdFiles = new List<string>();
            int baseTableId = GetNextAvailableTableId();

            for (int i = startIndex; i <= endIndex; i++)
            {
                string fileName = $"{prefix}{i}{suffix}";
                string soPath = $"{SO_ROOT_PATH}/{fileName}.asset";
                string jsonPath = $"{JSON_ROOT_PATH}/{fileName}.json";

                // 检查文件是否已存在
                if (File.Exists(soPath) || File.Exists(jsonPath))
                {
                    skipCount++;
                    Debug.LogWarning($"文件已存在，跳过: {fileName}");
                    continue;
                }

                // 创建 ScriptableObject
                var newTable = ScriptableObject.CreateInstance<ArtTableSO>();
                newTable.TableName = fileName;
                newTable.TableId = baseTableId + (i - startIndex);
                newTable.Items = new List<ArtItemData>();

                // 保存 SO 文件
                AssetDatabase.CreateAsset(newTable, soPath);

                // 创建 JSON 文件
                var jsonData = new ArtTableJsonData
                {
                    TableId = newTable.TableId,
                    TableName = newTable.TableName,
                    Items = new List<ArtItemJsonData>()
                };

                string json = JsonUtility.ToJson(jsonData, true);
                File.WriteAllText(jsonPath, json);

                createdFiles.Add(fileName);
                successCount++;

                // 显示进度
                float progress = (float)(i - startIndex + 1) / (endIndex - startIndex + 1);
                EditorUtility.DisplayProgressBar("创建资源", $"正在创建 {fileName}...", progress);
            }

            EditorUtility.ClearProgressBar();

            // 刷新 AssetDatabase
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            // 更新 Manifest
            UpdateManifest();

            // 显示结果
            string message = $"创建完成！\n成功创建: {successCount} 个\n跳过已存在: {skipCount} 个";
            if (createdFiles.Count > 0)
            {
                message += $"\n\n创建的文件:\n{string.Join("\n", createdFiles.ToArray())}";
            }

            EditorUtility.DisplayDialog("批量创建完成", message, "确定");
            Debug.Log($"[BatchCreateSceneResources] {message}");
        }

        private int GetNextAvailableTableId()
        {
            // 查找所有现有的 ArtTableSO，获取最大的 TableId
            string[] guids = AssetDatabase.FindAssets("t:ArtTableSO");
            int maxId = 0;

            foreach (string guid in guids)
            {
                string path = AssetDatabase.GUIDToAssetPath(guid);
                var table = AssetDatabase.LoadAssetAtPath<ArtTableSO>(path);
                if (table != null && table.TableId > maxId)
                {
                    maxId = table.TableId;
                }
            }

            return maxId + 1;
        }

        private void UpdateManifest()
        {
            try
            {
                // 查找所有ArtTableSO文件
                string[] guids = AssetDatabase.FindAssets("t:ArtTableSO", new[] { "Assets/Art_SubModule/Art_SO" });
                List<string> tablePaths = new List<string>();

                foreach (string guid in guids)
                {
                    string path = AssetDatabase.GUIDToAssetPath(guid);
                    if (!string.IsNullOrEmpty(path))
                    {
                        tablePaths.Add(path);
                    }
                }

                // 排序路径
                tablePaths.Sort();

                // 创建或更新manifest
                ArtTableManifest manifest;

                // 如果文件存在，读取现有的预加载配置
                if (File.Exists(MANIFEST_PATH))
                {
                    string existingJson = File.ReadAllText(MANIFEST_PATH);
                    manifest = JsonUtility.FromJson<ArtTableManifest>(existingJson);

                    // 确保字段不为null
                    if (manifest == null)
                    {
                        manifest = new ArtTableManifest();
                    }
                    if (manifest.preloadTableIds == null)
                    {
                        manifest.preloadTableIds = new int[0];
                    }
                }
                else
                {
                    // 创建新的manifest
                    manifest = new ArtTableManifest
                    {
                        preloadTableIds = new int[0]
                    };
                }

                // 更新路径列表
                manifest.tablePaths = tablePaths.ToArray();

                // 序列化为JSON
                string json = JsonUtility.ToJson(manifest, true);

                // 确保目录存在
                string directory = Path.GetDirectoryName(MANIFEST_PATH);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                // 写入文件
                File.WriteAllText(MANIFEST_PATH, json);
                AssetDatabase.ImportAsset(MANIFEST_PATH);

                Debug.Log($"[BatchCreateSceneResources] Manifest文件已更新: {MANIFEST_PATH}, 共 {tablePaths.Count} 个表");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"[BatchCreateSceneResources] 更新Manifest文件失败: {ex.Message}");
            }
        }

        [System.Serializable]
        public class ArtTableManifest
        {
            public string[] tablePaths;
            public int[] preloadTableIds;
        }

        [System.Serializable]
        public class ArtTableJsonData
        {
            public int TableId;
            public string TableName;
            public List<ArtItemJsonData> Items;
        }

        [System.Serializable]
        public class ArtItemJsonData
        {
            public int Id;
            public string Name;
            public string Desc;
            public string SpritePath;
            public string SpineAssetPath;
            public string SpineAnimName;
        }
    }
}
