using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Newtonsoft.Json;

namespace DefaultNamespace.ProcessMode
{
    public class SceneStepEditorWindow : EditorWindow
    {
        private List<ProcessStep> steps = new List<ProcessStep>();
        private List<bool> stepFoldouts = new List<bool>();  // 用于控制步骤的折叠状态
        private List<List<bool>> actionFoldouts = new List<List<bool>>();  // 用于控制每个步骤内动作的折叠状态
        private Vector2 scrollPosition;  // 滚动条位置
        private string configFilePath;

        [MenuItem("工具/Scene Step 编辑器")]
        public static void ShowWindow()
        {
            SceneStepEditorWindow window = GetWindow<SceneStepEditorWindow>("Scene Step 编辑器");

            // 设置窗口的宽度和默认高度
            float windowWidth = 500;
            float windowHeight = 600;

            // 计算居中的位置
            Rect centeredPosition = new Rect(
                (Screen.currentResolution.width - windowWidth) / 2,
                (Screen.currentResolution.height - windowHeight) / 2,
                windowWidth,
                windowHeight
            );

            // 设置窗口位置并固定宽度，可调整高度
            window.position = centeredPosition;
            // window.minSize = new Vector2(windowWidth, windowHeight);
            // window.maxSize = new Vector2(windowWidth, Screen.currentResolution.height);
        }
        private void OnEnable()
        {
            // 设置配置文件路径
            string dataFolderPath = Path.Combine(Application.streamingAssetsPath, "DataConfig");
            configFilePath = Path.Combine(dataFolderPath, "SceneStepData.json");

            // 如果文件存在，则加载文件内容
            if (File.Exists(configFilePath))
            {
                string json = File.ReadAllText(configFilePath);
                if (!string.IsNullOrEmpty(json))
                {
                    steps = JsonConvert.DeserializeObject<List<ProcessStep>>(json) ?? new List<ProcessStep>();
                    
                    // 初始化折叠状态列表
                    stepFoldouts = new List<bool>(new bool[steps.Count]);
                    actionFoldouts = new List<List<bool>>();
                    foreach (var step in steps)
                    {
                        actionFoldouts.Add(new List<bool>(new bool[step.Actions.Count]));
                    }
                }
            }
        }
        private void OnGUI()
        {
            GUILayout.Label("步骤编辑器", EditorStyles.boldLabel);

            // 开始滚动视图
            scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, true);
            GUILayout.BeginVertical(GUILayout.ExpandWidth(true));

            // 如果没有步骤，显示“增加步骤”按钮
            if (steps.Count == 0)
            {
                if (GUILayout.Button("+", GUILayout.Width(30)))
                {
                    steps.Add(new ProcessStep("新步骤",  new List<ProcessStepDescription>()));
                    stepFoldouts.Add(true);
                    actionFoldouts.Add(new List<bool>());
                }
            }
            for (int i = 0; i < steps.Count; i++)
            {
                if (stepFoldouts.Count <= i) stepFoldouts.Add(true);
                if (actionFoldouts.Count <= i) actionFoldouts.Add(new List<bool>());
                
                Rect rect2 = GUILayoutUtility.GetRect(3, 5, GUILayout.MaxWidth(position.width));  // 固定宽度为3
                EditorGUI.DrawRect(rect2, new Color(0.2196079f,0.2196079f,0.2196079f));  // 亮蓝色
                
                
                Rect rect = GUILayoutUtility.GetRect(3, 5, GUILayout.MaxWidth(position.width));  // 固定宽度为3
                EditorGUI.DrawRect(rect, new Color(0.03604485f,0.509434f,0.4336843f));  // 亮蓝色

                Rect rect1 = GUILayoutUtility.GetRect(3, 5, GUILayout.MaxWidth(position.width));  // 固定宽度为3
                EditorGUI.DrawRect(rect1, new Color(0.2196079f,0.2196079f,0.2196079f));  // 亮蓝色
                
                GUILayout.BeginHorizontal();

                // 增加和删除步骤按钮 
                if (i == steps.Count - 1 && GUILayout.Button("+", GUILayout.Width(30)))
                {
                    steps.Add(new ProcessStep("新步骤",  new List<ProcessStepDescription>()));
                    stepFoldouts.Add(true);
                    actionFoldouts.Add(new List<bool>());
                }

                if (GUILayout.Button("-", GUILayout.Width(30)))
                {
                    steps.RemoveAt(i);
                    stepFoldouts.RemoveAt(i);
                    actionFoldouts.RemoveAt(i);
                    GUILayout.EndHorizontal();
                    continue;
                }

                // 绘制蓝色竖条
                GUILayout.Space(4);
                DrawBrightBlueLine();


              
                stepFoldouts[i] = EditorGUILayout.Foldout(stepFoldouts[i], $"步骤 {i + 1}: {steps[i].StepDescription}", true);

                GUILayout.EndHorizontal();

                if (stepFoldouts[i])
                {
                    EditorGUI.indentLevel++;

                    // 步骤描述和评分
                    steps[i].StepDescription = EditorGUILayout.TextField("描述", steps[i].StepDescription);

                    GUILayout.Space(5);

                    // 动作列表
                    GUIStyle whiteBoldLabelStyle = new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = Color.white } };
                    Rect labelRect = GUILayoutUtility.GetRect(new GUIContent("动作列表"), whiteBoldLabelStyle, GUILayout.ExpandWidth(true));
                    EditorGUI.DrawRect(labelRect, Color.gray);
                    EditorGUI.LabelField(labelRect, "动作列表", whiteBoldLabelStyle);

