using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using OfficeOpenXml;
using Debug = UnityEngine.Debug;

namespace DesignTools
{
    /// <summary>
    /// 环境音配置Editor工具
    /// 读取Docs/config/Sound.xlsx的Ambient Sheet和Sound Sheet，编辑环境音配置和环境音属性
    /// </summary>
    public class AmbientSoundConfigEditor : BaseDesignToolEditor
    {
        private const string SOUND_EXCEL_NAME = "Sound.xlsx";
        private const string AMBIENT_SHEET_NAME = "Ambient";
        private const string SOUND_SHEET_NAME = "Sound";
        private const string LANGUAGE_EXCEL_NAME = "AllLanguage.xlsx";
        private const string LANGUAGE_SHEET_NAME = "client";
        
        // Ambient表格列索引
        private const int COL_ID = 1;
        private const int COL_AREA_ID = 2;
        private const int COL_SOUND_ID = 3;
        
        // Sound表格列索引
        private const int COL_SOUND_ID_IN_SOUND = 1;
        private const int COL_COMMENT = 2;
        private const int COL_ASSET_NAME = 3;
        private const int COL_PRIORITY = 4;
        private const int COL_LOOP = 5;
        private const int COL_VOLUME = 6;
        private const int COL_SPATIAL_BLEND = 7;
        private const int COL_MAX_DISTANCE = 8;
        
        // 固定的环境音ID列表
        private static readonly int[] AMBIENT_SOUND_IDS = { 10172, 10173, 10174, 10175, 10176, 10177, 10178, 10179 };
        
        private List<AmbientSoundData> ambientDataList = new List<AmbientSoundData>();
        private Dictionary<int, SoundData> soundDataDict = new Dictionary<int, SoundData>(); // 环境音的Sound数据
        private Dictionary<string, Dictionary<string, string>> languageDict = new Dictionary<string, Dictionary<string, string>>();
        
        // UI状态
        private Vector2 ambientScrollPosition;
        private Vector2 soundScrollPosition;
        private int selectedTab = 0; // 0=场景关联, 1=环境音编辑
        
        [MenuItem("策划工具/声音/环境音配置")]
        public static void ShowWindow()
        {
            var window = GetWindow<AmbientSoundConfigEditor>("环境音配置");
            window.minSize = window.GetMinWindowSize();
            window.Show();
        }
        
        #region 基类实现
        
        protected override string GetDocsPathPrefKey()
        {
            return "AmbientSoundConfigEditor_DocsPath";
        }
        
        protected override string GetWindowTitle()
        {
            return "环境音配置工具";
        }
        
        protected override Vector2 GetMinWindowSize()
        {
            return new Vector2(1200, 700);
        }
        
        protected override void LoadConfigData()
        {
            // 1. 加载语言表
            LoadLanguageData();
            
            // 2. 加载Sound表中的环境音数据
            LoadSoundData();
            
            // 3. 加载Ambient表
            LoadAmbientExcel();
        }
        
        protected override void DrawDataEditor()
        {
            // 标签页切换
            EditorGUILayout.BeginHorizontal();
            
            string[] tabNames = { "场景环境音关联", "环境音属性编辑" };
            selectedTab = GUILayout.Toolbar(selectedTab, tabNames, GUILayout.Height(30));
            
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.Space(5);
            
            // 根据选中的标签页显示不同内容
            if (selectedTab == 0)
            {
                DrawAmbientDataTable();
            }
            else
            {
                DrawSoundDataTable();
            }
        }
        
        protected override bool ShowBottomButtons()
        {
            return false; // 使用顶部保存按钮
        }
        
        protected override void SaveDataToExcel()
        {
            SaveToExcel();
        }
        
        #endregion
        
        #region 数据加载
        
