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

namespace EditorArt_Tools
{
    /// <summary>
    /// 批量导入场景Sprite资源到配置表
    /// </summary>
    public class BatchImportSceneSprites : 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 SPRITE_ROOT_PATH = "Assets/Art_SubModule/Art_Resource/Art_UISprites/Decorate";
        private const string MANIFEST_PATH = "Assets/Art_SubModule/Art_SO/art_table_manifest.json";

        private int startSceneIndex = 6;
        private int endSceneIndex = 50;
        private Vector2 scrollPosition;
        private List<ImportTask> importTasks = new List<ImportTask>();
        private bool isProcessing = false;

        private class ImportTask
        {
            public string SceneName;
            public string SoPath;
            public string SpriteFolderPath;
            public int SpriteCount;
            public bool FolderExists;
            public bool SoExists;
            public ImportStatus Status;
        }

        private enum ImportStatus
        {
            Pending,
            Success,
            Failed,
            Skipped
        }

        [MenuItem("美术工具/批量导入场景Sprite")]
        public static void ShowWindow()
        {
            var window = GetWindow<BatchImportSceneSprites>("批量导入场景Sprite");
            window.minSize = new Vector2(800, 600);
            window.Show();
        }

        private void OnEnable()
        {
            ScanTasks();
        }

        private void OnGUI()
        {
            EditorGUILayout.LabelField("批量导入场景Sprite资源", EditorStyles.boldLabel);
            EditorGUILayout.Space(10);

            EditorGUILayout.HelpBox(
                "此工具会自动扫描DecorateScene文件夹下的所有Scene配置表，\n" +
                "并从对应的Sprite文件夹中批量导入所有sprite资源。",
                MessageType.Info);

            EditorGUILayout.Space(10);

            // 设置范围
            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginChangeCheck();
            startSceneIndex = EditorGUILayout.IntField("起始场景序号:", startSceneIndex, GUILayout.Width(200));
            endSceneIndex = EditorGUILayout.IntField("结束场景序号:", endSceneIndex, GUILayout.Width(200));
            if (EditorGUI.EndChangeCheck())
            {
                ScanTasks();
            }
            
            if (GUILayout.Button("刷新扫描", GUILayout.Width(100)))
            {
                ScanTasks();
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space(10);

            // 统计信息
            int validTasks = importTasks.Count(t => t.FolderExists && t.SoExists && t.SpriteCount > 0);
            int totalSprites = importTasks.Where(t => t.FolderExists && t.SoExists).Sum(t => t.SpriteCount);
            
            EditorGUILayout.BeginHorizontal("box");
            EditorGUILayout.LabelField($"找到配置表: {importTasks.Count(t => t.SoExists)} 个");
            EditorGUILayout.LabelField($"可导入任务: {validTasks} 个");
            EditorGUILayout.LabelField($"总Sprite数: {totalSprites} 个");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space(10);

            // 任务列表
            EditorGUILayout.LabelField("导入任务列表:", EditorStyles.boldLabel);
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);

            foreach (var task in importTasks)
            {
                DrawTaskItem(task);
            }

            EditorGUILayout.EndScrollView();

            EditorGUILayout.Space(10);

            // 操作按钮
            GUI.enabled = !isProcessing && validTasks > 0;
            GUI.backgroundColor = Color.green;
            if (GUILayout.Button("开始批量导入", GUILayout.Height(40)))
            {
                StartBatchImport();
            }
            GUI.backgroundColor = Color.white;
            GUI.enabled = true;

            if (isProcessing)
            {
                EditorGUILayout.HelpBox("正在处理中，请稍候...", MessageType.Warning);
            }
        }