                    // 如果没有动作，显示“增加动作”按钮
                    if (steps[i].Actions.Count == 0)
                    {
                        if (GUILayout.Button("+", GUILayout.Width(30)))
                        {
                            steps[i].Actions.Add(new ProcessStepDescription(new List<string>(), null, "", false, "", false));
                            actionFoldouts[i].Add(true);
                        }
                    }

                    for (int j = 0; j < steps[i].Actions.Count; j++)
                    {
                        if (actionFoldouts[i].Count <= j) actionFoldouts[i].Add(true);

                        GUILayout.BeginHorizontal();

                        // 增加和删除动作按钮
                        if (j == steps[i].Actions.Count - 1 && GUILayout.Button("+", GUILayout.Width(30)))
                        {
                            steps[i].Actions.Add(new ProcessStepDescription(new List<string>(), null, "", false, "", false));
                            actionFoldouts[i].Add(true);
                        }

                        if (GUILayout.Button("-", GUILayout.Width(30)))
                        {
                            steps[i].Actions.RemoveAt(j);
                            actionFoldouts[i].RemoveAt(j);
                            GUILayout.EndHorizontal();
                            continue;
                        }

                        // 绘制蓝色竖条
                        DrawBrightBlueLine();
                        GUILayout.Space(5);

                        // 动作折叠控制
                        actionFoldouts[i][j] = EditorGUILayout.Foldout(actionFoldouts[i][j], $"动作 {j + 1}: {steps[i].Actions[j].Description}", true);

                        GUILayout.EndHorizontal();

                        if (actionFoldouts[i][j])
                        {
                            EditorGUI.indentLevel++;

                            steps[i].Actions[j].Description = EditorGUILayout.TextField("描述", steps[i].Actions[j].Description);
                            steps[i].Actions[j].IsSequential = EditorGUILayout.Toggle("按顺序点击", steps[i].Actions[j].IsSequential);
                            steps[i].Actions[j].IsUI = EditorGUILayout.Toggle("是否UI", steps[i].Actions[j].IsUI);
                            steps[i].Actions[j].Score = EditorGUILayout.FloatField("分数", steps[i].Actions[j].Score);  // 动作评分输入框

                            // 目标对象列表
                            GUIStyle whiteBoldLabelStyle1 = new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = Color.white } };
                            Rect labelRect1 = GUILayoutUtility.GetRect(new GUIContent("目标对象列表"), whiteBoldLabelStyle1, GUILayout.ExpandWidth(true));
                            EditorGUI.DrawRect(labelRect1, Color.gray);
                            EditorGUI.LabelField(labelRect1, "目标对象列表", whiteBoldLabelStyle1);

                            // 目标对象列表内容
                            for (int k = 0; k < steps[i].Actions[j].TargetObjects.Count; k++)
                            {
                                GUILayout.BeginHorizontal();

                                // 删除目标对象按钮
                                if (GUILayout.Button("-", GUILayout.Width(30)))
                                {
                                    steps[i].Actions[j].TargetObjects.RemoveAt(k);
                                    GUILayout.EndHorizontal();
                                    continue;
                                }

                                // 绘制蓝色竖条
                                DrawBrightBlueLine();
                                GUILayout.Space(5);

                                steps[i].Actions[j].TargetObjects[k] = EditorGUILayout.TextField($"目标对象 {k + 1}", steps[i].Actions[j].TargetObjects[k]);

                                GUILayout.EndHorizontal();
                            }

                            // 在最后一个目标对象下方居中显示“增加目标对象”按钮
                            GUILayout.BeginHorizontal();
                            GUILayout.FlexibleSpace();
                            if (GUILayout.Button("+", GUILayout.Width(300)))
                            {
                                steps[i].Actions[j].TargetObjects.Add("");
                            }
                            GUILayout.FlexibleSpace();
                            GUILayout.EndHorizontal();

                            EditorGUI.indentLevel--;
                        }
                    }

                    EditorGUI.indentLevel--;
                    GUILayout.Space(10);
                }
            }

            GUILayout.Space(20);
            GUILayout.EndVertical();

            // 结束滚动视图
            GUILayout.EndScrollView();

            // 更新按钮
            GUI.backgroundColor = Color.green;
            if (GUILayout.Button("更新到 StreamingAssets/DataConfig/SceneStepData.json", GUILayout.Height(40)))
            {
                UpdateConfiguration();
            }
            GUI.backgroundColor = Color.white;
        }

        private void UpdateConfiguration()
        {
            string dataFolderPath = Path.Combine(Application.streamingAssetsPath, "DataConfig");
            string configFilePath = Path.Combine(dataFolderPath, "SceneStepData.json");

            if (!Directory.Exists(dataFolderPath))
            {
                Directory.CreateDirectory(dataFolderPath);
            }

            string json = JsonConvert.SerializeObject(steps, Formatting.Indented);
            File.WriteAllText(configFilePath, json);

            EditorUtility.DisplayDialog("Scene Step 编辑器", "配置已更新到 StreamingAssets/DataConfig/SceneStepData.json", "确定");
        }

        private void DrawBrightBlueLine()
        {
            Rect rect = GUILayoutUtility.GetRect(3, EditorGUIUtility.singleLineHeight + 2, GUILayout.Width(3));  // 固定宽度为3
            EditorGUI.DrawRect(rect, new Color(0.3f, 0.5f, 1f, 1f));  // 亮蓝色
            
        }
        
        
        
    }
} 