        /// <summary>
        /// 加载语言表
        /// </summary>
        private void LoadLanguageData()
        {
            languageDict.Clear();
            
            string languageExcelPath = GetDocsConfigFilePath(LANGUAGE_EXCEL_NAME);
            
            if (!File.Exists(languageExcelPath))
            {
                Debug.LogWarning($"未找到语言表: {languageExcelPath}");
                return;
            }
            
            // ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            
            using (var package = new ExcelPackage(new FileInfo(languageExcelPath)))
            {
                var worksheet = package.Workbook.Worksheets[LANGUAGE_SHEET_NAME];
                
                if (worksheet == null)
                {
                    Debug.LogWarning($"未找到Sheet: {LANGUAGE_SHEET_NAME}");
                    return;
                }
                
                int rowCount = worksheet.Dimension?.Rows ?? 0;
                if (rowCount < 2)
                {
                    return;
                }
                
                // 第一行是表头，找到各列的索引
                int keyColIndex = -1;
                int zhCNColIndex = -1;
                
                for (int col = 1; col <= worksheet.Dimension.Columns; col++)
                {
                    string header = worksheet.Cells[1, col].Text.Trim();
                    if (header.Equals("key", StringComparison.OrdinalIgnoreCase) || 
                        header.Equals("Key", StringComparison.OrdinalIgnoreCase))
                    {
                        keyColIndex = col;
                    }
                    else if (header == "zh_CN")
                    {
                        zhCNColIndex = col;
                    }
                }
                
                if (keyColIndex == -1 || zhCNColIndex == -1)
                {
                    Debug.LogWarning($"语言表格式错误，未找到key或zh_CN列（已扫描 {worksheet.Dimension.Columns} 列）");
                    return;
                }
                
                // 从第3行开始读取数据（第1行是字段名，第2行是中文说明）
                for (int row = 3; row <= rowCount; row++)
                {
                    string key = worksheet.Cells[row, keyColIndex].Text.Trim();
                    string zhCN = worksheet.Cells[row, zhCNColIndex].Text.Trim();
                    
                    if (!string.IsNullOrEmpty(key))
                    {
                        if (!languageDict.ContainsKey(key))
                        {
                            languageDict[key] = new Dictionary<string, string>();
                        }
                        languageDict[key]["zh_CN"] = zhCN;
                    }
                }
            }
            
            Debug.Log($"加载了 {languageDict.Count} 条语言数据");
        }
        
        /// <summary>
        /// 加载Sound表中的环境音数据
        /// </summary>
        private void LoadSoundData()
        {
            soundDataDict.Clear();
            
            string excelPath = GetDocsConfigFilePath(SOUND_EXCEL_NAME);
            
            if (!File.Exists(excelPath))
            {
                EditorUtility.DisplayDialog("错误", 
                    $"未找到Sound.xlsx\n路径: {excelPath}", 
                    "确定");
                return;
            }
            
            // ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            
            using (var package = new ExcelPackage(new FileInfo(excelPath)))
            {
                var worksheet = package.Workbook.Worksheets[SOUND_SHEET_NAME];
                
                if (worksheet == null)
                {
                    EditorUtility.DisplayDialog("错误", 
                        $"未找到Sheet: {SOUND_SHEET_NAME}", 
                        "确定");
                    return;
                }
                
                int rowCount = worksheet.Dimension?.Rows ?? 0;
                
                // 从第3行开始读取（第1行是字段名，第2行是中文说明）
                for (int row = 3; row <= rowCount; row++)
                {
                    string idText = worksheet.Cells[row, COL_SOUND_ID_IN_SOUND].Text;
                    if (string.IsNullOrEmpty(idText))
                    {
                        continue;
                    }
                    
                    if (!int.TryParse(idText, out int soundId))
                    {
                        continue;
                    }
                    
                    // 只加载固定的环境音ID
                    if (!AMBIENT_SOUND_IDS.Contains(soundId))
                    {
                        continue;
                    }
                    
                    var soundData = new SoundData
                    {
                        Id = soundId,
                        Comment = worksheet.Cells[row, COL_COMMENT].Text,
                        AssetName = worksheet.Cells[row, COL_ASSET_NAME].Text,
                        Priority = ParseInt(worksheet.Cells[row, COL_PRIORITY].Text, 0),
                        Loop = ParseBool(worksheet.Cells[row, COL_LOOP].Text),
                        Volume = ParseFloat(worksheet.Cells[row, COL_VOLUME].Text, 1f),
                        SpatialBlend = ParseFloat(worksheet.Cells[row, COL_SPATIAL_BLEND].Text, 0f),
                        MaxDistance = ParseFloat(worksheet.Cells[row, COL_MAX_DISTANCE].Text, 100f),
                        RowIndex = row
                    };
                    
                    soundDataDict[soundId] = soundData;
                }
            }
            
            Debug.Log($"加载了 {soundDataDict.Count} 个环境音数据");
        }
        
