<template>
  <el-dialog
    class="api-edit"
    v-model="showDialog"
    :title="`${formData.id ? '编辑API' : '新增API'}`"
    :width="isFullscreen ? '100%' : '1000px'"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :fullscreen="isFullscreen"
    :before-close="cancel"
  >
    <template #header>
      <div class="dialog-header">
        <span class="dialog-title">{{ formData.id ? '编辑API' : '新增API' }}</span>
        <div class="dialog-tools">
          <el-button
            type="text"
            @click="toggleFullscreen"
          >
            <el-icon :size="20">
              <ele-FullScreen v-if="!isFullscreen" />
              <ele-ScaleToOriginal v-else />
            </el-icon>
          </el-button>
        </div>
      </div>
    </template>
    <div class="dialog-body-with-tabs">
      <div class="tab-navigation">
        <ul>
          <li @click="activeTab = 'basic'" :class="{ active: activeTab === 'basic' }">基本信息</li>
          <li @click="activeTab = 'executor'" :class="{ active: activeTab === 'executor' }">执行器</li>
          <li @click="activeTab = 'plugins'" :class="{ active: activeTab === 'plugins' }">全局插件</li>
        </ul>
      </div>
      <div class="tab-content">
        <el-form ref="formRef" :model="formData" :rules="ruleForm" label-width="100px">
          <!-- 基本信息 Tab -->
          <div v-show="activeTab === 'basic'" class="basic-info-tab">
            <div class="form-section-title">基础配置</div>
            <el-form-item label="API信息" required>
              <div class="method-name-container">
                <div class="method-select">
                  <el-select v-model="formData.method" placeholder="请求方法">
                    <el-option label="GET" value="GET"></el-option>
                    <el-option label="POST" value="POST"></el-option>
                    <el-option label="PUT" value="PUT"></el-option>
                    <el-option label="DELETE" value="DELETE"></el-option>
                  </el-select>
                </div>
                <div class="name-input">
                  <el-input v-model="formData.name" placeholder="请输入API名称" />
                </div>
              </div>
            </el-form-item>
            <el-form-item label="API路径" prop="path">
              <div class="path-input-container">
                <div class="path-prefix2">
                  {{ originUrl }}/apihub/
                </div>
                <el-input v-model="formData.path" placeholder="请输入API路径" class="path-input" />
              </div>
            </el-form-item>
            <el-form-item label="所属分组" prop="groupKey">
              <el-cascader v-model="formData.groupKey" :options="groupOptions" :props="{ checkStrictly: true, emitPath: false, value: 'GroupKey', label: 'Name', children: 'Children' }" placeholder="请选择所属分组" clearable style="width: 100%" />
            </el-form-item>
            <!-- <el-form-item label="版本" prop="version">
              <el-input v-model="formData.version" placeholder="请输入版本号，如1.0" />
            </el-form-item> -->
            <!-- <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态">
                <el-option label="草稿" value="Draft"></el-option>
                <el-option label="已发布" value="Published"></el-option>
                <el-option label="已废弃" value="Deprecated"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="描述" prop="description">
              <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入API描述" />
            </el-form-item>

            <el-form-item label="ContentType" prop="contentType">
              <el-select v-model="formData.contentType" placeholder="请选择ContentType" style="width: 100%;">
                <el-option label="application/x-www-form-urlencoded" value="application/x-www-form-urlencoded"></el-option>
                <el-option label="application/json" value="application/json"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="请求示例" prop="example" v-if="formData.contentType === 'application/json'">
              <el-input v-model="formData.example" type="textarea" :rows="4" placeholder="请输入请求示例" />
            </el-form-item>

            <el-form-item label="访问权限" prop="private">
              <el-radio-group v-model="formData.private">
                <el-radio :label="0">开放API</el-radio>
                <el-radio :label="1">私有API</el-radio>
              </el-radio-group>
            </el-form-item>

            <div class="form-section-title" v-if="formData.contentType === 'application/x-www-form-urlencoded'">参数定义
              <el-button type="primary" link @click="addParameter" style="margin-left: 10px;">
                <el-icon><ele-Plus /></el-icon>添加参数
              </el-button>
            </div>
            <el-form-item label-width="0" v-if="formData.contentType === 'application/x-www-form-urlencoded'">
              <el-table :data="formData.parameters" style="width: 100%" border>
                <el-table-column label="参数名" width="150">
                  <template #default="scope">
                    <el-input v-model="scope.row.name" placeholder="参数名"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="类型" width="120">
                  <template #default="scope">
                    <el-select v-model="scope.row.type" placeholder="类型">
                      <el-option label="string" value="string"></el-option>
                      <el-option label="int" value="int"></el-option>
                      <el-option label="float" value="float"></el-option>
                      <el-option label="bool" value="bool"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="必填" width="80">
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.required"></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="默认值" width="120">
                  <template #default="scope">
                    <el-input v-model="scope.row.defaultValue" placeholder="默认值"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="描述">
                  <template #default="scope">
                    <el-input v-model="scope.row.description" placeholder="参数描述"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="scope">
                    <el-button type="danger" link @click="removeParameter(scope.$index)">
                      <el-icon><ele-Delete /></el-icon>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>

          <!-- 执行器 Tab -->
          <div v-show="activeTab === 'executor'" class="executor-tab">
            <div class="form-section-title">SQL配置</div>
            <el-form-item label="数据源" prop="dataSourceKey">
              <el-select v-model="formData.dataSourceKey" placeholder="请选择数据源" filterable>
                <el-option v-for="item in dataSources" :key="item.id" :label="item.name" :value="item.dsKey"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="SQL类型" prop="sqlType">
              <el-radio-group v-model="formData.sqlType">
                <el-radio label="query">查询</el-radio>
                <el-radio label="procedure">存储过程</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="SQL内容" prop="sqlContent" class="sql-content-item">
              <SqlEditor
                v-model="formData.sqlContent"
                :height="300"
                @update:modelValue="onSqlContentChange"
              />
            </el-form-item>
            <el-form-item label="返回格式" prop="returnFormat">
              <el-select v-model="formData.returnFormat" placeholder="请选择返回格式">
                <el-option label="JSON" value="JSON"></el-option>
                <el-option label="XML" value="XML"></el-option>
              </el-select>
            </el-form-item>
          </div>

          <!-- 全局插件 Tab -->
          <div v-show="activeTab === 'plugins'" class="plugins-tab">
            <div class="form-section-title">全局插件配置
              <el-button type="primary" @click="showAddPluginDialog" style="margin-left: 10px;" size="small">
                <el-icon><ele-Plus /></el-icon>添加插件
              </el-button>
            </div>

            <!-- 插件列表 -->
            <div v-if="!formData.plugins || formData.plugins.length === 0" class="empty-plugins">
              <el-empty description="暂无插件配置" :image-size="80">
                <el-button type="primary" @click="showAddPluginDialog" size="small">添加插件</el-button>
              </el-empty>
            </div>
            <div v-else class="plugins-list">
              <el-card v-for="(plugin, index) in formData.plugins" :key="index" class="plugin-card" shadow="hover">
                <template #header>
                  <div class="plugin-card-header">
                    <div class="plugin-title">
                      <el-tag :type="plugin.category === 'Before' ? 'success' : 'warning'" size="small" effect="dark" style="margin-right: 10px;">
                        {{ plugin.category === 'Before' ? '前置插件' : '后置插件' }}
                      </el-tag>
                      <span class="plugin-name">{{ plugin.name }}</span>
                    </div>
                    <div class="plugin-actions">
                      <el-button type="primary" link @click="editPlugin(index)" size="small">
                        <el-icon><ele-Edit /></el-icon>
                      </el-button>
                      <el-button type="danger" link @click="confirmRemovePlugin(index)" size="small">
                        <el-icon><ele-Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </template>

                <div class="plugin-info">
                  <div class="plugin-type">
                    <span class="label">插件类型：</span>
                    <el-tag size="small" type="info">{{ plugin.type || 'JavaScript' }}</el-tag>
                  </div>
                  <div class="plugin-description" v-if="plugin.description">
                    <span class="label">插件描述：</span>
                    <span>{{ plugin.description }}</span>
                  </div>
                  <div class="plugin-config" v-if="plugin.config">
                    <span class="label">配置参数：</span>
                    <pre class="config-code">{{ formatPluginConfig(plugin.config) }}</pre>
                  </div>
                </div>
              </el-card>
            </div>
          </div>

          <!-- 添加插件对话框 -->
          <el-dialog
            v-model="addPluginDialogVisible"
            title="添加全局插件"
            width="650px"
            append-to-body
            destroy-on-close
          >
            <el-form ref="pluginFormRef" :model="currentPlugin" label-width="100px" :rules="pluginRules">
              <el-form-item label="插件类型" required>
                <el-radio-group v-model="filterPluginType" @change="filterPlugins" style="margin-bottom: 10px;">
                  <el-radio-button label="">全部</el-radio-button>
                  <el-radio-button label="JavaScript">JavaScript</el-radio-button>
