using UnityEngine;
using UnityEditor;
using System.IO;

/// <summary>
/// Y-Sort 批量添加工具
/// 
/// 使用方法：
/// 1. 在Unity菜单栏点击 Tools -> Y-Sort -> 批量添加YSorter
/// 2. 会自动给Player、Enemy和所有场景预制体添加YSorter组件
/// 3. 根据物体类型自动设置baseSortingOrder
/// </summary>
public class YSortBatchAdder : Editor
{
    [MenuItem("Tools/Y-Sort/批量添加YSorter到所有预制体")]
    public static void AddYSorterToAllPrefabs()
    {
        string prefabFolder = "Assets/2.5D Engine/Prefabs";
        
        if (!Directory.Exists(prefabFolder))
        {
            Debug.LogError($"找不到预制体文件夹: {prefabFolder}");
            return;
        }

        string[] prefabPaths = Directory.GetFiles(prefabFolder, "*.prefab", SearchOption.AllDirectories);
        int count = 0;

        foreach (string path in prefabPaths)
        {
            string normalizedPath = path.Replace("\\", "/");
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(normalizedPath);
            
            if (prefab == null) continue;

            // 检查是否已经有YSorter
            if (prefab.GetComponentInChildren<YSorter>() != null)
            {
                Debug.Log($"跳过 {prefab.name} - 已有YSorter");
                continue;
            }

            // 根据预制体名称判断类型并设置baseSortingOrder
            int baseOrder = DetermineBaseOrder(prefab.name);

            // 添加到根物体
            AddYSorterToPrefab(prefab, baseOrder);
            count++;
            
            Debug.Log($"已添加 YSorter 到 {prefab.name} (baseSortingOrder: {baseOrder})");
        }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        
        Debug.Log($"完成！共添加了 {count} 个YSorter");
    }

    [MenuItem("Tools/Y-Sort/添加YSorter到Player")]
    public static void AddYSorterToPlayer()
    {
        string playerPath = "Assets/2.5D Engine/Player.prefab";
        GameObject player = AssetDatabase.LoadAssetAtPath<GameObject>(playerPath);
        
        if (player == null)
        {
            Debug.LogError($"找不到Player预制体: {playerPath}");
            return;
        }

        AddYSorterToPrefab(player, 2000); // 角色层
        AssetDatabase.SaveAssets();
        Debug.Log("已添加YSorter到Player (baseSortingOrder: 2000)");
    }

    [MenuItem("Tools/Y-Sort/添加YSorter到Enemy")]
    public static void AddYSorterToEnemy()
    {
        string enemyPath = "Assets/2.5D Engine/Enemy.prefab";
        GameObject enemy = AssetDatabase.LoadAssetAtPath<GameObject>(enemyPath);
        
        if (enemy == null)
        {
            Debug.LogError($"找不到Enemy预制体: {enemyPath}");
            return;
        }

        AddYSorterToPrefab(enemy, 2000); // 角色层
        AssetDatabase.SaveAssets();
        Debug.Log("已添加YSorter到Enemy (baseSortingOrder: 2000)");
    }

    private static 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;
    }

    private static void AddYSorterToPrefab(GameObject prefab, int baseSortingOrder)
    {
        // 使用PrefabUtility打开预制体进行编辑
        string prefabPath = AssetDatabase.GetAssetPath(prefab);
        GameObject prefabRoot = PrefabUtility.LoadPrefabContents(prefabPath);

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

        // 保存预制体
        PrefabUtility.SaveAsPrefabAsset(prefabRoot, prefabPath);
        PrefabUtility.UnloadPrefabContents(prefabRoot);
    }
}
