using UnityEngine;
using UnityEditor;

public class PathSelectorWindow : EditorWindow
{

    // EditorPrefs 键名（每个路径一个唯一键）
    private const string PREFS_PATH1 = "PathSelector_Path1";
    private const string PREFS_PATH2 = "PathSelector_Path2";
    private const string PREFS_PATH3 = "PathSelector_Path3";
    private string path1 = "";
    private string path2 = "";
    private string path3 = "";
    private bool isLoad = false;

    [MenuItem("Tools/打表工具")]
    public static void ShowWindow()
    {
        // 显示窗口
        GetWindow<PathSelectorWindow>("打表工具");
    }

    private void OnEnable()
    {
        // 窗口打开时加载保存的路径
        path1 = EditorPrefs.GetString(PREFS_PATH1, "");
        path2 = EditorPrefs.GetString(PREFS_PATH2, "");
        path3 = EditorPrefs.GetString(PREFS_PATH3, "");
    }

    private void OnDisable()
    {
        // 窗口关闭时保存（虽然每次修改都会保存，但以防万一）
        SavePaths();
    }

    private void OnGUI()
    {
        GUILayout.Space(10);

        // 绘制三个路径选择栏
        DrawPathField("excel文件路径:", ref path1);
        DrawPathField("实体类位置:", ref path2);
        DrawPathField("Asset位置:", ref path3);

        GUILayout.Space(10);

        // 两个按钮
        if (GUILayout.Button("生成实体类"))
        {
            ExcelToEntityGenerator.LoadAll(path1, path2, path3);
            
            isLoad = true;
        }

        if (GUILayout.Button("生成Asset"))
        {
            if (!isLoad)
            {
                Debug.LogError("请先生成实体类");
            }
            isLoad = false;
            ExcelToEntityGenerator.CreateAllContainers();
            
        }
        GUILayout.Label("说明：\n1. 请选择excel文件路径、实体类位置、Asset位置。\n2. 点击生成实体类。\n3. 点击生成Asset。");
    }

    /// <summary>
    /// 绘制一个带浏览按钮的路径输入行
    /// </summary>
    private void DrawPathField(string label, ref string path)
    {
        EditorGUILayout.BeginHorizontal();

        // 标签
        EditorGUILayout.LabelField(label, GUILayout.Width(85));
        
        // 路径文本框
        path = EditorGUILayout.TextField(path);

        // 浏览按钮
        if (GUILayout.Button("...", GUILayout.Width(30)))
        {
            // 打开文件夹选择对话框（默认从项目根目录开始）
            string selectedPath = EditorUtility.OpenFolderPanel("选择文件夹", Application.dataPath, "");
            if (!string.IsNullOrEmpty(selectedPath))
            {
                // 若需要，可以将绝对路径转换为相对路径（例如相对于项目根目录）
                // 这里直接保存绝对路径
                path = selectedPath;
            }
        }

        EditorGUILayout.EndHorizontal();
    }

    private void SavePaths()
    {
        EditorPrefs.SetString(PREFS_PATH1, path1);
        EditorPrefs.SetString(PREFS_PATH2, path2);
        EditorPrefs.SetString(PREFS_PATH3, path3);
    }
}