<template><div class="page-content space-y-6">
  <div class="mb-2"><h2 class="text-xl font-semibold">市场总览</h2><p class="text-g-500 mt-1 text-sm">分类管理 + 三类已发布资源的统一目录（MCP 服务器 / Skills / 数字员工）</p></div>

  <ElCard shadow="never">
    <template #header><div class="flex items-center justify-between"><span>分类管理</span><ElButton size="small" type="primary" @click="catOpen">新增分类</ElButton></div></template>
    <ElTable v-loading="catLoading" :data="categories" row-key="id">
      <ElTableColumn prop="name" label="名称" min-width="150"/>
      <ElTableColumn prop="description" label="描述" min-width="220"/>
      <ElTableColumn label="适用范围" width="140"><template #default="{row}">{{row.resource_type ? typeLabel(row.resource_type) : '全局'}}</template></ElTableColumn>
      <ElTableColumn prop="sort_order" label="排序" width="80"/>
      <ElTableColumn label="操作" width="90" fixed="right"><template #default="{row}"><ElButton link type="danger" @click="catRemove(row)">删除</ElButton></template></ElTableColumn>
    </ElTable>
  </ElCard>

  <ElCard shadow="never">
    <template #header><div class="flex items-center justify-between"><span>统一目录（已发布资源）</span><div class="flex items-center gap-2">
      <ElSelect v-model="filter.type" clearable placeholder="全部类型" class="w-40"><ElOption v-for="t in types" :key="t.value" :label="t.label" :value="t.value"/></ElSelect>
      <ElSelect v-model="filter.category_id" clearable placeholder="全部分类" class="w-40"><ElOption v-for="c in categories" :key="c.id" :label="c.name" :value="c.id"/></ElSelect>
      <ElInput v-model="filter.q" placeholder="搜索名称/编码" clearable class="w-52"/>
      <ElButton type="primary" @click="loadCatalog">查询</ElButton>
    </div></div></template>
    <ElTable v-loading="catalogLoading" :data="catalog" row-key="code">
      <ElTableColumn label="类型" width="110"><template #default="{row}"><ElTag :type="typeTag(row.type)">{{typeLabel(row.type)}}</ElTag></template></ElTableColumn>
      <ElTableColumn prop="code" label="编码" min-width="140"/>
      <ElTableColumn prop="name" label="名称" min-width="150"/>
      <ElTableColumn prop="description" label="描述" min-width="240" show-overflow-tooltip/>
      <ElTableColumn label="分类" width="120"><template #default="{row}">{{row.category_name||'—'}}</template></ElTableColumn>
      <ElTableColumn label="标签" width="180"><template #default="{row}"><ElTag v-for="t in row.tags" :key="t" size="small" class="mr-1">{{t}}</ElTag></template></ElTableColumn>
      <ElTableColumn label="范围" width="100"><template #default="{row}">{{row.department_ids.length?`${row.department_ids.length} 部门`:'公开'}}</template></ElTableColumn>
      <ElTableColumn prop="updated_at" label="更新时间" width="180"/>
    </ElTable>
  </ElCard>

  <ElDialog v-model="catVisible" title="新增分类" width="440px">
    <ElForm label-width="90px">
      <ElFormItem label="名称"><ElInput v-model="catForm.name"/></ElFormItem>
      <ElFormItem label="描述"><ElInput v-model="catForm.description" type="textarea"/></ElFormItem>
      <ElFormItem label="适用范围"><ElSelect v-model="catForm.resource_type"><ElOption value="" label="全局"/><ElOption v-for="t in types" :key="t.value" :label="t.label" :value="t.value"/></ElSelect></ElFormItem>
      <ElFormItem label="排序"><ElInputNumber v-model="catForm.sort_order" :min="0"/></ElFormItem>
    </ElForm>
    <template #footer><ElButton @click="catVisible=false">取消</ElButton><ElButton type="primary" @click="catSave">保存</ElButton></template>
  </ElDialog>
</div></template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { createMarketplaceCategory, deleteMarketplaceCategory, fetchMarketplaceCategories, fetchMarketplaceCatalog, type MarketplaceCategory, type MarketItem } from '@/api/marketplace'
const catLoading = ref(false), catalogLoading = ref(false), catVisible = ref(false)
const categories = ref<MarketplaceCategory[]>([]), catalog = ref<MarketItem[]>([])
const catForm = reactive({ name: '', description: '', resource_type: '', sort_order: 0 })
const filter = reactive({ type: '', category_id: '', q: '' })
const types = [{ value: 'mcp_server', label: 'MCP 服务器' }, { value: 'skill', label: 'Skill' }, { value: 'digital_employee', label: '数字员工' }]
function typeLabel(t: string) { return types.find(x => x.value === t)?.label || t }
function typeTag(t: string) { return t === 'digital_employee' ? 'primary' : t === 'mcp_server' ? 'success' : 'warning' }
async function load() {
  catLoading.value = true
  try { categories.value = await fetchMarketplaceCategories() } finally { catLoading.value = false }
  await loadCatalog()
}
async function loadCatalog() {
  catalogLoading.value = true
  try {
    const params: Record<string, string | number> = {}
    if (filter.type) params.type = filter.type
    if (filter.category_id) params.category_id = filter.category_id
    if (filter.q) params.q = filter.q
    catalog.value = await fetchMarketplaceCatalog(params)
  } finally { catalogLoading.value = false }
}
function catOpen() { Object.assign(catForm, { name: '', description: '', resource_type: '', sort_order: 0 }); catVisible.value = true }
async function catSave() {
  await createMarketplaceCategory({ ...catForm, resource_type: catForm.resource_type || undefined })
  catVisible.value = false; await load()
}
async function catRemove(row: MarketplaceCategory) {
  await ElMessageBox.confirm(`删除分类“${row.name}”？`, '确认', { type: 'warning' })
  await deleteMarketplaceCategory(row.id); await load()
}
onMounted(load)
</script>