        private void DrawTaskItem(ImportTask task)
        {
            Color originalBg = GUI.backgroundColor;

            // 根据状态设置背景色
            switch (task.Status)
            {
                case ImportStatus.Success:
                    GUI.backgroundColor = new Color(0.5f, 1f, 0.5f, 0.3f);
                    break;
                case ImportStatus.Failed:
                    GUI.backgroundColor = new Color(1f, 0.5f, 0.5f, 0.3f);
                    break;
                case ImportStatus.Skipped:
                    GUI.backgroundColor = new Color(1f, 1f, 0.5f, 0.3f);
                    break;
            }

            EditorGUILayout.BeginVertical("box");
            GUI.backgroundColor = originalBg;

            EditorGUILayout.BeginHorizontal();

            // 状态图标
            string statusIcon = task.Status switch
            {
                ImportStatus.Success => "✔",
                ImportStatus.Failed => "✘",
                ImportStatus.Skipped => "⊘",
                _ => "○"
            };
            EditorGUILayout.LabelField(statusIcon, GUILayout.Width(20));

            // 场景名称
            EditorGUILayout.LabelField(task.SceneName, EditorStyles.boldLabel, GUILayout.Width(150));

            // SO状态
            if (task.SoExists)
            {
                GUI.color = Color.green;
                EditorGUILayout.LabelField("SO✔", GUILayout.Width(40));
            }
            else
            {
                GUI.color = Color.red;
                EditorGUILayout.LabelField("SO✘", GUILayout.Width(40));
            }
            GUI.color = Color.white;

            // 文件夹状态
            if (task.FolderExists)
            {
                GUI.color = Color.green;
                EditorGUILayout.LabelField($"文件夹✔ ({task.SpriteCount} sprites)", GUILayout.Width(150));
            }
            else
            {
                GUI.color = Color.red;
                EditorGUILayout.LabelField("文件夹✘", GUILayout.Width(150));
            }
            GUI.color = Color.white;

            GUILayout.FlexibleSpace();

            // 状态文本
            if (task.Status != ImportStatus.Pending)
            {
                EditorGUILayout.LabelField(task.Status.ToString(), GUILayout.Width(80));
            }

            EditorGUILayout.EndHorizontal();

            // 路径信息
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField($"SO: {task.SoPath}", EditorStyles.miniLabel);
            EditorGUILayout.LabelField($"Sprite: {task.SpriteFolderPath}", EditorStyles.miniLabel);
            EditorGUI.indentLevel--;

            EditorGUILayout.EndVertical();
        }

        private void ScanTasks()
        {
            importTasks.Clear();

            for (int i = startSceneIndex; i <= endSceneIndex; i++)
            {
                string sceneName = $"Scene{i}Resource";
                string soPath = $"{SO_ROOT_PATH}/{sceneName}.asset";
                string spriteFolderPath = $"{SPRITE_ROOT_PATH}/Scene{i}";

                var task = new ImportTask
                {
                    SceneName = sceneName,
                    SoPath = soPath,
                    SpriteFolderPath = spriteFolderPath,
                    SoExists = File.Exists(soPath),
                    FolderExists = Directory.Exists(spriteFolderPath),
                    Status = ImportStatus.Pending
                };

                // 统计Sprite数量
                if (task.FolderExists)
                {
                    string[] guids = AssetDatabase.FindAssets("t:Sprite", new[] { spriteFolderPath });
                    task.SpriteCount = guids.Length;
                }

                importTasks.Add(task);
            }

            Repaint();
        }