        /// <summary>
        /// 加载Ambient.xlsx
        /// </summary>
        private void LoadAmbientExcel()
        {
            ambientDataList.Clear();
            
            string excelPath = GetDocsConfigFilePath(SOUND_EXCEL_NAME);
            
            if (!File.Exists(excelPath))
            {
                EditorUtility.DisplayDialog("错误", 
                    $"未找到Sound.xlsx\n路径: {excelPath}", 
                    "确定");
                return;
            }
            
            // ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            
            using (var package = new ExcelPackage(new FileInfo(excelPath)))
            {
                var worksheet = package.Workbook.Worksheets[AMBIENT_SHEET_NAME];
                
                if (worksheet == null)
                {
                    EditorUtility.DisplayDialog("错误", 
                        $"未找到Sheet: {AMBIENT_SHEET_NAME}", 
                        "确定");
                    return;
                }
                
                int rowCount = worksheet.Dimension?.Rows ?? 0;
                
                // 从第3行开始读取（第1行是字段名，第2行是中文说明）
                for (int row = 3; row <= rowCount; row++)
                {
                    string idText = worksheet.Cells[row, COL_ID].Text;
                    if (string.IsNullOrEmpty(idText))
                    {
                        continue;
                    }
                    
                    if (!int.TryParse(idText, out int id))
                    {
                        continue;
                    }
                    
                    int areaId = ParseInt(worksheet.Cells[row, COL_AREA_ID].Text, 0);
                    int soundId = ParseInt(worksheet.Cells[row, COL_SOUND_ID].Text, 0);
                    
                    var ambientData = new AmbientSoundData
                    {
                        Id = id,
                        AreaId = areaId,
                        SoundId = soundId,
                        RowIndex = row
                    };
                    
                    ambientDataList.Add(ambientData);
                }
            }
            
            Debug.Log($"加载了 {ambientDataList.Count} 条环境音配置");
        }
        
        #endregion
        
        #region UI绘制
        
        /// <summary>
        /// 绘制环境音数据表格
        /// </summary>
        private void DrawAmbientDataTable()
        {
            EditorGUILayout.BeginVertical("box");
            
            // 顶部信息和保存按钮
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField($"共 {ambientDataList.Count} 条环境音配置", EditorStyles.boldLabel);
            
            GUILayout.FlexibleSpace();
            
            // 添加新行按钮
            if (GUILayout.Button("➕ 添加新行", GUILayout.Height(25), GUILayout.Width(100)))
            {
                AddNewAmbientData();
            }
            
            // 保存按钮
            GUI.backgroundColor = Color.green;
            if (GUILayout.Button("💾 保存到Excel", GUILayout.Height(25), GUILayout.Width(120)))
            {
                SaveToExcel();
            }
            GUI.backgroundColor = Color.white;
            
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.Space(5);
            
            // 表头
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            EditorGUILayout.LabelField("ID", EditorStyles.boldLabel, GUILayout.Width(50));
            EditorGUILayout.LabelField("场景ID", EditorStyles.boldLabel, GUILayout.Width(60));
            EditorGUILayout.LabelField("场景名称", EditorStyles.boldLabel, GUILayout.Width(200));
            EditorGUILayout.LabelField("环境音", EditorStyles.boldLabel, GUILayout.Width(300));
            EditorGUILayout.LabelField("操作", EditorStyles.boldLabel, GUILayout.Width(60));
            EditorGUILayout.EndHorizontal();
            
            // 数据行
            ambientScrollPosition = EditorGUILayout.BeginScrollView(ambientScrollPosition, GUILayout.ExpandHeight(true));
            
            for (int i = 0; i < ambientDataList.Count; i++)
            {
                var data = ambientDataList[i];
                DrawAmbientDataRow(data, i);
            }
            
            EditorGUILayout.EndScrollView();
            
            EditorGUILayout.EndVertical();
        }
        
