<script setup lang="ts">
import type {
  Agent,
  AgentUpdateInput,
  KnowledgeBaseSimpleItem,
  ModelListItem,
  WorkflowListItem,
} from '#/api/ai-platform/ai-platform';

import { defineAsyncComponent, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import {
  ArrowLeft,
  Bot,
  CircleHelp,
  CirclePlus,
  Play,
  Save,
  Trash2,
} from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDivider,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElOption,
  ElScrollbar,
  ElSelect,
  ElSlider,
  ElSwitch,
  ElTabPane,
  ElTabs,
  ElTag,
  ElTooltip,
} from 'element-plus';

import {
  getActiveModelsApi,
  getAgentDetailApi,
  getKnowledgeBaseSimpleListApi,
  getWorkflowListApi,
  publishAgentApi,
  updateAgentApi,
} from '#/api/ai-platform/ai-platform';
import { useAppContextStore } from '#/store/app-context';

const AiChatPanel = defineAsyncComponent(() =>
  import('#/components/ai-chat-panel/AiChatPanel.vue'),
);

const appContextStore = useAppContextStore();

const route = useRoute();
const router = useRouter();
const agentId = route.params.id as string;

// 数据
const loading = ref(false);
const saving = ref(false);
const agent = ref<Agent | null>(null);
const activeTab = ref('persona');

// 表单数据
const formData = reactive<AgentUpdateInput>({
  name: '',
  description: '',
  avatar: '',
  mode: 'autonomous',
  persona: {
    role: '',
    personality: [],
    skills: [],
    constraints: [],
    background: '',
    examples: [],
  },
  system_prompt: '',
  model_id: '',
  temperature: 0.7,
  top_p: 1,
  max_tokens: 4096,
  max_iterations: 10,
  welcome_message: '',
  suggested_questions: [],
  workflow_id: '',
  is_public: false,
  enable_memory: false,
  memory_window: 10,
  enable_streaming: true,
  knowledge_base_ids: [],
  knowledge_config: {
    top_k: 5,
    score_threshold: 0.5,
    retrieval_mode: 'hybrid',
    annotation_reply_enabled: false,
    annotation_threshold: 0.9,
  },
});

// 模型列表
const modelList = ref<ModelListItem[]>([]);

// 工作流列表（对话流模式）
const workflowList = ref<WorkflowListItem[]>([]);

// 知识库列表
const knowledgeBaseList = ref<KnowledgeBaseSimpleItem[]>([]);

// 人设输入
const personalityInput = ref('');
const skillInput = ref('');
const constraintInput = ref('');
const questionInput = ref('');

// 从 Agent 获取表单数据
function getFormDataFromAgent(a: Agent): AgentUpdateInput {
  return {
    name: a.name,
    description: a.description,
    avatar: a.avatar,
    mode: a.mode,
    persona: a.persona || {},
    system_prompt: a.system_prompt,
    model_id: a.model_id || '',
    temperature: a.temperature,
    top_p: a.top_p,
    max_tokens: a.max_tokens,
    max_iterations: a.max_iterations,
    welcome_message: a.welcome_message,
    suggested_questions: a.suggested_questions || [],
    workflow_id: a.workflow_id || '',
    is_public: a.is_public,
    enable_memory: a.enable_memory || false,
    memory_window: a.memory_window || 10,
    enable_streaming: a.enable_streaming ?? true,
    knowledge_base_ids: a.knowledge_base_ids || [],
    knowledge_config: a.knowledge_config || {
      top_k: 5,
      score_threshold: 0.5,
      retrieval_mode: 'hybrid',
    },
  };
}

// 加载智能体详情
async function loadAgent() {
  loading.value = true;
  try {
    const data = await getAgentDetailApi(agentId);
    agent.value = data;
    Object.assign(formData, getFormDataFromAgent(data));
  } catch (error) {
    console.error('加载智能体失败:', error);
    ElMessage.error($t('ai-platform.agent.loadFailed'));
  } finally {
    loading.value = false;
  }
}

