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

namespace DesignTools
{
    /// <summary>
    /// 音效配置Editor工具
    /// 读取Docs/config/Sound.xlsx的Sound Sheet，编辑音效配置
    /// </summary>
    public class SoundItemConfigEditor : BaseDesignToolEditor
    {
        private const string SOUND_EXCEL_NAME = "Sound.xlsx";
        private const string SOUND_SHEET_NAME = "Sound";
        
        // 表格列索引
        private const int COL_ID = 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;
        
        private List<SoundData> soundDataList = new List<SoundData>();
        private List<SoundData> filteredSoundDataList = new List<SoundData>();
        
        // 搜索和筛选
        private string searchText = "";
        private bool showOnlyLoopSounds = false;
        
        // 分页
        private int currentPage = 0;
        private int itemsPerPage = 20;
        private int totalPages = 0;
        
        // 编辑状态
        private Dictionary<int, bool> foldoutStates = new Dictionary<int, bool>();
        
        [MenuItem("策划工具/声音/音效配置")]
        public static void ShowWindow()
        {
            var window = GetWindow<SoundItemConfigEditor>("音效配置");
            window.minSize = window.GetMinWindowSize();
            window.Show();
        }
        
        #region 基类实现
        
        protected override string GetDocsPathPrefKey()
        {
            return "SoundItemConfigEditor_DocsPath";
        }
        
        protected override string GetWindowTitle()
        {
            return "音效配置工具";
        }
        
        protected override Vector2 GetMinWindowSize()
        {
            return new Vector2(1200, 700);
        }
        
        protected override void LoadConfigData()
        {
            // 加载Sound表
            LoadSoundExcel();
        }
        
        protected override void DrawDataEditor()
        {
            DrawFilterAndPagination();
            EditorGUILayout.Space(5);
            DrawSoundDataTable();
        }
        
        /// <summary>
        /// 不显示基类的底部按钮（已在顶部显示）
        /// </summary>
        protected override bool ShowBottomButtons()
        {
            return false;
        }
        
        /// <summary>
        /// 保存数据到Excel（覆盖基类方法）
        /// </summary>
        protected override void SaveDataToExcel()
        {
            SaveToExcel();
        }
        
        #endregion
        
        #region 数据加载
        
        /// <summary>
        /// 加载Sound.xlsx
        /// </summary>
        private void LoadSoundExcel()
        {
            soundDataList.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_ID].Text;
                    if (string.IsNullOrEmpty(idText))
                    {
                        continue;
                    }
                    
                    if (!int.TryParse(idText, out int id))
                    {
                        continue;
                    }
                    
                    var soundData = new SoundData
                    {
                        Id = id,
                        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
                    };
                    