        /// <summary>
        /// 绘制单行环境音数据
        /// </summary>
        private void DrawAmbientDataRow(AmbientSoundData data, int index)
        {
            EditorGUILayout.BeginHorizontal("box");
            
            // ID（只读，自增）
            EditorGUILayout.LabelField(data.Id.ToString(), GUILayout.Width(50));
            
            // 场景ID（可编辑）
            int newAreaId = EditorGUILayout.IntField(data.AreaId, GUILayout.Width(60));
            if (newAreaId != data.AreaId)
            {
                data.AreaId = newAreaId;
            }
            
            // 场景名称（显示 AreaId + 中文名）
            string sceneName = GetSceneName(data.AreaId);
            EditorGUILayout.LabelField(sceneName, GUILayout.Width(200));
            
            // 环境音下拉选择
            int currentIndex = GetSoundIndex(data.SoundId);
            string[] soundOptions = GetSoundOptions();
            int[] soundIds = AMBIENT_SOUND_IDS;
            
            int newIndex = EditorGUILayout.Popup(currentIndex, soundOptions, GUILayout.Width(300));
            if (newIndex != currentIndex && newIndex >= 0 && newIndex < soundIds.Length)
            {
                data.SoundId = soundIds[newIndex];
            }
            
            // 删除按钮
            GUI.backgroundColor = new Color(1f, 0.3f, 0.3f);
            if (GUILayout.Button("删除", GUILayout.Width(60), GUILayout.Height(20)))
            {
                if (EditorUtility.DisplayDialog("确认删除", 
                    $"确定要删除ID为 {data.Id} 的环境音配置吗？", 
                    "删除", "取消"))
                {
                    ambientDataList.RemoveAt(index);
                }
            }
            GUI.backgroundColor = Color.white;
            
            EditorGUILayout.EndHorizontal();
        }
        
        /// <summary>
        /// 绘制环境音属性编辑表格
        /// </summary>
        private void DrawSoundDataTable()
        {
            EditorGUILayout.BeginVertical("box");
            
            // 顶部信息和保存按钮
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField($"共 {soundDataDict.Count} 个环境音", EditorStyles.boldLabel);
            
            GUILayout.FlexibleSpace();
            
            // 保存按钮
            GUI.backgroundColor = Color.green;
            if (GUILayout.Button("💾 保存到Excel", GUILayout.Height(25), GUILayout.Width(120)))
            {
                SaveToExcel();
            }
            GUI.backgroundColor = Color.white;
            
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.Space(5);
            
            // 表头
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            EditorGUILayout.LabelField("ID", EditorStyles.boldLabel, GUILayout.Width(60));
            EditorGUILayout.LabelField("策划备注", EditorStyles.boldLabel, GUILayout.Width(120));
            EditorGUILayout.LabelField("资源名称", EditorStyles.boldLabel, GUILayout.Width(180));
            EditorGUILayout.LabelField("优先级", EditorStyles.boldLabel, GUILayout.Width(60));
            EditorGUILayout.LabelField("循环", EditorStyles.boldLabel, GUILayout.Width(50));
            EditorGUILayout.LabelField("音量", EditorStyles.boldLabel, GUILayout.Width(120));
            EditorGUILayout.LabelField("空间混合", EditorStyles.boldLabel, GUILayout.Width(120));
            EditorGUILayout.LabelField("最大距离", EditorStyles.boldLabel, GUILayout.Width(80));
            EditorGUILayout.EndHorizontal();
            
            // 数据行
            soundScrollPosition = EditorGUILayout.BeginScrollView(soundScrollPosition, GUILayout.ExpandHeight(true));
            
            // 按固定顺序显示环境音
            foreach (int soundId in AMBIENT_SOUND_IDS)
            {
                if (soundDataDict.ContainsKey(soundId))
                {
                    DrawSoundDataRow(soundDataDict[soundId]);
                }
            }
            
            EditorGUILayout.EndScrollView();
            
            EditorGUILayout.EndVertical();
        }
        