// 加载模型列表
async function loadModels() {
  try {
    const data = await getActiveModelsApi();
    modelList.value = data.filter((m) => m.model_type === 'chat');
  } catch (error) {
    console.error('加载模型列表失败:', error);
  }
}

// 加载工作流列表
async function loadWorkflows() {
  try {
    // 只加载已发布的工作流
    const res = await getWorkflowListApi({
      status: 'published',
      pageSize: 100,
    });
    workflowList.value = res.items;
  } catch (error) {
    console.error('加载工作流列表失败:', error);
  }
}

// 保存
async function handleSave() {
  saving.value = true;
  try {
    await updateAgentApi(agentId, formData);
    ElMessage.success($t('ai-platform.agent.saveSuccess'));
    await loadAgent();
  } catch (error: any) {
    ElMessage.error(error.message || $t('ai-platform.agent.saveFailed'));
  } finally {
    saving.value = false;
  }
}

// 发布
async function handlePublish() {
  try {
    // 先自动保存
    await updateAgentApi(agentId, formData);
    ElMessage.success($t('ai-platform.agent.saveSuccess'));

    // 然后发布
    await publishAgentApi(agentId);
    ElMessage.success($t('ai-platform.agent.publishSuccess'));
    await loadAgent();
  } catch (error: any) {
    ElMessage.error(error.message || $t('ai-platform.agent.operationFailed'));
  }
}

// 返回
function handleBack() {
  router.push(appContextStore.getContextPath('/ai-platform/agent'));
}

// 添加性格特点
function addPersonality() {
  if (personalityInput.value.trim()) {
    if (!formData.persona) formData.persona = {};
    if (!formData.persona.personality) formData.persona.personality = [];
    formData.persona.personality.push(personalityInput.value.trim());
    personalityInput.value = '';
  }
}

// 删除性格特点
function removePersonality(index: number) {
  formData.persona?.personality?.splice(index, 1);
}

// 添加技能
function addSkill() {
  if (skillInput.value.trim()) {
    if (!formData.persona) formData.persona = {};
    if (!formData.persona.skills) formData.persona.skills = [];
    formData.persona.skills.push(skillInput.value.trim());
    skillInput.value = '';
  }
}

// 删除技能
function removeSkill(index: number) {
  formData.persona?.skills?.splice(index, 1);
}

// 添加约束
function addConstraint() {
  if (constraintInput.value.trim()) {
    if (!formData.persona) formData.persona = {};
    if (!formData.persona.constraints) formData.persona.constraints = [];
    formData.persona.constraints.push(constraintInput.value.trim());
    constraintInput.value = '';
  }
}

// 删除约束
function removeConstraint(index: number) {
  formData.persona?.constraints?.splice(index, 1);
}

// 添加推荐问题
function addQuestion() {
  if (questionInput.value.trim()) {
    if (!formData.suggested_questions) formData.suggested_questions = [];
    formData.suggested_questions.push(questionInput.value.trim());
    questionInput.value = '';
  }
}

// 删除推荐问题
function removeQuestion(index: number) {
  formData.suggested_questions?.splice(index, 1);
}

// ==================== 对话预览相关 ====================

// 监听模式切换，重置 activeTab
watch(
  () => formData.mode,
  (newMode) => {
    // 对话流模式下，某些标签页不存在，需要切换到有效的标签页
    if (
      newMode === 'dialog_flow' &&
      ['model', 'persona', 'prompt'].includes(activeTab.value)
    ) {
      activeTab.value = 'welcome';
    }
  },
);

// 加载知识库列表
async function loadKnowledgeBases() {
  try {
    const data = await getKnowledgeBaseSimpleListApi();
    knowledgeBaseList.value = data;
  } catch (error) {
    console.error('加载知识库列表失败:', error);
  }
}

onMounted(() => {
  loadAgent();
  loadModels();
  loadWorkflows();
  loadKnowledgeBases();
});
</script>