                    soundDataList.Add(soundData);
                }
            }
            
            Debug.Log($"加载了 {soundDataList.Count} 条音效配置");
            
            // 初始化筛选列表
            ApplyFilter();
        }
        
        #endregion
        
        #region UI绘制
        
        /// <summary>
        /// 绘制筛选和分页
        /// </summary>
        private void DrawFilterAndPagination()
        {
            EditorGUILayout.BeginVertical("box");
            
            // 搜索和筛选
            EditorGUILayout.BeginHorizontal();
            
            EditorGUILayout.LabelField("搜索", GUILayout.Width(40));
            string newSearchText = EditorGUILayout.TextField(searchText);
            if (newSearchText != searchText)
            {
                searchText = newSearchText;
                ApplyFilter();
            }
            
            bool newShowOnlyLoop = EditorGUILayout.Toggle("仅显示循环音效", showOnlyLoopSounds, GUILayout.Width(150));
            if (newShowOnlyLoop != showOnlyLoopSounds)
            {
                showOnlyLoopSounds = newShowOnlyLoop;
                ApplyFilter();
            }
            
            if (GUILayout.Button("清除筛选", GUILayout.Width(80)))
            {
                searchText = "";
                showOnlyLoopSounds = false;
                ApplyFilter();
            }
            
            GUILayout.FlexibleSpace();
            
            // 保存按钮（放在筛选区域右侧，更显眼）
            GUI.backgroundColor = Color.green;
            if (GUILayout.Button("💾 保存到Excel", GUILayout.Height(25), GUILayout.Width(120)))
            {
                SaveToExcel();
            }
            GUI.backgroundColor = Color.white;
            
            EditorGUILayout.EndHorizontal();
            
            // 分页控制
            EditorGUILayout.BeginHorizontal();
            
            EditorGUILayout.LabelField($"共 {filteredSoundDataList.Count} 条音效", GUILayout.Width(120));
            
            GUILayout.FlexibleSpace();
            
            if (GUILayout.Button("<<", GUILayout.Width(40)))
            {
                currentPage = 0;
            }
            
            GUI.enabled = currentPage > 0;
            if (GUILayout.Button("<", GUILayout.Width(40)))
            {
                currentPage--;
            }
            GUI.enabled = true;
            
            EditorGUILayout.LabelField($"第 {currentPage + 1}/{totalPages} 页", GUILayout.Width(100));
            
            GUI.enabled = currentPage < totalPages - 1;
            if (GUILayout.Button(">", GUILayout.Width(40)))
            {
                currentPage++;
            }
            GUI.enabled = true;
            
            if (GUILayout.Button(">>", GUILayout.Width(40)))
            {
                currentPage = totalPages - 1;
            }
            
            EditorGUILayout.LabelField("每页", GUILayout.Width(30));
            int newItemsPerPage = EditorGUILayout.IntField(itemsPerPage, GUILayout.Width(50));
            if (newItemsPerPage != itemsPerPage && newItemsPerPage > 0)
            {
                itemsPerPage = newItemsPerPage;
                ApplyFilter();
            }
            
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.EndVertical();
        }
        
        /// <summary>
        /// 绘制音效数据表格
        /// </summary>
        private void DrawSoundDataTable()
        {
            EditorGUILayout.BeginVertical("box");
            
            // 表头
            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();
            
            // 数据行（使用 ExpandHeight 让 ScrollView 自适应剩余空间）
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, GUILayout.ExpandHeight(true));
            
            int startIndex = currentPage * itemsPerPage;
            int endIndex = Mathf.Min(startIndex + itemsPerPage, filteredSoundDataList.Count);
            
            for (int i = startIndex; i < endIndex; i++)
            {
                var soundData = filteredSoundDataList[i];
                DrawSoundDataRow(soundData);
            }
            
            EditorGUILayout.EndScrollView();
            
            EditorGUILayout.EndVertical();
        }
        
        /// <summary>
        /// 绘制单行音效数据
        /// </summary>
        private void DrawSoundDataRow(SoundData data)
        {
            bool isExpanded = foldoutStates.ContainsKey(data.Id) && foldoutStates[data.Id];
            
            EditorGUILayout.BeginVertical("box");
            
            // 基础信息行
            EditorGUILayout.BeginHorizontal();
            
            // ID（可编辑）
            int newId = EditorGUILayout.IntField(data.Id, GUILayout.Width(60));
            if (newId != data.Id && newId > 0)
            {
                data.Id = newId;
            }
            
            // 策划备注
            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();
            
            EditorGUILayout.EndVertical();
        }
        
        #endregion
        
        #region 数据筛选和保存
        
        /// <summary>
        /// 应用筛选
        /// </summary>
        private void ApplyFilter()
        {
            filteredSoundDataList.Clear();
            
            foreach (var data in soundDataList)
            {
                bool matchSearch = string.IsNullOrEmpty(searchText) ||
                                   data.Id.ToString().Contains(searchText) ||
                                   data.Comment.Contains(searchText) ||
                                   data.AssetName.Contains(searchText);
                
                bool matchLoop = !showOnlyLoopSounds || data.Loop;
                
                if (matchSearch && matchLoop)
                {
                    filteredSoundDataList.Add(data);
                }
            }
            
            // 更新分页
            totalPages = Mathf.Max(1, Mathf.CeilToInt((float)filteredSoundDataList.Count / itemsPerPage));
            currentPage = Mathf.Clamp(currentPage, 0, totalPages - 1);
        }
        
        /// <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)))
                {
                    var worksheet = package.Workbook.Worksheets[SOUND_SHEET_NAME];
                    
                    if (worksheet == null)
                    {
                        EditorUtility.DisplayDialog("错误", 
                            $"未找到Sheet: {SOUND_SHEET_NAME}", 
                            "确定");
                        return;
                    }
                    
                    // 更新每一行数据
                    foreach (var data in soundDataList)
                    {
                        int row = data.RowIndex;
                        
                        worksheet.Cells[row, COL_ID].Value = data.Id;
                        worksheet.Cells[row, COL_COMMENT].Value = data.Comment;
                        worksheet.Cells[row, COL_ASSET_NAME].Value = data.AssetName;
                        worksheet.Cells[row, COL_PRIORITY].Value = data.Priority;
                        worksheet.Cells[row, COL_LOOP].Value = data.Loop ? "TRUE" : "FALSE";
                        worksheet.Cells[row, COL_VOLUME].Value = data.Volume;
                        worksheet.Cells[row, COL_SPATIAL_BLEND].Value = data.SpatialBlend;
                        worksheet.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 SoundData
    {
        public int Id;                    // 声音编号
        public string Comment;            // 策划备注
        public string AssetName;          // 资源名称
        public int Priority;              // 优先级（0默认，128最高，-128最低）
        public bool Loop;                 // 是否循环
        public float Volume;              // 音量（0~1）
        public float SpatialBlend;        // 空间混合量（0为2D，1为3D）
        public float MaxDistance;         // 最大距离
        public int RowIndex;              // Excel中的行索引（用于保存时定位）
    }
}