        /// <summary>
        /// 绘制单行环境音Sound数据
        /// </summary>
        private void DrawSoundDataRow(SoundData data)
        {
            EditorGUILayout.BeginHorizontal("box");
            
            // ID（只读）
            EditorGUILayout.LabelField(data.Id.ToString(), GUILayout.Width(60));
            
            // 策划备注
            string newComment = EditorGUILayout.TextField(data.Comment, GUILayout.Width(120));
            if (newComment != data.Comment)
            {
                data.Comment = newComment;
            }
            
            // 资源名称
            string newAssetName = EditorGUILayout.TextField(data.AssetName, GUILayout.Width(180));
            if (newAssetName != data.AssetName)
            {
                data.AssetName = newAssetName;
            }
            
            // 优先级
            int newPriority = EditorGUILayout.IntField(data.Priority, GUILayout.Width(60));
            if (newPriority != data.Priority)
            {
                data.Priority = Mathf.Clamp(newPriority, -128, 128);
            }
            
            // 循环
            bool newLoop = EditorGUILayout.Toggle(data.Loop, GUILayout.Width(50));
            if (newLoop != data.Loop)
            {
                data.Loop = newLoop;
            }
            
            // 音量（带滑动条）
            float newVolume = EditorGUILayout.Slider(data.Volume, 0f, 1f, GUILayout.Width(120));
            if (!Mathf.Approximately(newVolume, data.Volume))
            {
                data.Volume = newVolume;
            }
            
            // 空间混合（带滑动条）
            float newSpatialBlend = EditorGUILayout.Slider(data.SpatialBlend, 0f, 1f, GUILayout.Width(120));
            if (!Mathf.Approximately(newSpatialBlend, data.SpatialBlend))
            {
                data.SpatialBlend = newSpatialBlend;
            }
            
            // 最大距离
            float newMaxDistance = EditorGUILayout.FloatField(data.MaxDistance, GUILayout.Width(80));
            if (!Mathf.Approximately(newMaxDistance, data.MaxDistance))
            {
                data.MaxDistance = Mathf.Max(0f, newMaxDistance);
            }
            
            EditorGUILayout.EndHorizontal();
        }
        
        #endregion
        
        #region 数据操作
        
        /// <summary>
        /// 添加新环境音数据
        /// </summary>
        private void AddNewAmbientData()
        {
            int newId = ambientDataList.Count > 0 ? ambientDataList.Max(d => d.Id) + 1 : 1;
            
            var newData = new AmbientSoundData
            {
                Id = newId,
                AreaId = 0,
                SoundId = 10172, // 默认第一个环境音
                RowIndex = -1 // 新行，还没有Excel行索引
            };
            
            ambientDataList.Add(newData);
        }
        
        /// <summary>
        /// 获取场景名称
        /// </summary>
        private string GetSceneName(int areaId)
        {
            if (areaId == 0)
            {
                return "未设置";
            }
            
            string key = $"CS_ScenePanel_Scene{areaId}";
            
            if (languageDict.ContainsKey(key) && languageDict[key].ContainsKey("zh_CN"))
            {
                string zhName = languageDict[key]["zh_CN"];
                return $"{areaId} - {zhName}";
            }
            
            return $"{areaId} - (未找到名称)";
        }
        
        /// <summary>
        /// 获取环境音选项（用于下拉框）
        /// </summary>
        private string[] GetSoundOptions()
        {
            List<string> options = new List<string>();
            foreach (int soundId in AMBIENT_SOUND_IDS)
            {
                if (soundDataDict.ContainsKey(soundId))
                {
                    var soundData = soundDataDict[soundId];
                    options.Add($"{soundId} - {soundData.Comment} - {soundData.AssetName}");
                }
                else
                {
                    options.Add($"{soundId} - (未加载)");
                }
            }
            return options.ToArray();
        }
        