<!--                  <el-radio-button label="Go">Go</el-radio-button>-->
                  <el-radio-button label="LUA">LUA</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="插件分类">
                <el-radio-group v-model="filterPluginCategory" @change="filterPlugins" style="margin-bottom: 10px;">
                  <el-radio-button label="">全部</el-radio-button>
                  <el-radio-button label="Before">前置插件</el-radio-button>
                  <el-radio-button label="After">后置插件</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="选择插件" required>
                <div style="display: flex; gap: 10px; align-items: center;">
                  <el-select
                    v-model="selectedPluginId"
                    placeholder="选择现有插件"
                    style="width: 350px"
                    filterable
                    clearable
                    @change="handlePluginSelected"
                  >
                    <el-option
                      v-for="item in filteredPlugins"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                      <div style="display: flex; align-items: center; justify-content: space-between;">
                        <span>{{ item.name }}</span>
                        <div>
                          <el-tag size="small" type="info" style="margin-left: 5px;">{{ item.type }}</el-tag>
                          <el-tag
                            size="small"
                            :type="item.category === 'Before' ? 'success' : 'warning'"
                            style="margin-left: 5px;"
                          >
                            {{ item.category === 'Before' ? '前置' : '后置' }}
                          </el-tag>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                  <el-button type="success" @click="createNewPlugin" size="default">新建插件</el-button>
                </div>
              </el-form-item>

              <template v-if="selectedPluginId || isCreatingNewPlugin">
                <el-form-item label="插件名称" prop="name" required>
                  <el-input v-model="currentPlugin.name" placeholder="请输入插件名称" />
                </el-form-item>

                <el-form-item label="插件类型" prop="type" required>
                  <el-select v-model="currentPlugin.type" placeholder="请选择插件类型" style="width: 100%;">
                    <el-option label="JavaScript" value="JavaScript" />
                    <el-option label="Go" value="Go" />
                    <el-option label="LUA" value="LUA" />
                  </el-select>
                </el-form-item>

                <el-form-item label="插件分类" prop="category" required>
                  <el-select v-model="currentPlugin.category" placeholder="请选择插件分类" style="width: 100%;">
                    <el-option label="前置插件" value="Before" />
                    <el-option label="后置插件" value="After" />
                  </el-select>
                </el-form-item>

                <el-form-item label="配置参数" prop="config">
                  <el-input
                    v-model="currentPlugin.config"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入JSON格式的配置参数，例如：{ &quot;key&quot;: &quot;value&quot; }"
                  />
                  <div class="tip-text">配置参数应为JSON格式，会在运行时传递给插件</div>
                </el-form-item>

                <el-form-item label="描述" prop="description">
                  <el-input
                    v-model="currentPlugin.description"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入插件描述"
                  />
                </el-form-item>
              </template>
            </el-form>

            <template #footer>
              <div class="dialog-footer">
                <el-button @click="addPluginDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAddPlugin" :loading="savePluginLoading">确定</el-button>
              </div>
            </template>
          </el-dialog>
        </el-form>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import SqlEditor from "./SqlEditor.vue";
