<template><div class="page-content">
  <div class="mb-5 flex items-start justify-between">
    <div><h2 class="text-xl font-semibold">数字员工</h2><p class="text-g-500 mt-1 text-sm">人设 + 模型 + Skills/工具/MCP/知识库编排，发布后进入资源市场供用户安装对话；发布前校验全部绑定</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="130"/>
    <ElTableColumn prop="model" label="模型" min-width="130"/>
    <ElTableColumn label="绑定" width="180"><template #default="{row}"><ElTag size="small" type="primary">技能{{row.skill_ids.length}}</ElTag><ElTag size="small" type="info">工具{{row.tool_ids.length}}</ElTag><ElTag size="small" type="success">MCP{{row.mcp_server_ids.length}}</ElTag></template></ElTableColumn>
    <ElTableColumn label="参数" width="150"><template #default="{row}"><span class="text-g-500 text-xs">temp {{row.temperature}} · {{row.max_tool_rounds}}轮</span></template></ElTableColumn>
    <ElTableColumn label="状态" width="150"><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="250" fixed="right"><template #default="{row}">
      <ElButton link type="primary" @click="openRuns(row)">运行记录</ElButton>
      <ElButton v-if="row.status!=='published'" link type="success" @click="publish(row)">发布</ElButton>
      <ElButton v-else link type="warning" @click="archive(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?'编辑数字员工':'新建数字员工'" width="860px">
    <ElForm label-width="110px">
      <div class="grid grid-cols-2 gap-x-4">
        <ElFormItem label="编码"><ElInput v-model="form.code" placeholder="support_agent"/></ElFormItem>
        <ElFormItem label="名称"><ElInput v-model="form.name"/></ElFormItem>
      </div>
      <ElFormItem label="描述"><ElInput v-model="form.description" type="textarea"/></ElFormItem>
      <ElFormItem label="人设"><ElInput v-model="form.persona" type="textarea" :rows="3" placeholder="你是公司的技术支持专家，回复简洁专业……"/></ElFormItem>
      <ElFormItem label="模型"><ElInput v-model="form.model" placeholder="deepseek-chat"/></ElFormItem>
      <div class="grid grid-cols-2 gap-x-4">
        <ElFormItem label="Skills"><ElSelect v-model="form.skill_ids" multiple class="w-full" placeholder="绑定技能"><ElOption v-for="s in skills" :key="s.id" :label="s.name" :value="s.id"/></ElSelect></ElFormItem>
        <ElFormItem label="工具"><ElSelect v-model="form.tool_ids" multiple class="w-full" placeholder="绑定工具"><ElOption v-for="t in tools" :key="t.id" :label="t.name" :value="t.id"/></ElSelect></ElFormItem>
      </div>
      <div class="grid grid-cols-2 gap-x-4">
        <ElFormItem label="MCP 服务器"><ElSelect v-model="form.mcp_server_ids" multiple class="w-full" placeholder="绑定 MCP"><ElOption v-for="m in mcpServers" :key="m.id" :label="m.name" :value="m.id"/></ElSelect></ElFormItem>
        <ElFormItem label="知识库"><ElSelect v-model="form.knowledge_base_ids" multiple class="w-full" placeholder="绑定知识库"><ElOption v-for="k in knowledge" :key="k.id" :label="k.name" :value="k.id"/></ElSelect></ElFormItem>
      </div>
      <div class="grid grid-cols-3 gap-x-4">
        <ElFormItem label="温度"><ElInputNumber v-model="form.temperature" :min="0" :max="2" :step="0.1" class="w-full"/></ElFormItem>
        <ElFormItem label="召回 TopK"><ElInputNumber v-model="form.retrieval_top_k" :min="1" :max="50" class="w-full"/></ElFormItem>
        <ElFormItem label="工具轮次"><ElInputNumber v-model="form.max_tool_rounds" :min="1" :max="20" class="w-full"/></ElFormItem>
      </div>
      <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="runsVisible" :title="'运行记录：'+(running?.name||'')" width="760px">
    <ElTable v-loading="runsLoading" :data="runs" row-key="id">
      <ElTableColumn prop="request_id" label="请求 ID" min-width="200"/>
      <ElTableColumn label="状态" width="90"><template #default="{row}"><ElTag :type="row.status==='success'?'success':'danger'">{{row.status==='success'?'成功':'失败'}}</ElTag></template></ElTableColumn>
      <ElTableColumn prop="latency_ms" label="耗时ms" width="90"/>
      <ElTableColumn label="检索/工具" width="110"><template #default="{row}">{{row.retrieval_count}} / {{row.tool_count}}</template></ElTableColumn>
      <ElTableColumn label="错误" min-width="180" show-overflow-tooltip><template #default="{row}">{{row.error||'—'}}</template></ElTableColumn>
      <ElTableColumn prop="created_at" label="时间" width="180"/>
    </ElTable>
  </ElDialog>
