using UnityEditor;
using UnityEngine;
using System.IO;
using OfficeOpenXml;

/// <summary>
/// DecorateCost表格转换工具
/// 用于将Icon列的完整路径转换为只保留文件名
/// 例如: Icon/first/s1_icon_renwu_5 -> s1_icon_renwu_5
/// </summary>
public class DecorateCostTableConverter : EditorWindow
{
    private string excelPath = "E:\\WorkSpace\\Docs\\config\\DecorateCost.xlsx";
    private const string SHEET_NAME = "DecorateCost";
    private Vector2 scrollPosition;
    private string logMessage = "";
    
    [MenuItem("蹊径/转换DecorateCost表格")]
    public static void ShowWindow()
    {
        var window = GetWindow<DecorateCostTableConverter>("DecorateCost表格转换");
        window.minSize = new Vector2(500, 400);
    }
    
    private void OnGUI()
    {
        GUILayout.Label("DecorateCost表格Icon路径转换工具", EditorStyles.boldLabel);
        GUILayout.Space(10);
        
        EditorGUILayout.HelpBox(
            "此工具会将Icon列的完整路径转换为只保留文件名。\n" +
            "例如: Icon/first/s1_icon_renwu_5 → s1_icon_renwu_5\n\n" +
            "转换规则：\n" +
            "• 如果Icon路径包含'/'，则只保留最后一部分\n" +
            "• 如果Icon路径为空或不包含'/'，则保持不变\n" +
            "• 如果Action列包含'init_spine'，则跳过该行（不转换）\n" +
            "• 会自动备份原文件（添加.backup扩展名）", 
            MessageType.Info);
        
        GUILayout.Space(10);
        
        // Excel文件路径
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Excel路径:", GUILayout.Width(80));
        excelPath = EditorGUILayout.TextField(excelPath);
        if (GUILayout.Button("浏览", GUILayout.Width(60)))
        {
            string path = EditorUtility.OpenFilePanel("选择DecorateCost.xlsx", "", "xlsx");
            if (!string.IsNullOrEmpty(path))
            {
                excelPath = path;
            }
        }
        EditorGUILayout.EndHorizontal();
        
        GUILayout.Space(10);
        
        // 转换按钮
        if (GUILayout.Button("开始转换", GUILayout.Height(30)))
        {
            ConvertTable();
        }
        
        GUILayout.Space(10);
        
        // 日志显示区域
        if (!string.IsNullOrEmpty(logMessage))
        {
            EditorGUILayout.LabelField("转换日志:", EditorStyles.boldLabel);
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, GUILayout.Height(200));
            EditorGUILayout.TextArea(logMessage, GUILayout.ExpandHeight(true));
            EditorGUILayout.EndScrollView();
        }
    }
    
    private void ConvertTable()
    {
        logMessage = "";
        
        // 检查文件是否存在
        if (!File.Exists(excelPath))
        {
            logMessage = $"❌ 错误: 文件不存在\n路径: {excelPath}";
            Debug.LogError(logMessage);
            return;
        }
        
        try
        {
            // 设置EPPlus许可证
            
            // 备份原文件
            string backupPath = excelPath + ".backup";
            File.Copy(excelPath, backupPath, true);
            logMessage += $"✓ 已备份原文件到: {backupPath}\n\n";
            
            // 读取Excel
            using (var package = new ExcelPackage(new FileInfo(excelPath)))
            {
                var worksheet = package.Workbook.Worksheets[SHEET_NAME];
                if (worksheet == null)
                {
                    logMessage += $"❌ 错误: 找不到工作表 '{SHEET_NAME}'\n";
                    Debug.LogError(logMessage);
                    return;
                }
                
                // 查找Icon列的索引（假设第一行是标题行）
                int iconColIndex = -1;
                int sortIdColIndex = -1;
                int actionColIndex = -1;
                int totalCols = worksheet.Dimension.End.Column;
                
                for (int col = 1; col <= totalCols; col++)
                {
                    var cellValue = worksheet.Cells[1, col].Text.Trim();
                    if (cellValue == "Icon" || cellValue == "图标")
                    {
                        iconColIndex = col;
                    }
                    else if (cellValue == "SortId" || cellValue == "排序Id")
                    {
                        sortIdColIndex = col;
                    }
                    else if (cellValue == "Action" || cellValue == "行为")
                    {
                        actionColIndex = col;
                    }
                }
                
                if (iconColIndex == -1)
                {
                    logMessage += "❌ 错误: 找不到Icon列\n";
                    Debug.LogError(logMessage);
                    return;
                }
                
                logMessage += $"✓ 找到Icon列: 第{iconColIndex}列\n";
                if (sortIdColIndex != -1)
                {
                    logMessage += $"✓ 找到SortId列: 第{sortIdColIndex}列\n";
                }
                if (actionColIndex != -1)
                {
                    logMessage += $"✓ 找到Action列: 第{actionColIndex}列\n";
                }
                logMessage += "\n开始转换...\n\n";
                
                int totalRows = worksheet.Dimension.End.Row;
                int convertedCount = 0;
                int skippedCount = 0;
                int emptyCount = 0;
                int spineSkippedCount = 0;
                
                // 从第3行开始处理（第1行是英文标题，第2行是中文标题）
                for (int row = 3; row <= totalRows; row++)
                {
                    var iconCell = worksheet.Cells[row, iconColIndex];
                    string originalIcon = iconCell.Text.Trim();
                    
                    if (string.IsNullOrEmpty(originalIcon))
                    {
                        emptyCount++;
                        continue;
                    }
                    
                    // 检查Action列是否包含init_spine
                    bool hasInitSpine = false;
                    if (actionColIndex != -1)
                    {
                        var actionCell = worksheet.Cells[row, actionColIndex];
                        string actionValue = actionCell.Text.Trim();
                        if (!string.IsNullOrEmpty(actionValue) && actionValue.Contains("init_spine"))
                        {
                            hasInitSpine = true;
                        }
                    }
                    
                    // 如果包含init_spine，跳过这一行
                    if (hasInitSpine)
                    {
                        spineSkippedCount++;
                        logMessage += $"第{row}行: 跳过(包含init_spine): {originalIcon}\n";
                        continue;
                    }
                    
                    // 如果包含'/'，则只保留最后一部分
                    if (originalIcon.Contains("/"))
                    {
                        string newIcon = originalIcon.Substring(originalIcon.LastIndexOf('/') + 1);
                        iconCell.Value = newIcon;
                        
                        string sortInfo = "";
                        if (sortIdColIndex != -1)
                        {
                            var sortIdCell = worksheet.Cells[row, sortIdColIndex];
                            sortInfo = $" [SortId={sortIdCell.Text}]";
                        }
                        
                        logMessage += $"第{row}行{sortInfo}: {originalIcon} → {newIcon}\n";
                        convertedCount++;
                    }
                    else
                    {
                        skippedCount++;
                    }
                }
                
                // 保存修改
                package.Save();
                
                logMessage += $"\n转换完成！\n";
                logMessage += $"━━━━━━━━━━━━━━━━━━━━━━\n";
                logMessage += $"✓ 已转换: {convertedCount} 条\n";
                logMessage += $"• 跳过(无需转换): {skippedCount} 条\n";
                logMessage += $"• 跳过(init_spine): {spineSkippedCount} 条\n";
                logMessage += $"• 空值: {emptyCount} 条\n";
                logMessage += $"━━━━━━━━━━━━━━━━━━━━━━\n";
                logMessage += $"✓ 文件已保存: {excelPath}\n";
                
                Debug.Log("DecorateCost表格转换完成！");
                EditorUtility.DisplayDialog("转换完成", 
                    $"Icon路径转换完成！\n\n已转换: {convertedCount} 条\n跳过(无需转换): {skippedCount} 条\n跳过(init_spine): {spineSkippedCount} 条\n空值: {emptyCount} 条\n\n原文件已备份", 
                    "确定");
            }
        }
        catch (System.Exception ex)
        {
            logMessage += $"\n❌ 转换失败:\n{ex.Message}\n\n{ex.StackTrace}";
            Debug.LogError($"转换失败: {ex.Message}");
            EditorUtility.DisplayDialog("转换失败", $"转换过程中出现错误:\n\n{ex.Message}", "确定");
        }
    }
}