import api from "/@/api/modules/apiHub";
import { ruleRequired } from "/@/utils/validator";
import getOrigin from '/@/utils/origin';
import {
  Plus as ElePlus,
  Delete as EleDelete,
  FullScreen as EleFullScreen,
  ScaleToOriginal as EleScaleToOriginal
} from '@element-plus/icons-vue';
// 使用自定义的 SqlEditor 组件替代 MonacoEditor

const emit = defineEmits(["getList"]);

const showDialog = ref(false);
const formRef = ref();
const dataSources = ref<any[]>([]);
const activeTab = ref('basic'); // 当前激活的Tab
const availablePlugins = ref<any[]>([]);
const addPluginDialogVisible = ref(false);
const selectedPluginId = ref<number | null>(null);
const isCreatingNewPlugin = ref(false);
const savePluginLoading = ref(false);
const pluginFormRef = ref();

// 插件过滤相关
const filterPluginType = ref(''); // 过滤的插件类型
const filterPluginCategory = ref(''); // 过滤的插件分类
const filteredPlugins = ref<any[]>([]); // 过滤后的插件列表

const currentPlugin = reactive({
  id: null as number | null,
  name: '',
  type: 'JavaScript',
  category: 'Before',
  content: '',
  config: '',
  description: ''
});

const pluginRules = {
  name: [{ required: true, message: '请输入插件名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择插件类型', trigger: 'change' }],
  category: [{ required: true, message: '请选择插件分类', trigger: 'change' }]
};

const originUrl: string = getOrigin("");

// SQL编辑器已经在组件内部处理了关键字和自动完成功能

// SQL内容变化回调
const onSqlContentChange = (value: string) => {
  // 这里可以添加其他需要的处理逻辑
  formData.sqlContent = value;
};

// 全屏显示控制
const isFullscreen = ref(false);