        /// <summary>
        /// 获取SoundId在下拉列表中的索引
        /// </summary>
        private int GetSoundIndex(int soundId)
        {
            for (int i = 0; i < AMBIENT_SOUND_IDS.Length; i++)
            {
                if (AMBIENT_SOUND_IDS[i] == soundId)
                {
                    return i;
                }
            }
            return 0; // 默认返回第一个
        }
        
        /// <summary>
        /// 保存到Excel
        /// </summary>
        private void SaveToExcel()
        {
            try
            {
                string excelPath = GetDocsConfigFilePath(SOUND_EXCEL_NAME);
                
                // ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                
                using (var package = new ExcelPackage(new FileInfo(excelPath)))
                {
                    // 1. 保存Ambient Sheet
                    var ambientWorksheet = package.Workbook.Worksheets[AMBIENT_SHEET_NAME];
                    
                    if (ambientWorksheet != null)
                    {
                        // 先清除旧数据（从第3行开始）
                        int existingRowCount = ambientWorksheet.Dimension?.Rows ?? 2;
                        for (int row = 3; row <= existingRowCount; row++)
                        {
                            ambientWorksheet.DeleteRow(3);
                        }
                        
                        // 写入新数据
                        int currentRow = 3;
                        foreach (var data in ambientDataList)
                        {
                            ambientWorksheet.Cells[currentRow, COL_ID].Value = data.Id;
                            ambientWorksheet.Cells[currentRow, COL_AREA_ID].Value = data.AreaId;
                            ambientWorksheet.Cells[currentRow, COL_SOUND_ID].Value = data.SoundId;
                            
                            data.RowIndex = currentRow;
                            currentRow++;
                        }
                    }
                    
                    // 2. 保存Sound Sheet中的环境音数据
                    var soundWorksheet = package.Workbook.Worksheets[SOUND_SHEET_NAME];
                    
                    if (soundWorksheet != null)
                    {
                        foreach (var kvp in soundDataDict)
                        {
                            var data = kvp.Value;
                            int row = data.RowIndex;
                            
                            soundWorksheet.Cells[row, COL_SOUND_ID_IN_SOUND].Value = data.Id;
                            soundWorksheet.Cells[row, COL_COMMENT].Value = data.Comment;
                            soundWorksheet.Cells[row, COL_ASSET_NAME].Value = data.AssetName;
                            soundWorksheet.Cells[row, COL_PRIORITY].Value = data.Priority;
                            soundWorksheet.Cells[row, COL_LOOP].Value = data.Loop ? "TRUE" : "FALSE";
                            soundWorksheet.Cells[row, COL_VOLUME].Value = data.Volume;
                            soundWorksheet.Cells[row, COL_SPATIAL_BLEND].Value = data.SpatialBlend;
                            soundWorksheet.Cells[row, COL_MAX_DISTANCE].Value = data.MaxDistance;
                        }
                    }
                    
                    package.Save();
                }
                
                EditorUtility.DisplayDialog("成功", "环境音配置已保存到Excel！", "确定");
                Debug.Log("环境音配置已保存");
            }
            catch (Exception e)
            {
                EditorUtility.DisplayDialog("错误", $"保存失败: {e.Message}", "确定");
                Debug.LogError($"保存环境音配置失败: {e}");
            }
        }
        
        #endregion
        
        #region 辅助方法
        
        private int ParseInt(string text, int defaultValue)
        {
            if (int.TryParse(text, out int result))
            {
                return result;
            }
            return defaultValue;
        }
        
        private float ParseFloat(string text, float defaultValue)
        {
            if (float.TryParse(text, out float result))
            {
                return result;
            }
            return defaultValue;
        }
        
        private bool ParseBool(string text)
        {
            return text.Equals("TRUE", StringComparison.OrdinalIgnoreCase) ||
                   text.Equals("true", StringComparison.OrdinalIgnoreCase) ||
                   text == "1";
        }
        
        #endregion
    }
    
    /// <summary>
    /// 环境音数据类
    /// </summary>
    [Serializable]
    public class AmbientSoundData
    {
        public int Id;              // 自增ID
        public int AreaId;          // 场景ID
        public int SoundId;         // 环境音SoundId
        public int RowIndex;        // Excel中的行索引（用于保存时定位）
    }
}
