<template><div class="page-content">
  <div class="mb-5 flex items-start justify-between">
    <div><h2 class="text-xl font-semibold">Skills 技能</h2><p class="text-g-500 mt-1 text-sm">带变量与工具/知识库绑定的提示词包：先渲染、再绑定到数字员工，发布后进入资源市场</p></div>
    <ElButton type="primary" @click="openCreate">新建 Skill</ElButton>
  </div>
  <ElTable v-loading="loading" :data="items" row-key="id">
    <ElTableColumn prop="code" label="编码" min-width="120"/>
    <ElTableColumn prop="name" label="名称" min-width="130"/>
    <ElTableColumn label="正文" min-width="240" show-overflow-tooltip><template #default="{row}"><span class="line-clamp-2 text-g-500">{{row.content}}</span></template></ElTableColumn>
    <ElTableColumn label="绑定" width="150"><template #default="{row}"><ElTag size="small" type="info">工具{{row.tool_ids.length}}</ElTag><ElTag size="small" type="success">MCP{{row.mcp_server_ids.length}}</ElTag><ElTag size="small" type="warning">知识{{row.knowledge_base_ids.length}}</ElTag></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="200" fixed="right"><template #default="{row}"><ElButton link type="primary" @click="openPreview(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?'编辑 Skill':'新建 Skill'" width="820px">
    <ElForm label-width="100px">
      <div class="grid grid-cols-2 gap-x-4">
        <ElFormItem label="编码"><ElInput v-model="form.code" placeholder="support_qa"/></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.content" type="textarea" :rows="6" placeholder="支持 {{变量}} 占位符渲染"/></ElFormItem>
      <ElFormItem label="变量"><div class="w-full space-y-2">
        <div v-for="(v,i) in form.variables" :key="i" class="grid grid-cols-[1fr_1fr_90px_30px] items-center gap-2">
          <ElInput v-model="v.name" placeholder="变量名"/>
          <ElInput v-model="v.label" placeholder="标签"/>
          <div class="flex items-center justify-center"><ElSwitch v-model="v.required"/><span class="ml-1 text-xs text-g-500">必填</span></div>
          <ElButton link type="danger" :icon="'Delete'" @click="form.variables.splice(i,1)"/>
        </div>
        <ElButton size="small" @click="form.variables.push({name:'',label:'',required:false})">+ 添加变量</ElButton>
      </div></ElFormItem>
      <div class="grid grid-cols-3 gap-x-4">
        <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>
        <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-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="previewVisible" :title="'渲染预览：'+(previewing?.name||'')" width="680px">
    <div class="space-y-3">
      <ElFormItem v-for="v in previewing?.variables||[]" :key="v.name" :label="v.label||v.name">
        <ElInput v-model="previewValues[v.name]" :placeholder="String(v.default??'')"/>
      </ElFormItem>
      <ElButton type="primary" :loading="previewNow" @click="runPreview">渲染</ElButton>
      <pre class="max-h-80 overflow-auto rounded bg-black p-3 text-xs text-white">{{previewResult}}</pre>
    </div>
  </ElDialog>
</div></template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { createSkill, deleteSkill, fetchMarketplaceCategories, fetchMCPServers, fetchSkills, renderSkill, updateSkill, type MarketplaceCategory, type MCPServer, type Skill, type SkillInput } from '@/api/marketplace'
import { fetchKnowledgeBases, fetchTools, type KnowledgeBase, type ToolDefinition } from '@/api/workbench'
const loading = ref(false), visible = ref(false), previewVisible = ref(false), previewNow = ref(false)
const editing = ref(''), items = ref<Skill[]>([]), categories = ref<MarketplaceCategory[]>([])
const tools = ref<ToolDefinition[]>([]), mcpServers = ref<MCPServer[]>([]), knowledge = ref<KnowledgeBase[]>([])
const previewing = ref<Skill>(), previewValues = ref<Record<string, string>>({}), previewResult = ref('')
const blank = (): SkillInput => ({ code: '', name: '', description: '', content: '', variables: [], tool_ids: [], mcp_server_ids: [], knowledge_base_ids: [], status: 'draft', category_id: null, tags: [], department_ids: [], enabled: true })
const form = reactive<SkillInput>(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, tools.value, mcpServers.value, knowledge.value] = await Promise.all([fetchSkills(), fetchMarketplaceCategories(), fetchTools(), fetchMCPServers(), fetchKnowledgeBases()])
  } finally { loading.value = false }
}
function openCreate() { editing.value = ''; Object.assign(form, blank()); visible.value = true }
function openEdit(row: Skill) {
  editing.value = row.id
  Object.assign(form, { code: row.code, name: row.name, description: row.description, content: row.content, variables: row.variables.map(v => ({ ...v })), tool_ids: [...row.tool_ids], mcp_server_ids: [...row.mcp_server_ids], knowledge_base_ids: [...row.knowledge_base_ids], 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: Skill, v: boolean) { await updateSkill(row.id, { ...row, enabled: v }); await load() }
async function save() {
  editing.value ? await updateSkill(editing.value, form) : await createSkill(form)
  visible.value = false; await load()
}
async function remove(row: Skill) {
  await ElMessageBox.confirm(`删除 Skill“${row.name}”？`, '确认', { type: 'warning' })
  await deleteSkill(row.id); await load()
}
function openPreview(row: Skill) {
  previewing.value = row
  previewValues.value = {}
  for (const v of row.variables) if (v.default) previewValues.value[v.name] = v.default
  previewResult.value = ''; previewVisible.value = true
}
async function runPreview() {
  if (!previewing.value) return
  previewNow.value = true
  try { const r = await renderSkill(previewing.value.id, previewValues.value); previewResult.value = r.rendered } finally { previewNow.value = false }
}
onMounted(load)
</script>