// 检查哪个标签页有验证错误并切换到该标签页
const checkTabWithErrors = () => {
  // 获取所有验证失败的字段
  const fields = formRef.value.fields;
  const errorFields = [];

  // 收集所有错误字段
  for (const field in fields) {
    if (fields[field].validateState === 'error') {
      errorFields.push(field);
    }
  }

  if (errorFields.length === 0) return;

  // 基本信息标签页的字段
  const basicTabFields = ['name', 'path', 'version', 'description', 'groupKey'];
  // 执行器标签页的字段
  const executorTabFields = ['dataSourceKey', 'sqlType', 'sqlContent', 'returnFormat', 'status'];
  // 全局插件标签页的字段
  const pluginsTabFields = [];
  // 检查插件相关字段
  errorFields.forEach(field => {
    if (field.startsWith('plugins[')) {
      pluginsTabFields.push(field);
    }
  });

  // 检查每个标签页并切换到有错误的标签页
  const errorTabs = [];

  if (errorFields.some(field => basicTabFields.includes(field))) {
    errorTabs.push({ tab: 'basic', name: '基本信息' });
  }
  if (errorFields.some(field => executorTabFields.includes(field))) {
    errorTabs.push({ tab: 'executor', name: '执行器' });
  }
  if (pluginsTabFields.length > 0) {
    errorTabs.push({ tab: 'plugins', name: '全局插件' });
  }

  if (errorTabs.length > 0) {
    // 如果当前标签页不在错误标签页列表中，切换到第一个错误标签页
    const currentTabHasError = errorTabs.some(tab => tab.tab === activeTab.value);
    if (!currentTabHasError) {
      activeTab.value = errorTabs[0].tab;
    }

    // 显示错误提示
    showErrorTooltip(errorTabs);

    // 等待DOM更新后滚动到错误字段
    nextTick(() => {
      const errorElement = document.querySelector('.is-error');
      if (errorElement) {
        errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    });
  }
};

// 显示错误提示
const showErrorTooltip = (errorTabs) => {
  // 创建错误标签页列表的HTML
  let errorMessage = '<div class="error-tabs-list">';
  errorMessage += '<div class="error-title">以下标签页有必填项未填写：</div>';
  errorMessage += '<ul>';
  errorTabs.forEach(tab => {
    errorMessage += `<li class="error-tab-item" data-tab="${tab.tab}">${tab.name}</li>`;
  });
  errorMessage += '</ul>';
  errorMessage += '</div>';

  // 显示消息提示
  ElMessage({
    dangerouslyUseHTMLString: true,
    message: errorMessage,
    type: 'error',
    duration: 5000,
    showClose: true,
    onClose: () => {
      // 消息关闭后移除事件监听
      removeErrorTabClickListeners();
    }
  });

  // 等待DOM更新后添加点击事件
  nextTick(() => {
    addErrorTabClickListeners();
  });
};

// 添加错误标签页点击事件
const addErrorTabClickListeners = () => {
  const tabItems = document.querySelectorAll('.error-tab-item');
  tabItems.forEach(item => {
    item.addEventListener('click', handleErrorTabClick);
    // 添加手型光标和下划线样式
    item.style.cursor = 'pointer';
    item.style.textDecoration = 'underline';
    item.style.color = '#409EFF';
  });
};

// 移除错误标签页点击事件
const removeErrorTabClickListeners = () => {
  const tabItems = document.querySelectorAll('.error-tab-item');
  tabItems.forEach(item => {
    item.removeEventListener('click', handleErrorTabClick);
  });
};

// 错误标签页点击处理函数
const handleErrorTabClick = (event) => {
  const tabName = event.target.getAttribute('data-tab');
  if (tabName) {
    activeTab.value = tabName;
    // 等待DOM更新后滚动到错误字段
    nextTick(() => {
      const errorElement = document.querySelector('.is-error');
      if (errorElement) {
        errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    });
  }
};

api.dataSource.list().then((res: any) => {
  dataSources.value = res.list;
});

// 分组选项
const groupOptions = ref([]);

// 定义基础表单数据
const baseForm = {
  id: null,
  name: "",
  path: "",
  method: "GET",
  dataSourceKey: null,
  sqlType: "query",
  sqlContent: "",
  parameters: [],
  returnFormat: "JSON",
  version: "1.0",
  status: "Draft",
  plugins: [],
  groupKey: "",
  description: "",
  contentType: "application/x-www-form-urlencoded", // 默认为 application/x-www-form-urlencoded
  example: "", // 请求参数示例
  private: 0, // 访问权限类型：0为公开，1为私有
};

const formData = reactive(JSON.parse(JSON.stringify(baseForm)));

// 表单验证规则
const ruleForm = {
  name: [ruleRequired("API名称不能为空", "change")],
  path: [ruleRequired("API路径不能为空", "change")],
  method: [ruleRequired("请求方法不能为空", "change")],
  dataSourceKey: [ruleRequired("数据源不能为空", "change")],
  sqlType: [ruleRequired("SQL类型不能为空", "change")],
  sqlContent: [ruleRequired("SQL内容不能为空", "change")],
  returnFormat: [ruleRequired("返回格式不能为空", "change")],
  version: [ruleRequired("版本不能为空", "change")],
  status: [ruleRequired("状态不能为空", "change")],
};

// 添加参数
const addParameter = () => {
  if (!formData.parameters) {
    formData.parameters = [];
  }
  formData.parameters.push({
    name: "",
    type: "string",
    required: false,
    defaultValue: "",
    description: "",
  });
};

// 移除参数
const removeParameter = (index: number) => {
  formData.parameters.splice(index, 1);
};

// 显示添加插件对话框
const showAddPluginDialog = () => {
  // 重置对话框状态
  selectedPluginId.value = null;
  isCreatingNewPlugin.value = false;
  filterPluginType.value = '';
  filterPluginCategory.value = '';
  Object.assign(currentPlugin, {
    id: null,
    name: '',
    type: 'JavaScript',
    category: 'Before',
    content: '',
    config: '',
    description: ''
  });

  // 加载可用插件列表
  loadAvailablePlugins();

  // 显示对话框
  addPluginDialogVisible.value = true;
};

// 过滤插件列表
const filterPlugins = () => {
  if (!availablePlugins.value || availablePlugins.value.length === 0) {
    filteredPlugins.value = [];
    return;
  }

  // 同时根据类型和分类过滤
  filteredPlugins.value = availablePlugins.value.filter(plugin => {
    // 如果没有设置过滤条件，则返回所有插件
    const typeMatch = !filterPluginType.value || plugin.type === filterPluginType.value;
    const categoryMatch = !filterPluginCategory.value || plugin.category === filterPluginCategory.value;
    return typeMatch && categoryMatch;
  });
};

// 加载可用插件列表
const loadAvailablePlugins = async () => {
  try {
    const res = await api.plugin.list({});
    // 处理可能的不同数据结构
    if (res.data) {
      if (Array.isArray(res.data)) {
        availablePlugins.value = res.data;
      } else if (res.data.data && Array.isArray(res.data.data)) {
        availablePlugins.value = res.data.data;
      } else if (res.data.Data && Array.isArray(res.data.Data)) {
        availablePlugins.value = res.data.Data;
      }
    } else if (res.Data && Array.isArray(res.Data)) {
      availablePlugins.value = res.Data;
    }

    // 处理首字母大写的属性名
    if (availablePlugins.value.length > 0) {
      availablePlugins.value = availablePlugins.value.map(plugin => {
        const newPlugin = {...plugin};
        if (newPlugin.Id !== undefined) newPlugin.id = newPlugin.Id;
        if (newPlugin.Name !== undefined) newPlugin.name = newPlugin.Name;
        if (newPlugin.Type !== undefined) newPlugin.type = newPlugin.Type;
        if (newPlugin.Category !== undefined) newPlugin.category = newPlugin.Category;
        if (newPlugin.Content !== undefined) newPlugin.content = newPlugin.Content;
        if (newPlugin.Description !== undefined) newPlugin.description = newPlugin.Description;
        return newPlugin;
      });
    }

    // 应用过滤器
    filterPlugins();
  } catch (error) {
    // 加载插件列表失败
    ElMessage.error('加载可用插件列表失败');
  }
};

// 选择现有插件
const handlePluginSelected = (pluginId: number) => {
  if (!pluginId) {
    // 清除选择
    Object.assign(currentPlugin, {
      id: null,
      name: '',
      type: 'JavaScript',
      category: 'Before',
      content: '',
      config: '',
      description: ''
    });
    isCreatingNewPlugin.value = false;
    return;
  }

  // 查找选中的插件
  const selectedPlugin = availablePlugins.value.find(p => p.id === pluginId);
  if (selectedPlugin) {
    Object.assign(currentPlugin, {
      id: selectedPlugin.id,
      name: selectedPlugin.name,
      type: selectedPlugin.type || 'JavaScript',
      category: selectedPlugin.category || 'Before',
      content: selectedPlugin.content || '',
      config: '',  // 默认为空，让用户自己配置
      description: selectedPlugin.description || ''
    });
    isCreatingNewPlugin.value = false;
  }
};

// 创建新插件
const createNewPlugin = () => {
  selectedPluginId.value = null;
  Object.assign(currentPlugin, {
    id: null,
    name: '',
    type: 'JavaScript',
    category: 'Before',
    content: '',
    config: '',
    description: ''
  });
  isCreatingNewPlugin.value = true;
};

// 编辑插件
const editPlugin = (index: number) => {
  if (!formData.plugins || !formData.plugins[index]) return;

  const plugin = formData.plugins[index];
  selectedPluginId.value = plugin.id || null;
  Object.assign(currentPlugin, {
    id: plugin.id || null,
    name: plugin.name || '',
    type: plugin.type || 'JavaScript',
    category: plugin.category || 'Before',
    content: plugin.content || '',
    config: plugin.config || '',
    description: plugin.description || ''
  });

  // 编辑现有插件
  isCreatingNewPlugin.value = false;
  addPluginDialogVisible.value = true;
};

// 确认添加/编辑插件
const confirmAddPlugin = async () => {
  if (!pluginFormRef.value) return;

  await pluginFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    try {
      // 检查配置参数是否是有效的JSON
      if (currentPlugin.config) {
        try {
          JSON.parse(currentPlugin.config);
        } catch (e) {
          ElMessage.error('配置参数不是有效的JSON格式');
          return;
        }
      }

      // 如果是创建新插件
      if (isCreatingNewPlugin.value && !selectedPluginId.value) {
        savePluginLoading.value = true;

        try {
          // 创建新插件
          const newPluginData = {
            name: currentPlugin.name,
            type: currentPlugin.type,
            category: currentPlugin.category,
            content: currentPlugin.content,
            description: currentPlugin.description
          };

          const res = await api.plugin.add(newPluginData);
          const newPluginId = res.data?.id || res.data?.Id;

          if (newPluginId) {
            ElMessage.success('创建新插件成功');
            selectedPluginId.value = newPluginId;
            currentPlugin.id = newPluginId;

            // 重新加载插件列表
            await loadAvailablePlugins();
          } else {
            throw new Error('创建插件失败，无法获取插件ID');
          }
        } catch (error) {
          // 创建插件失败
          ElMessage.error('创建新插件失败，请重试');
          return;
        } finally {
          savePluginLoading.value = false;
        }
      }

      // 无论是否是新建的插件，都添加到API的插件列表中
      if (!formData.plugins) {
        formData.plugins = [];
      }

      // 检查是否已存在相同的插件
      const existingIndex = formData.plugins.findIndex(p => p.name === currentPlugin.name);

      // 创建插件对象
      const pluginToAdd = {
        id: currentPlugin.id,
        name: currentPlugin.name,
        type: currentPlugin.type,
        category: currentPlugin.category,
        config: currentPlugin.config,
        description: currentPlugin.description
      };

      if (existingIndex >= 0) {
        // 更新现有插件
        formData.plugins[existingIndex] = pluginToAdd;
        ElMessage.success('插件配置已更新');
      } else {
        // 添加新插件
        formData.plugins.push(pluginToAdd);
        ElMessage.success('插件已添加到API配置');
      }

      // 关闭对话框
      addPluginDialogVisible.value = false;
    } catch (error) {
      // 保存失败
      ElMessage.error('保存插件失败，请重试');
    }
  });
};