</div></template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { archiveDigitalEmployee, createDigitalEmployee, deleteDigitalEmployee, fetchDigitalEmployeeRuns, fetchMarketplaceCategories, fetchMCPServers, fetchDigitalEmployees, fetchSkills, publishDigitalEmployee, updateDigitalEmployee, type DigitalEmployee, type DigitalEmployeeInput, type DigitalEmployeeRun, type MarketplaceCategory, type MCPServer, type Skill } from '@/api/marketplace'
import { fetchKnowledgeBases, fetchTools, type KnowledgeBase, type ToolDefinition } from '@/api/workbench'
const loading = ref(false), visible = ref(false), runsVisible = ref(false), runsLoading = ref(false), editing = ref('')
const items = ref<DigitalEmployee[]>([]), categories = ref<MarketplaceCategory[]>([])
const skills = ref<Skill[]>([]), tools = ref<ToolDefinition[]>([]), mcpServers = ref<MCPServer[]>([]), knowledge = ref<KnowledgeBase[]>([])
const runs = ref<DigitalEmployeeRun[]>([]), running = ref<DigitalEmployee>()
const blank = (): DigitalEmployeeInput => ({ code: '', name: '', description: '', persona: '', model: '', skill_ids: [], tool_ids: [], mcp_server_ids: [], knowledge_base_ids: [], temperature: 0.7, retrieval_top_k: 5, max_tool_rounds: 5, status: 'draft', category_id: null, tags: [], department_ids: [], enabled: true })
const form = reactive<DigitalEmployeeInput>(blank())
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, skills.value, tools.value, mcpServers.value, knowledge.value] = await Promise.all([fetchDigitalEmployees(), fetchMarketplaceCategories(), fetchSkills(), fetchTools(), fetchMCPServers(), fetchKnowledgeBases()])
  } finally { loading.value = false }
}
function openCreate() { editing.value = ''; Object.assign(form, blank()); visible.value = true }
function openEdit(row: DigitalEmployee) {
  editing.value = row.id
  Object.assign(form, { code: row.code, name: row.name, description: row.description, persona: row.persona, model: row.model, skill_ids: [...row.skill_ids], tool_ids: [...row.tool_ids], mcp_server_ids: [...row.mcp_server_ids], knowledge_base_ids: [...row.knowledge_base_ids], temperature: row.temperature, retrieval_top_k: row.retrieval_top_k, max_tool_rounds: row.max_tool_rounds, status: row.status, category_id: row.category_id ?? null, tags: [...row.tags], department_ids: [...row.department_ids], enabled: row.enabled })
  visible.value = true
}
async function toggleEnabled(row: DigitalEmployee, v: boolean) { await updateDigitalEmployee(row.id, { ...row, enabled: v }); await load() }
async function save() {
  editing.value ? await updateDigitalEmployee(editing.value, form) : await createDigitalEmployee(form)
  visible.value = false; await load()
}
async function publish(row: DigitalEmployee) {
  try { await publishDigitalEmployee(row.id); ElMessage.success('已发布到资源市场'); await load() } catch (e) { ElMessage.error(String(e)) }
}
async function archive(row: DigitalEmployee) {
  await archiveDigitalEmployee(row.id); await load()
}
async function remove(row: DigitalEmployee) {
  await ElMessageBox.confirm(`删除数字员工“${row.name}”？`, '确认', { type: 'warning' })
  await deleteDigitalEmployee(row.id); await load()
}
async function openRuns(row: DigitalEmployee) {
  running.value = row; runsVisible.value = true; runsLoading.value = true
  try { runs.value = await fetchDigitalEmployeeRuns(row.id) } finally { runsLoading.value = false }
}
onMounted(load)
</script>