        private void StartBatchImport()
        {
            isProcessing = true;

            int successCount = 0;
            int failedCount = 0;
            int skippedCount = 0;
            int totalSpritesImported = 0;

            try
            {
                for (int i = 0; i < importTasks.Count; i++)
                {
                    var task = importTasks[i];

                    // 跳过无效任务
                    if (!task.SoExists || !task.FolderExists || task.SpriteCount == 0)
                    {
                        task.Status = ImportStatus.Skipped;
                        skippedCount++;
                        continue;
                    }

                    // 显示进度
                    float progress = (float)i / importTasks.Count;
                    EditorUtility.DisplayProgressBar("批量导入", $"正在处理 {task.SceneName}...", progress);

                    // 加载SO
                    var table = AssetDatabase.LoadAssetAtPath<ArtTableSO>(task.SoPath);
                    if (table == null)
                    {
                        Debug.LogError($"无法加载配置表: {task.SoPath}");
                        task.Status = ImportStatus.Failed;
                        failedCount++;
                        continue;
                    }

                    // 获取所有Sprite
                    string[] guids = AssetDatabase.FindAssets("t:Sprite", new[] { task.SpriteFolderPath });
                    if (guids.Length == 0)
                    {
                        task.Status = ImportStatus.Skipped;
                        skippedCount++;
                        continue;
                    }

                    // 获取当前最大ID
                    int startId = table.Items.Count > 0 ? table.Items.Max(item => item.Id) + 1 : 1;

                    // 导入Sprite
                    int importedCount = 0;
                    foreach (string guid in guids)
                    {
                        string assetPath = AssetDatabase.GUIDToAssetPath(guid);
                        Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(assetPath);

                        if (sprite != null)
                        {
                            // 检查是否已存在同名资源
                            if (table.Items.Any(item => item.Name == sprite.name))
                            {
                                Debug.LogWarning($"[{task.SceneName}] 跳过重复资源: {sprite.name}");
                                continue;
                            }

                            var newItem = new ArtItemData
                            {
                                Id = startId + importedCount,
                                Name = sprite.name,
                                Desc = "",
                                Sprite = sprite
                            };

                            table.Items.Add(newItem);
                            importedCount++;
                        }
                    }

                    if (importedCount > 0)
                    {
                        // 保存SO
                        EditorUtility.SetDirty(table);
                        AssetDatabase.SaveAssets();

                        // 同步JSON
                        SyncToJson(table);

                        task.Status = ImportStatus.Success;
                        successCount++;
                        totalSpritesImported += importedCount;

                        Debug.Log($"[{task.SceneName}] 成功导入 {importedCount} 个sprite资源");
                    }
                    else
                    {
                        task.Status = ImportStatus.Skipped;
                        skippedCount++;
                    }

                    Repaint();
                }

                // 更新Manifest
                UpdateManifest();
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                isProcessing = false;
            }

            // 显示结果
            string message = $"批量导入完成！\n\n" +
                           $"✔ 成功: {successCount} 个配置表\n" +
                           $"✘ 失败: {failedCount} 个\n" +
                           $"⊘ 跳过: {skippedCount} 个\n" +
                           $"📦 总共导入: {totalSpritesImported} 个sprite";

            EditorUtility.DisplayDialog("批量导入完成", message, "确定");
            Debug.Log($"[BatchImportSceneSprites] {message}");

            Repaint();
        }

        private void SyncToJson(ArtTableSO table)
        {
            string soPath = AssetDatabase.GetAssetPath(table);
            string relativePath = soPath.Replace(SO_ROOT_PATH, "").Replace(".asset", ".json");
            string jsonPath = JSON_ROOT_PATH + relativePath;

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

            // 创建JSON数据
            var jsonData = new ArtTableJsonData
            {
                TableId = table.TableId,
                TableName = table.TableName,
                Items = table.Items.Select(item => new ArtItemJsonData
                {
                    Id = item.Id,
                    Name = item.Name,
                    Desc = item.Desc,
                    SpritePath = item.Sprite != null ? AssetDatabase.GetAssetPath(item.Sprite) : "",
                    SpineAssetPath = item.SpineAsset != null ? AssetDatabase.GetAssetPath(item.SpineAsset) : "",
                    SpineAnimName = item.SpineAnimName
                }).ToList()
            };

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

            AssetDatabase.ImportAsset(jsonPath);
        }

        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);

                    if (manifest == null)
                    {
                        manifest = new ArtTableManifest();
                    }
                    if (manifest.preloadTableIds == null)
                    {
                        manifest.preloadTableIds = new int[0];
                    }
                }
                else
                {
                    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($"[BatchImportSceneSprites] Manifest文件已更新: {MANIFEST_PATH}");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"[BatchImportSceneSprites] 更新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;
        }
    }
}