// 格式化插件配置显示
const formatPluginConfig = (config: string) => {
  if (!config) return '';

  try {
    const configObj = JSON.parse(config);
    return JSON.stringify(configObj, null, 2);
  } catch (e) {
    return config; // 如果不是有效的JSON，则原样返回
  }
};

// 确认删除插件
const confirmRemovePlugin = (index: number) => {
  ElMessageBox.confirm(`确定要移除插件 "${formData.plugins[index]?.name || '未命名插件'}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    removePlugin(index);
    ElMessage.success('插件已移除');
  }).catch(() => {});
};

// 此函数保留为兼容性考虑，实际调用showAddPluginDialog
/* eslint-disable-next-line no-unused-vars */
const addPlugin = () => {
  if (!formData.plugins) {
    formData.plugins = [];
  }
  // 显示添加插件对话框
  showAddPluginDialog();
};

// 移除插件
const removePlugin = (index: number) => {
  formData.plugins.splice(index, 1);
};

// 切换全屏显示
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;

  // 全屏模式下调整内容容器高度
  if (isFullscreen.value) {
    nextTick(() => {
      const dialogBodyWithTabs = document.querySelector('.dialog-body-with-tabs');
      if (dialogBodyWithTabs) {
        (dialogBodyWithTabs as HTMLElement).style.height = 'calc(100vh - 120px)';
      }
    });
  } else {
    nextTick(() => {
      const dialogBodyWithTabs = document.querySelector('.dialog-body-with-tabs');
      if (dialogBodyWithTabs) {
        (dialogBodyWithTabs as HTMLElement).style.height = '600px';
      }
    });
  }
};

// 提交表单
const onSubmit = () => {
  // 使用回调形式的验证，而不是异步验证
  formRef.value.validate((valid, fields) => {
    if (valid) {
      // 验证通过
      // 准备提交数据
      const submitData = JSON.parse(JSON.stringify(formData));

      // 调用API
      if (submitData.id) {
        // 编辑模式
        api.edit(submitData).then(() => {
          ElMessage.success("操作成功");
          resetForm();
          showDialog.value = false;
          emit("getList");
        });
      } else {
        // 新增模式
        delete submitData.id;
        api.add(submitData).then(() => {
          ElMessage.success("操作成功");
          resetForm();
          showDialog.value = false;
          emit("getList");
        });
      }
    } else {
      // 验证失败
      // 直接显示错误提示
      showValidationErrorMessage(fields);

      // 验证失败时检查是哪个标签页的必填项出错
      checkTabWithErrors();

      return false;
    }
  });
};

// 显示验证错误消息
const showValidationErrorMessage = (fields) => {
  // 获取所有错误字段
  const errorFields = Object.keys(fields);
  if (errorFields.length === 0) return;

  // 基本信息标签页的字段
  const basicTabFields = ['name', 'path', 'version', 'description', 'groupKey'];
  // 执行器标签页的字段
  const executorTabFields = ['dataSourceKey', 'sqlType', 'sqlContent', 'returnFormat', 'status'];

  // 检查每个标签页的错误
  const errorTabs = [];

  if (errorFields.some(field => basicTabFields.includes(field))) {
    errorTabs.push('基本信息');
  }
  if (errorFields.some(field => executorTabFields.includes(field))) {
    errorTabs.push('执行器');
  }
  if (errorFields.some(field => field.startsWith('plugins['))) {
    errorTabs.push('全局插件');
  }

  if (errorTabs.length > 0) {
    // 显示错误消息
    ElMessage({
      message: `请检查以下标签页的必填项：${errorTabs.join('、')}`,
      type: 'error',
      duration: 5000,
      showClose: true
    });
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, JSON.parse(JSON.stringify(baseForm)));
  activeTab.value = 'basic'; // 重置 Tab
  formRef.value && formRef.value.resetFields();
};



// 取消操作
const cancel = () => {
  ElMessageBox.confirm(
    '确定要关闭吗？未保存的内容将会丢失',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      showDialog.value = false;
      resetForm();
    })
    .catch(() => {
      // 用户取消关闭，不做任何操作
    });
};

// 加载分组选项
const loadGroupOptions = async () => {
  api.group.tree().then((res: any) => {
    groupOptions.value = res.list || [];
  });
};

// 打开对话框
const open = async (row?: any, defaultGroupKey?: string) => {
  resetForm();
  showDialog.value = true;

  // 加载分组选项
  await loadGroupOptions();

  if (row) {
    // 编辑模式，填充表单数据
    nextTick(() => {
      // 如果是编辑模式，需要先获取详情
      // 实际使用时，可能需要先调用API获取完整数据
      // 这里模拟直接使用传入的行数据
      const rowData = JSON.parse(JSON.stringify(row));

      // 打印原始数据，查看后端返回的字段结构
      console.log('编辑模式下原始数据:', rowData);

      // 处理字段名称的映射，确保前端和后端字段名称一致
      // 处理 ContentType 字段（可能后端是 ContentType，前端是 contentType）
      if (rowData.ContentType !== undefined && rowData.contentType === undefined) {
        rowData.contentType = rowData.ContentType;
        console.log('映射 ContentType -> contentType:', rowData.contentType);
      }

      // 处理 Example 字段（可能后端是 Example，前端是 example）
      if (rowData.Example !== undefined && rowData.example === undefined) {
        rowData.example = rowData.Example;
        console.log('映射 Example -> example:', rowData.example);
      }

      // 处理 Private 字段（可能后端是 Private，前端是 private）
      if (rowData.Private !== undefined && rowData.private === undefined) {
        rowData.private = rowData.Private;
        console.log('映射 Private -> private:', rowData.private);
      }

      // 如果没有 contentType，设置默认值
      if (rowData.contentType === undefined || rowData.contentType === null || rowData.contentType === '') {
        rowData.contentType = 'application/x-www-form-urlencoded';
        console.log('设置默认 contentType:', rowData.contentType);
      }

      // 处理 private 字段的数据类型，确保是数字类型
      if (rowData.private !== undefined) {
        // 如果是字符串，转换为数字
        if (typeof rowData.private === 'string') {
          rowData.private = parseInt(rowData.private, 10) || 0;
          console.log('将 private 从字符串转换为数字:', rowData.private);
        }
      } else {
        // 如果没有 private，设置默认值
        rowData.private = 0;
        console.log('设置默认 private:', rowData.private);
      }

      Object.assign(formData, rowData);

      // 打印最终表单数据，查看是否正确设置了这三个字段
      console.log('最终表单数据:', {
        contentType: formData.contentType,
        example: formData.example,
        private: formData.private
      });

      // 确保参数数组存在
      if (!formData.parameters) {
        formData.parameters = [];
      }
    });
  }
  if (defaultGroupKey) {
    // 新增模式，设置默认分组
    formData.groupKey = defaultGroupKey;
  }
};

defineExpose({ open });
</script>

<style scoped>
/* 错误提示样式 */
:deep(.error-tabs-list) {
  text-align: left;
  padding: 5px 0;
}

:deep(.error-title) {
  font-weight: bold;
  margin-bottom: 5px;
}

:deep(.error-tabs-list ul) {
  list-style: disc;
  padding-left: 20px;
  margin: 5px 0;
}

:deep(.error-tab-item) {
  margin: 3px 0;
  padding: 2px 0;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.dialog-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.dialog-tools {
  display: flex;
  align-items: center;
}

:deep(.el-dialog__header) {
  padding: 15px 0;
  margin: 0;
}

:deep(.el-dialog__headerbtn) {
  top: 15px;
  right: 20px;
}

:deep(.el-dialog__body) {
  padding-top: 0;
}

.api-edit .dialog-body-with-tabs {
  display: flex;
  height: 600px; /* 固定高度，使切换tab时不会改变 */
}

.tab-navigation {
  width: 150px; /* 稍微加宽一点导航宽度 */
  border-right: 1px solid #e0e0e0; /* 颜色调整 */
  padding-right: 0; /* 移除右边padding，让li撑满 */
  margin-right: 0; /* 移除右边margin */
}

.tab-navigation ul {
  list-style: none;
  padding: 10px 0;
  margin: 0;
}

.tab-navigation li {
  padding: 12px 20px; /* 调整padding */
  cursor: pointer;
  /* border-radius: 4px; */ /* 移除圆角，使其更像设计图的tab */
  margin-bottom: 2px; /* tab之间的间距 */
  font-size: 14px;
  color: #303133;
}

.tab-navigation li:hover {
  background-color: #f0f2f5; /* hover颜色调整 */
}

.tab-navigation li.active {
  background-color: #e6f7ff; /* active背景色调整 */
  color: #1890ff; /* active文字颜色调整 */
  border-right: 3px solid #1890ff; /* active时右侧有蓝色竖线 */
  font-weight: 500; /* active时文字稍微加粗 */
}

.tab-content {
  flex: 1;
  overflow-y: auto;
  height: 100%; /* 使内容区域填充整个高度 */
  padding: 10px 20px; /* tab内容的padding */
}

.form-section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  padding: 10px 0;
  margin-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
}

.basic-info-tab,
.executor-tab,
.plugins-tab {
  height: 100%; /* 使每个标签页内容区域填充整个高度 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
}

.basic-info-tab .el-form-item,
.executor-tab .el-form-item,
.plugins-tab .el-form-item {
  margin-bottom: 18px; /* 统一表单项间距 */
}

/* 全局插件样式 */
.plugins-tab .form-section-title {
  margin-bottom: 15px; /* Ensure space before the first plugin item or empty state */
}

.plugin-list-item {
  display: flex;
  align-items: flex-start; /* Aligns items to the top, good if details section can vary in height */
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}
.plugin-list-item:last-of-type {
  border-bottom: none;
  padding-bottom: 0; /* No padding if it's the last item and no border */
}

.plugin-item-details {
  flex-grow: 1;
}

.plugin-item-details .plugin-field {
  margin-bottom: 10px;
}
.plugin-item-details .plugin-field:last-of-type {
  margin-bottom: 0; /* No margin for the last field in the details section */
}

.plugin-remove-action {
  flex-shrink: 0;
  margin-left: 15px;
  padding-top: 5px; /* Small top padding to align better with first line of text or input */
}

.empty-plugins {
  text-align: center;
  padding: 20px 0;
  color: #909399;
}

/* Monaco Editor 样式 */
.sql-content-item {
  width: 100%;
}

.monaco-editor-wrapper {
  display: flex;
  align-items: stretch;
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  min-width: 500px;
}

.line-number-container {
  background-color: #f5f7fa;
  border-right: 1px solid #dcdfe6;
  min-width: 40px;
  width: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 8px;
}

.line-number {
  color: #909399;
  font-family: monospace;
  font-size: 12px;
  line-height: 1.5;
  text-align: center;
  width: 100%;
}

.monaco-editor-container {
  height: 350px; /* 增加编辑器高度，使其更好地利用空间 */
  flex-grow: 1;
  overflow: hidden;
  border: none;
}

/* API路径输入框样式 */
.path-input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.path-prefix2 {
  background-color: #eee;
  padding: 0 10px;
  height: 32px;
  line-height: 32px;
  border: 1px solid #dcdfe6;
  border-right: none;
  border-radius: 4px 0 0 4px;
  color: #606266;
  white-space: nowrap;
}

/* 深色主题下的样式 */
[data-theme='dark'] .path-prefix2 {
  background-color: #333;
  border-color: #424242;
  color: #dadada;
}

.path-input {
  flex: 1;
}

:deep(.path-input .el-input__inner) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

/* 请求方法和API名称同行样式 */
.method-name-container {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 10px;
}

.method-select {
  width: 120px;
  flex-shrink: 0;
}

.name-input {
  flex: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  border-top: 1px solid #e0e0e0;
}
</style>