<template>
  <div class="agent-editor bg-background-deep flex h-screen flex-col">
    <!-- 顶部工具栏 -->
    <div
      class="bg-background m-3 flex h-14 flex-shrink-0 items-center justify-between rounded-[8px] px-4"
    >
      <div class="flex items-center gap-4">
        <ElButton link @click="handleBack">
          <ArrowLeft class="mr-1 h-4 w-4" />
          {{ $t('ai-platform.agent.back') }}
        </ElButton>
        <ElDivider direction="vertical" />
        <div class="flex items-center gap-2">
          <Bot class="text-primary h-5 w-5" />
          <span class="text-lg font-medium">{{
            agent?.name || $t('ai-platform.agent.loading')
          }}</span>
          <ElTag
            v-if="agent"
            size="small"
            :type="agent.status === 'published' ? 'success' : 'info'"
          >
            {{
              agent.status === 'published'
                ? $t('ai-platform.agent.status.published')
                : agent.status === 'disabled'
                  ? $t('ai-platform.agent.status.disabled')
                  : $t('ai-platform.agent.status.draft')
            }}
          </ElTag>
        </div>
      </div>
      <div class="flex items-center gap-2">
        <ElButton
          v-if="agent?.status !== 'published'"
          type="success"
          @click="handlePublish"
        >
          <Play class="mr-1 h-4 w-4" />
          {{ $t('ai-platform.agent.publish') }}
        </ElButton>
        <ElButton :loading="saving" type="primary" plain @click="handleSave">
          <Save class="mr-1 h-4 w-4" />
          {{ $t('ai-platform.agent.save') }}
        </ElButton>
      </div>
    </div>

    <!-- 主体内容：左右布局 -->
    <div class="flex flex-1 overflow-hidden">
      <!-- 左侧：配置编排 -->
      <div
        v-loading="loading"
        class="mx-3 mb-3 flex w-1/2 flex-col overflow-hidden rounded-[8px]"
      >
        <ElScrollbar class="flex-1">
          <div class="">
            <!-- 基本信息 -->
            <ElCard class="mb-4" style="border: none" shadow="never">
              <template #header>
                <span class="font-medium">{{
                  $t('ai-platform.agent.basicInfo')
                }}</span>
              </template>
              <ElForm label-position="top">
                <div class="grid grid-cols-2 gap-4">
                  <ElFormItem :label="$t('ai-platform.agent.form.name')">
                    <ElInput v-model="formData.name" />
                  </ElFormItem>
                  <ElFormItem :label="$t('ai-platform.agent.form.appCode')">
                    <ElInput :model-value="agent?.code" disabled />
                  </ElFormItem>
                  <ElFormItem>
                    <template #label>
                      <div class="flex items-center gap-1">
                        <span>{{ $t('ai-platform.agent.runMode') }}</span>
                        <ElTooltip
                          placement="top"
                          :content="$t('ai-platform.agent.runModeTooltip')"
                        >
                          <CircleHelp
                            class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                          />
                        </ElTooltip>
                      </div>
                    </template>
                    <ElSelect v-model="formData.mode" style="width: 100%">
                      <ElOption
                        :label="$t('ai-platform.agent.mode.autonomousLabel')"
                        value="autonomous"
                      />
                      <ElOption
                        :label="$t('ai-platform.agent.mode.dialogFlowLabel')"
                        value="dialog_flow"
                      />
                    </ElSelect>
                  </ElFormItem>
                </div>
                <!-- 对话流模式：选择工作流 -->
                <ElFormItem v-if="formData.mode === 'dialog_flow'">
                  <template #label>
                    <div class="flex items-center gap-1">
                      <span>{{ $t('ai-platform.agent.relatedWorkflow') }}</span>
                      <ElTooltip
                        placement="top"
                        :content="
                          $t('ai-platform.agent.relatedWorkflowTooltip')
                        "
                      >
                        <CircleHelp
                          class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                        />
                      </ElTooltip>
                    </div>
                  </template>
                  <ElSelect
                    v-model="formData.workflow_id"
                    clearable
                    filterable
                    :placeholder="$t('ai-platform.agent.selectWorkflow')"
                    style="width: 100%"
                  >
                    <ElOption
                      v-for="wf in workflowList"
                      :key="wf.id"
                      :label="wf.name"
                      :value="wf.id"
                    >
                      <div class="flex items-center justify-between">
                        <span>{{ wf.name }}</span>
                        <span class="text-muted-foreground text-xs">{{
                          wf.code
                        }}</span>
                      </div>
                    </ElOption>
                  </ElSelect>
                  <div class="text-muted-foreground mt-1 text-xs">
                    {{ $t('ai-platform.agent.dialogFlowHint') }}
                  </div>
                </ElFormItem>
                <!-- 对话流模式：记忆配置 -->
                <ElFormItem v-if="formData.mode === 'dialog_flow'">
                  <template #label>
                    <div class="flex items-center gap-1">
                      <span>{{
                        $t('ai-platform.agent.conversationMemory')
                      }}</span>
                      <ElTooltip
                        placement="top"
                        :content="
                          $t('ai-platform.agent.conversationMemoryTooltip')
                        "
                      >
                        <CircleHelp
                          class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                        />
                      </ElTooltip>
                    </div>
                  </template>
                  <div class="flex items-center gap-4">
                    <ElSwitch v-model="formData.enable_memory" />
                    <span class="text-muted-foreground text-sm">
                      {{
                        formData.enable_memory
                          ? $t('ai-platform.agent.enabled')
                          : $t('ai-platform.agent.notEnabled')
                      }}
                    </span>
                  </div>
                </ElFormItem>
                <ElFormItem
                  v-if="
                    formData.mode === 'dialog_flow' && formData.enable_memory
                  "
                >
                  <template #label>
                    <div class="flex items-center gap-1">
                      <span>{{ $t('ai-platform.agent.memoryWindow') }}</span>
                      <ElTooltip
                        placement="top"
                        :content="$t('ai-platform.agent.memoryWindowTooltip')"
                      >
                        <CircleHelp
                          class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                        />
                      </ElTooltip>
                    </div>
                  </template>
                  <ElInputNumber
                    v-model="formData.memory_window"
                    :min="1"
                    :max="50"
                    style="width: 120px"
                  />
                  <span class="text-muted-foreground ml-2 text-sm">{{
                    $t('ai-platform.agent.rounds')
                  }}</span>
                </ElFormItem>
                <ElFormItem :label="$t('ai-platform.agent.form.description')">
                  <ElInput
                    v-model="formData.description"
                    :rows="2"
                    :placeholder="$t('ai-platform.agent.agentDescription')"
                    type="textarea"
                  />
                </ElFormItem>
              </ElForm>
            </ElCard>

            <!-- 配置标签页 -->
            <ElCard style="border: none" shadow="never">
              <ElTabs v-model="activeTab">
                <!-- 人设配置（仅自主规划模式） -->
                <ElTabPane
                  v-if="formData.mode === 'autonomous'"
                  :label="$t('ai-platform.agent.persona.title')"
                  name="persona"
                >
                  <ElForm label-position="top">
                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.persona.role')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="
                              $t('ai-platform.agent.persona.roleTooltip')
                            "
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <ElInput
                        v-model="formData.persona!.role"
                        :rows="3"
                        :placeholder="
                          $t('ai-platform.agent.persona.rolePlaceholder')
                        "
                        type="textarea"
                      />
                    </ElFormItem>

                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.persona.personality')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="
                              $t('ai-platform.agent.persona.personalityTooltip')
                            "
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <div class="mb-2 flex flex-wrap gap-2">
                        <ElTag
                          v-for="(p, index) in formData.persona?.personality ||
                          []"
                          :key="index"
                          closable
                          @close="removePersonality(index)"
                        >
                          {{ p }}
                        </ElTag>
                      </div>
                      <div class="flex gap-2">
                        <ElInput
                          v-model="personalityInput"
                          :placeholder="
                            $t(
                              'ai-platform.agent.persona.personalityPlaceholder',
                            )
                          "
                          @keyup.enter="addPersonality"
                        />
                        <ElButton @click="addPersonality">
                          {{ $t('ai-platform.agent.persona.add') }}
                        </ElButton>
                      </div>
                    </ElFormItem>

                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.persona.skills')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="
                              $t('ai-platform.agent.persona.skillsTooltip')
                            "
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <div class="mb-2 flex flex-wrap gap-2">
                        <ElTag
                          v-for="(s, index) in formData.persona?.skills || []"
                          :key="index"
                          closable
                          type="success"
                          @close="removeSkill(index)"
                        >
                          {{ s }}
                        </ElTag>
                      </div>
                      <div class="flex gap-2">
                        <ElInput
                          v-model="skillInput"
                          :placeholder="
                            $t('ai-platform.agent.persona.skillsPlaceholder')
                          "
                          @keyup.enter="addSkill"
                        />
                        <ElButton @click="addSkill">
                          {{ $t('ai-platform.agent.persona.add') }}
                        </ElButton>
                      </div>
                    </ElFormItem>

                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.persona.constraints')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="
                              $t('ai-platform.agent.persona.constraintsTooltip')
                            "
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <div class="mb-2 flex flex-wrap gap-2">
                        <ElTag
                          v-for="(c, index) in formData.persona?.constraints ||
                          []"
                          :key="index"
                          closable
                          type="warning"
                          @close="removeConstraint(index)"
                        >
                          {{ c }}
                        </ElTag>
                      </div>
                      <div class="flex gap-2">
                        <ElInput
                          v-model="constraintInput"
                          :placeholder="
                            $t(
                              'ai-platform.agent.persona.constraintsPlaceholder',
                            )
                          "
                          @keyup.enter="addConstraint"
                        />
                        <ElButton @click="addConstraint">
                          {{ $t('ai-platform.agent.persona.add') }}
                        </ElButton>
                      </div>
                    </ElFormItem>

                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.persona.background')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="
                              $t('ai-platform.agent.persona.backgroundTooltip')
                            "
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <ElInput
                        v-model="formData.persona!.background"
                        :rows="3"
                        :placeholder="
                          $t('ai-platform.agent.persona.backgroundPlaceholder')
                        "
                        type="textarea"
                      />
                    </ElFormItem>
                  </ElForm>
                </ElTabPane>

                <!-- 提示词配置（仅自主规划模式） -->
                <ElTabPane
                  v-if="formData.mode === 'autonomous'"
                  :label="$t('ai-platform.agent.prompt.title')"
                  name="prompt"
                >
                  <ElForm label-position="top">
                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.prompt.title')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="$t('ai-platform.agent.prompt.tooltip')"
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <ElInput
                        v-model="formData.system_prompt"
                        :rows="12"
                        :placeholder="
                          $t('ai-platform.agent.prompt.placeholder')
                        "
                        type="textarea"
                      />
                    </ElFormItem>
                  </ElForm>
                </ElTabPane>

                <!-- 模型配置（仅自主规划模式） -->
                <ElTabPane
                  v-if="formData.mode === 'autonomous'"
                  :label="$t('ai-platform.agent.model.title')"
                  name="model"
                >
                  <ElForm label-position="top">
                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{ $t('ai-platform.agent.model.label') }}</span>
                          <ElTooltip
                            placement="top"
                            :content="$t('ai-platform.agent.model.tooltip')"
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <ElSelect
                        v-model="formData.model_id"
                        filterable
                        :placeholder="$t('ai-platform.agent.model.placeholder')"
                        style="width: 100%"
                      >
                        <ElOption
                          v-for="model in modelList"
                          :key="model.id"
                          :label="model.display_name"
                          :value="model.id"
                        />
                      </ElSelect>
                    </ElFormItem>

                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.model.temperature')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="
                              $t('ai-platform.agent.model.temperatureTooltip')
                            "
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <ElSlider
                        v-model="formData.temperature"
                        :max="2"
                        :min="0"
                        :step="0.1"
                        show-input
                      />
                    </ElFormItem>

                    <div class="grid grid-cols-2 gap-4">
                      <ElFormItem>
                        <template #label>
                          <div class="flex items-center gap-1">
                            <span>{{
                              $t('ai-platform.agent.model.maxToken')
                            }}</span>
                            <ElTooltip
                              placement="top"
                              :content="
                                $t('ai-platform.agent.model.maxTokenTooltip')
                              "
                            >
                              <CircleHelp
                                class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                              />
                            </ElTooltip>
                          </div>
                        </template>
                        <ElInputNumber
                          v-model="formData.max_tokens"
                          :max="32000"
                          :min="100"
                          :step="100"
                          style="width: 100%"
                        />
                      </ElFormItem>

                      <ElFormItem>
                        <template #label>
                          <div class="flex items-center gap-1">
                            <span>{{
                              $t('ai-platform.agent.model.maxIterations')
                            }}</span>
                            <ElTooltip
                              placement="top"
                              :content="
                                $t(
                                  'ai-platform.agent.model.maxIterationsTooltip',
                                )
                              "
                            >
                              <CircleHelp
                                class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                              />
                            </ElTooltip>
                          </div>
                        </template>
                        <ElInputNumber
                          v-model="formData.max_iterations"
                          :max="20"
                          :min="1"
                          style="width: 100%"
                        />
                      </ElFormItem>
                    </div>

                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.model.streaming')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="
                              $t('ai-platform.agent.model.streamingTooltip')
                            "
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <div class="flex items-center gap-4">
                        <ElSwitch v-model="formData.enable_streaming" />
                        <span class="text-muted-foreground text-sm">
                          {{
                            formData.enable_streaming
                              ? $t('ai-platform.agent.enabled')
                              : $t('ai-platform.agent.notEnabled')
                          }}
                        </span>
                      </div>
                    </ElFormItem>
                  </ElForm>
                </ElTabPane>

                <!-- 知识库配置（仅自主规划模式） -->
                <ElTabPane
                  v-if="formData.mode === 'autonomous'"
                  :label="$t('ai-platform.agent.knowledgeBase.title')"
                  name="knowledge"
                >
                  <ElForm label-position="top">
                    <ElFormItem
                      :label="$t('ai-platform.agent.knowledgeBase.label')"
                    >
                      <ElSelect
                        v-model="formData.knowledge_base_ids"
                        clearable
                        filterable
                        multiple
                        :placeholder="
                          $t('ai-platform.agent.knowledgeBase.placeholder')
                        "
                        style="width: 100%"
                      >
                        <ElOption
                          v-for="kb in knowledgeBaseList"
                          :key="kb.id"
                          :label="kb.name"
                          :value="kb.id"
                        >
                          <div class="flex items-center justify-between">
                            <span>{{ kb.name }}</span>
                            <span class="text-muted-foreground text-xs">
                              {{ kb.document_count || 0 }}
                              {{
                                $t('ai-platform.agent.knowledgeBase.documents')
                              }}
                            </span>
                          </div>
                        </ElOption>
                      </ElSelect>
                      <div class="text-muted-foreground mt-1 text-xs">
                        {{ $t('ai-platform.agent.knowledgeBase.hint') }}
                      </div>
                    </ElFormItem>

                    <template
                      v-if="
                        formData.knowledge_base_ids &&
                        formData.knowledge_base_ids.length > 0
                      "
                    >
                      <ElFormItem>
                        <template #label>
                          <div class="flex items-center gap-1">
                            <span>{{
                              $t(
                                'ai-platform.agent.knowledgeBase.retrievalMode',
                              )
                            }}</span>
                            <ElTooltip
                              placement="top"
                              :content="
                                $t(
                                  'ai-platform.agent.knowledgeBase.retrievalModeTooltip',
                                )
                              "
                            >
                              <CircleHelp
                                class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                              />
                            </ElTooltip>
                          </div>
                        </template>
                        <ElSelect
                          v-model="formData.knowledge_config!.retrieval_mode"
                          style="width: 100%"
                        >
                          <ElOption
                            :label="
                              $t(
                                'ai-platform.agent.knowledgeBase.hybridRecommended',
                              )
                            "
                            value="hybrid"
                          />
                          <ElOption
                            :label="
                              $t('ai-platform.agent.knowledgeBase.vectorSearch')
                            "
                            value="vector"
                          />
                          <ElOption
                            :label="
                              $t(
                                'ai-platform.agent.knowledgeBase.fulltextSearch',
                              )
                            "
                            value="fulltext"
                          />
                        </ElSelect>
                      </ElFormItem>

                      <div class="grid grid-cols-2 gap-4">
                        <ElFormItem>
                          <template #label>
                            <div class="flex items-center gap-1">
                              <span>{{
                                $t('ai-platform.agent.knowledgeBase.topK')
                              }}</span>
                              <ElTooltip
                                placement="top"
                                :content="
                                  $t(
                                    'ai-platform.agent.knowledgeBase.topKTooltip',
                                  )
                                "
                              >
                                <CircleHelp
                                  class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                                />
                              </ElTooltip>
                            </div>
                          </template>
                          <ElInputNumber
                            v-model="formData.knowledge_config!.top_k"
                            :max="20"
                            :min="1"
                            style="width: 100%"
                          />
                        </ElFormItem>

                        <ElFormItem>
                          <template #label>
                            <div class="flex items-center gap-1">
                              <span>{{
                                $t(
                                  'ai-platform.agent.knowledgeBase.scoreThreshold',
                                )
                              }}</span>
                              <ElTooltip
                                placement="top"
                                :content="
                                  $t(
                                    'ai-platform.agent.knowledgeBase.scoreThresholdTooltip',
                                  )
                                "
                              >
                                <CircleHelp
                                  class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                                />
                              </ElTooltip>
                            </div>
                          </template>
                          <ElSlider
                            v-model="formData.knowledge_config!.score_threshold"
                            :max="1"
                            :min="0"
                            :step="0.05"
                            show-input
                          />
                        </ElFormItem>
                      </div>

                      <ElDivider />

                      <ElFormItem>
                        <template #label>
                          <div class="flex items-center gap-1">
                            <span>{{
                              $t('ai-platform.agent.knowledge.annotationReply')
                            }}</span>
                            <ElTooltip
                              placement="top"
                              :content="
                                $t(
                                  'ai-platform.agent.knowledge.annotationReplyTip',
                                )
                              "
                            >
                              <CircleHelp
                                class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                              />
                            </ElTooltip>
                          </div>
                        </template>
                        <ElSwitch
                          v-model="
                            formData.knowledge_config!.annotation_reply_enabled
                          "
                        />
                      </ElFormItem>

                      <ElFormItem
                        v-if="
                          formData.knowledge_config!.annotation_reply_enabled
                        "
                      >
                        <template #label>
                          <div class="flex items-center gap-1">
                            <span>{{
                              $t(
                                'ai-platform.agent.knowledge.annotationThreshold',
                              )
                            }}</span>
                            <ElTooltip
                              placement="top"
                              :content="
                                $t(
                                  'ai-platform.agent.knowledge.annotationThresholdTip',
                                )
                              "
                            >
                              <CircleHelp
                                class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                              />
                            </ElTooltip>
                          </div>
                        </template>
                        <ElSlider
                          v-model="
                            formData.knowledge_config!.annotation_threshold
                          "
                          :max="1"
                          :min="0.5"
                          :step="0.05"
                          show-input
                        />
                      </ElFormItem>
                    </template>
                  </ElForm>
                </ElTabPane>

                <!-- 开场白配置 -->
                <ElTabPane
                  :label="$t('ai-platform.agent.welcome.title')"
                  name="welcome"
                >
                  <ElForm label-position="top">
                    <ElFormItem>
                      <template #label>
                        <div class="flex items-center gap-1">
                          <span>{{
                            $t('ai-platform.agent.welcome.title')
                          }}</span>
                          <ElTooltip
                            placement="top"
                            :content="$t('ai-platform.agent.welcome.tooltip')"
                          >
                            <CircleHelp
                              class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                            />
                          </ElTooltip>
                        </div>
                      </template>
                      <ElInput
                        v-model="formData.welcome_message"
                        :rows="4"
                        :placeholder="
                          $t('ai-platform.agent.welcome.placeholder')
                        "
                        type="textarea"
                      />
                    </ElFormItem>
                  </ElForm>
                </ElTabPane>

                <!-- 推荐问题配置 -->
                <ElTabPane
                  :label="$t('ai-platform.agent.suggestions.title')"
                  name="suggestions"
                >
                  <div class="text-muted-foreground mb-4 text-sm">
                    {{ $t('ai-platform.agent.suggestions.hint') }}
                  </div>

                  <!-- 推荐问题列表 -->
                  <div class="space-y-3">
                    <div
                      v-for="(_q, index) in formData.suggested_questions || []"
                      :key="index"
                      class="bg-card hover:border-primary/50 group flex items-center gap-3 rounded-lg border p-3 transition-all"
                    >
                      <div
                        class="bg-primary/10 text-primary flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full text-xs font-medium"
                      >
                        {{ index + 1 }}
                      </div>
                      <ElInput
                        v-model="formData.suggested_questions![index]"
                        :placeholder="
                          $t('ai-platform.agent.suggestions.placeholder')
                        "
                        class="flex-1"
                      />
                      <ElButton
                        link
                        type="danger"
                        class="opacity-0 transition-opacity group-hover:opacity-100"
                        @click="removeQuestion(index)"
                      >
                        <Trash2 class="h-4 w-4" />
                      </ElButton>
                    </div>
                  </div>

                  <!-- 添加新问题 -->
                  <div class="mt-4 flex gap-2">
                    <ElInput
                      v-model="questionInput"
                      :placeholder="
                        $t('ai-platform.agent.suggestions.inputPlaceholder')
                      "
                      @keyup.enter="addQuestion"
                    />
                    <ElButton type="primary" @click="addQuestion">
                      <CirclePlus class="mr-1 h-4 w-4" />
                      {{ $t('ai-platform.agent.suggestions.add') }}
                    </ElButton>
                  </div>

                  <!-- 空状态 -->
                  <div
                    v-if="!formData.suggested_questions?.length"
                    class="mt-4 rounded-lg border-2 border-dashed p-8 text-center"
                  >
                    <div class="text-muted-foreground">
                      {{ $t('ai-platform.agent.suggestions.empty') }}
                    </div>
                  </div>
                </ElTabPane>
              </ElTabs>
            </ElCard>
          </div>
        </ElScrollbar>
      </div>

      <!-- 右侧：对话预览与调试 -->
      <div class="bg-muted mb-3 mr-3 flex flex-1 flex-col overflow-hidden">
        <AiChatPanel
          mode="agent-debug"
          :agent-id="agentId"
          :agent="agent as any"
          :disabled="agent?.status !== 'published'"
          :placeholder="
            agent?.status === 'published'
              ? $t('ai-platform.agent.debug.inputPlaceholder')
              : $t('ai-platform.agent.debug.publishFirst')
          "
          :show-clear-button="true"
          :show-close-button="false"
          :show-header="false"
          :enable-voice="true"
          layout="fullscreen"
          class="flex-1"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.agent-editor {
  height: 100vh;
}
</style>
