<template><div class="page-content">
  <div class="mb-5 flex items-start justify-between">
    <div><h2 class="text-xl font-semibold">MCP 服务器</h2><p class="text-g-500 mt-1 text-sm">注册标准 MCP 服务器（streamable HTTP / SSE），自动发现工具后注入数字员工与运行时；端点经 SSRF 校验，凭据头加密存储</p></div>
    <ElButton type="primary" @click="openCreate">注册服务器</ElButton>
  </div>
  <ElTable v-loading="loading" :data="items" row-key="id">
    <ElTableColumn prop="code" label="编码" min-width="130"/>
    <ElTableColumn prop="name" label="名称" min-width="140"/>
    <ElTableColumn label="端点" min-width="240"><template #default="{row}"><ElTag :type="row.transport==='sse'?'warning':'info'">{{row.transport}}</ElTag><span class="ml-2">{{row.endpoint_url}}</span></template></ElTableColumn>
    <ElTableColumn label="分类" width="110"><template #default="{row}">{{row.category_name||'—'}}</template></ElTableColumn>
    <ElTableColumn label="凭据" width="90"><template #default="{row}">{{row.has_secret_headers?'已加密':'无'}}</template></ElTableColumn>
    <ElTableColumn label="状态" width="160"><template #default="{row}"><ElTag :type="statusType(row.status)">{{statusLabel(row.status)}}</ElTag><ElSwitch class="ml-2" :model-value="row.enabled" @change="v=>toggleEnabled(row,Boolean(v))" size="small"/></template></ElTableColumn>
    <ElTableColumn label="操作" width="210" fixed="right"><template #default="{row}"><ElButton link type="primary" @click="openTest(row)">测试</ElButton><ElButton link type="primary" @click="openEdit(row)">编辑</ElButton><ElButton link type="danger" @click="remove(row)">删除</ElButton></template></ElTableColumn>
  </ElTable>

  <ElDialog v-model="visible" :title="editing?'编辑 MCP 服务器':'注册 MCP 服务器'" width="720px">
    <ElForm label-width="100px">
      <div class="grid grid-cols-2 gap-x-4">
        <ElFormItem label="编码"><ElInput v-model="form.code" placeholder="github_mcp"/></ElFormItem>
        <ElFormItem label="名称"><ElInput v-model="form.name"/></ElFormItem>
      </div>
      <ElFormItem label="描述"><ElInput v-model="form.description" type="textarea"/></ElFormItem>
      <div class="grid grid-cols-[130px_1fr] gap-x-4">
        <ElFormItem label="传输方式"><ElSelect v-model="form.transport"><ElOption value="streamable-http" label="streamable HTTP"/><ElOption value="sse" label="SSE"/></ElSelect></ElFormItem>
        <ElFormItem label="端点 URL"><ElInput v-model="form.endpoint_url" placeholder="https://mcp.example.com/mcp"/></ElFormItem>
      </div>
      <ElFormItem label="请求头 JSON"><ElInput v-model="headersJSON" type="textarea" :rows="3" :placeholder="editing&&currentHasHeaders?'留空以保留现有加密请求头':'{&quot;Authorization&quot;:&quot;Bearer ...&quot;}'"/></ElFormItem>
      <div class="grid grid-cols-2 gap-x-4">
        <ElFormItem label="状态"><ElSelect v-model="form.status"><ElOption value="draft" label="草稿"/><ElOption value="published" label="已发布"/><ElOption value="archived" label="已归档"/></ElSelect></ElFormItem>
        <ElFormItem label="分类"><ElSelect v-model="form.category_id" clearable class="w-full"><ElOption v-for="c in categories" :key="c.id" :label="c.name" :value="c.id"/></ElSelect></ElFormItem>
      </div>
      <ElFormItem label="标签"><ElSelect v-model="form.tags" multiple allow-create filterable default-first-option class="w-full"/></ElFormItem>
      <ElFormItem label="部门范围"><ElSelect v-model="form.department_ids" multiple allow-create filterable class="w-full" placeholder="留空为公开市场资源"/></ElFormItem>
      <ElFormItem label="启用"><ElSwitch v-model="form.enabled"/></ElFormItem>
    </ElForm>
    <template #footer><ElButton @click="visible=false">取消</ElButton><ElButton type="primary" @click="save">保存</ElButton></template>
  </ElDialog>

  <ElDialog v-model="testVisible" :title="'连通性测试：'+(testing?.name||'')" width="620px">
    <div class="mb-3 flex items-center gap-2"><ElTag type="info">{{testing?.endpoint_url}}</ElTag><ElButton type="primary" :loading="testingNow" @click="runTest">重新发现工具</ElButton></div>
    <ElTable v-if="testTools.length" :data="testTools" row-key="name">
      <ElTableColumn prop="name" label="工具名" min-width="140"/>
      <ElTableColumn prop="description" label="描述"/>
    </ElTable>
    <ElEmpty v-else description="尚未测试或未发现工具"/>
  </ElDialog>
