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

/// <summary>
/// Y-Sort 批量添加工具 - EditorWindow版本
/// </summary>
public class YSortEditorWindow : EditorWindow
{
    private Vector2 scrollPosition;
    private List<string> logMessages = new List<string>();

    [MenuItem("Tools/Y-Sort/Y-Sort管理工具")]
    public static void ShowWindow()
    {
        GetWindow<YSortEditorWindow>("Y-Sort管理工具");
    }

    private void OnGUI()
    {
        GUILayout.Label("Y-Sort批量添加", EditorStyles.boldLabel);
        
        GUILayout.Space(10);
        
        if (GUILayout.Button("添加YSorter到Player预制体", GUILayout.Height(30)))
        {
            AddToPlayer();
        }
        
        if (GUILayout.Button("添加YSorter到Enemy预制体", GUILayout.Height(30)))
        {
            AddToEnemy();
        }
        
        GUILayout.Space(10);
        
        if (GUILayout.Button("批量添加到所有场景预制体 (2.5D Engine/Prefabs)", GUILayout.Height(30)))
        {
            AddToAllPrefabs();
        }
        
        GUILayout.Space(10);
        
        if (GUILayout.Button("清除日志", GUILayout.Height(20)))
        {
            logMessages.Clear();
            Repaint();
        }
        
        GUILayout.Space(10);
        GUILayout.Label("日志输出:", EditorStyles.boldLabel);
        
        scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.ExpandHeight(true));
        foreach (string msg in logMessages)
        {
            GUILayout.Label(msg);
        }
        GUILayout.EndScrollView();
    }

    private void AddLog(string msg)
    {
        logMessages.Add(msg);
        Debug.Log(msg);
        Repaint();
    }

    private void AddToPlayer()
    {
        string path = "Assets/2.5D Engine/Player.prefab";
        AddYSorterToPrefab(path, 2000, "Player");
    }

    private void AddToEnemy()
    {
        string path = "Assets/2.5D Engine/Enemy.prefab";
        AddYSorterToPrefab(path, 2000, "Enemy");
    }

    private void AddToAllPrefabs()
    {
        string folder = "Assets/2.5D Engine/Prefabs";
        string[] files = System.IO.Directory.GetFiles(folder, "*.prefab", System.IO.SearchOption.AllDirectories);
        
        int count = 0;
        foreach (string file in files)
        {
            string normalizedPath = file.Replace("\\", "/");
            string prefabName = System.IO.Path.GetFileNameWithoutExtension(file);
            int baseOrder = DetermineBaseOrder(prefabName);
            
            if (AddYSorterToPrefab(normalizedPath, baseOrder, prefabName))
            {
                count++;
            }
        }
        
        AddLog($"完成！共添加了 {count} 个YSorter");
    }

    private bool AddYSorterToPrefab(string path, int baseSortingOrder, string displayName)
    {
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
        if (prefab == null)
        {
            AddLog($"错误: 找不到预制体 {displayName}");
            return false;
        }

        // 检查是否已有YSorter
        if (prefab.GetComponentInChildren<YSorter>() != null)
        {
            AddLog($"跳过 {displayName} - 已有YSorter");
            return false;
        }

        // 打开预制体进行编辑
        string assetPath = AssetDatabase.GetAssetPath(prefab);
        GameObject prefabRoot = PrefabUtility.LoadPrefabContents(assetPath);
        
        if (prefabRoot == null)
        {
            AddLog($"错误: 无法加载预制体内容 {displayName}");
            return false;
        }

        // 添加YSorter组件
        YSorter ySorter = prefabRoot.AddComponent<YSorter>();
        
        // 设置baseSortingOrder
        SerializedObject so = new SerializedObject(ySorter);
        SerializedProperty prop = so.FindProperty("baseSortingOrder");
        if (prop != null)
        {
            prop.intValue = baseSortingOrder;
            so.ApplyModifiedProperties();
        }

        // 保存
        PrefabUtility.SaveAsPrefabAsset(prefabRoot, assetPath);
        PrefabUtility.UnloadPrefabContents(prefabRoot);

        AddLog($"✓ 已添加 YSorter 到 {displayName} (baseSortingOrder: {baseSortingOrder})");
        return true;
    }

    private int DetermineBaseOrder(string prefabName)
    {
        string nameLower = prefabName.ToLower();

        if (nameLower.Contains("ground") || nameLower.Contains("floor"))
            return 0;
        if (nameLower.Contains("shadow"))
            return 500;
        if (nameLower.Contains("grass") || nameLower.Contains("flower") || 
            nameLower.Contains("leaf") || nameLower.Contains("leaves"))
            return 800;
        if (nameLower.Contains("rock") || nameLower.Contains("bamboo") || 
            nameLower.Contains("barrel") || nameLower.Contains("box") ||
            nameLower.Contains("log") || nameLower.Contains("board") ||
            nameLower.Contains("bush") || nameLower.Contains("bonfire") ||
            nameLower.Contains("candle") || nameLower.Contains("carcasses") ||
            nameLower.Contains("lotus") || nameLower.Contains("pedestal") ||
            nameLower.Contains("scarecrow") || nameLower.Contains("skeleton") ||
            nameLower.Contains("skull") || nameLower.Contains("spear") ||
            nameLower.Contains("statue") || nameLower.Contains("tent") ||
            nameLower.Contains("tenticles") || nameLower.Contains("wooden") ||
            nameLower.Contains("bag") || nameLower.Contains("house"))
            return 1000;

        return 1000;
    }
}