</div></template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { createMCPServer, deleteMCPServer, fetchMarketplaceCategories, fetchMCPServers, testMCPServer, updateMCPServer, type MarketplaceCategory, type MCPServer, type MCPServerInput, type MCPTool } from '@/api/marketplace'
const loading = ref(false), visible = ref(false), testVisible = ref(false), testingNow = ref(false)
const editing = ref(''), currentHasHeaders = ref(false)
const items = ref<MCPServer[]>([]), categories = ref<MarketplaceCategory[]>([])
const testTools = ref<MCPTool[]>([]), testing = ref<MCPServer>()
const blank = (): MCPServerInput => ({ code: '', name: '', description: '', transport: 'streamable-http', endpoint_url: '', status: 'draft', category_id: null, tags: [], department_ids: [], enabled: true })
const form = reactive<MCPServerInput>(blank()), headersJSON = ref('{}')
function statusType(s: string) { return s === 'published' ? 'success' : s === 'archived' ? 'info' : 'warning' }
function statusLabel(s: string) { return s === 'published' ? '已发布' : s === 'archived' ? '已归档' : '草稿' }
async function load() {
  loading.value = true
  try {
    ;[items.value, categories.value] = await Promise.all([fetchMCPServers(), fetchMarketplaceCategories()])
  } finally { loading.value = false }
}
function openCreate() { editing.value = ''; currentHasHeaders.value = false; Object.assign(form, blank()); headersJSON.value = '{}'; visible.value = true }
function openEdit(row: MCPServer) {
  editing.value = row.id; currentHasHeaders.value = row.has_secret_headers
  Object.assign(form, { code: row.code, name: row.name, description: row.description, transport: row.transport, endpoint_url: row.endpoint_url, status: row.status, category_id: row.category_id ?? null, tags: [...row.tags], department_ids: [...row.department_ids], enabled: row.enabled })
  headersJSON.value = ''; visible.value = true
}
async function toggleEnabled(row: MCPServer, v: boolean) {
  await updateMCPServer(row.id, { ...row, enabled: v })
  await load()
}
async function save() {
  try {
    if (headersJSON.value.trim()) form.headers = JSON.parse(headersJSON.value)
    else delete form.headers
  } catch { ElMessage.error('请求头 JSON 格式无效'); return }
  editing.value ? await updateMCPServer(editing.value, form) : await createMCPServer(form)
  visible.value = false; await load()
}
async function remove(row: MCPServer) {
  await ElMessageBox.confirm(`删除 MCP 服务器“${row.name}”？`, '确认', { type: 'warning' })
  await deleteMCPServer(row.id); await load()
}
function openTest(row: MCPServer) { testing.value = row; testTools.value = []; testVisible.value = true; runTest() }
async function runTest() {
  if (!testing.value) return
  testingNow.value = true
  try { testTools.value = await testMCPServer(testing.value.id) } finally { testingNow.value = false }
}
onMounted(load)
</script>
