<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">浏览已发布的 MCP 服务器、Skills 与数字员工，安装后可对话使用；跨部门资源仅对所属部门可见</p></div>
      <ElButton :type="view==='browse'?'primary':'default'" @click="toggleView">{{view==='browse'?'我的安装':'浏览市场'}}</ElButton>
    </div>

    <template v-if="view==='browse'">
      <div class="mb-4 flex flex-wrap items-center gap-2">
        <ElRadioGroup v-model="filter.type" @change="loadMarket">
          <ElRadioButton value="">全部</ElRadioButton>
          <ElRadioButton value="mcp_server">MCP 服务器</ElRadioButton>
          <ElRadioButton value="skill">Skills</ElRadioButton>
          <ElRadioButton value="digital_employee">数字员工</ElRadioButton>
        </ElRadioGroup>
        <ElSelect v-model="filter.category_id" clearable placeholder="分类" class="w-40" @change="loadMarket">
          <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-56" @change="loadMarket"/>
        <ElButton type="primary" @click="loadMarket">查询</ElButton>
      </div>
      <div v-loading="loading" class="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
        <ElCard v-for="item in items" :key="item.type+':'+item.code" shadow="hover">
          <div class="flex items-start justify-between">
            <div class="flex items-center gap-2"><ElTag :type="typeTag(item.type)" size="small">{{typeLabel(item.type)}}</ElTag><b>{{item.name}}</b></div>
            <ElTag v-if="installed.has(item.type+':'+item.code)" type="success" size="small">已安装</ElTag>
          </div>
          <p class="text-g-500 mt-2 min-h-10 text-sm">{{item.description||'暂无描述'}}</p>
          <div class="mt-2 flex items-center justify-between">
            <div class="flex flex-wrap gap-1"><ElTag v-for="t in item.tags.slice(0,3)" :key="t" size="small" class="mr-1">{{t}}</ElTag><span v-if="item.category_name" class="text-g-400 text-xs">{{item.category_name}}</span></div>
            <code class="text-xs">{{item.code}}</code>
          </div>
          <div class="mt-3 flex justify-end gap-2">
            <ElButton size="small" @click="openDetail(item)">详情</ElButton>
            <ElButton v-if="!installed.has(item.type+':'+item.code)" size="small" type="primary" @click="install(item)">安装</ElButton>
            <ElButton v-else size="small" type="danger" plain @click="uninstall(item)">卸载</ElButton>
          </div>
        </ElCard>
        <ElEmpty v-if="!loading && !items.length" class="col-span-full"/>
      </div>
    </template>

    <template v-else>
      <div v-loading="loading" class="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
        <ElCard v-for="item in installedItems" :key="item.type+':'+item.code" shadow="hover">
          <div class="flex items-start justify-between">
            <div class="flex items-center gap-2"><ElTag :type="typeTag(item.type)" size="small">{{typeLabel(item.type)}}</ElTag><b>{{item.name}}</b></div>
            <ElTag type="success" size="small">已安装</ElTag>
          </div>
          <p class="text-g-500 mt-2 min-h-10 text-sm">{{item.description||'暂无描述'}}</p>
          <div class="mt-3 flex justify-end gap-2">
            <ElButton size="small" @click="openDetail(item)">详情</ElButton>
            <ElButton size="small" type="danger" plain @click="uninstall(item)">卸载</ElButton>
          </div>
        </ElCard>
        <ElEmpty v-if="!loading && !installedItems.length" class="col-span-full" description="还没有安装任何资源"/>
      </div>
    </template>

    <ElDrawer v-model="detailVisible" :title="detail?.item?.name" size="480px">
      <template v-if="detail">
        <ElTag :type="typeTag(detail.item.type)" size="small">{{typeLabel(detail.item.type)}}</ElTag>
        <h3 class="mt-3 text-lg font-semibold">{{detail.item.name}}</h3>
        <code class="text-xs">{{detail.item.code}}</code>
        <p class="text-g-500 mt-3 text-sm">{{detail.item.description||'暂无描述'}}</p>
        <ElDivider/>
        <div class="text-g-500 text-sm">详情字段</div>
        <pre class="mt-2 max-h-80 overflow-auto rounded bg-black p-3 text-xs text-white">{{JSON.stringify(detail.detail,null,2)}}</pre>
        <div class="mt-4">
          <ElButton v-if="!installed.has(detail.item.type+':'+detail.item.code)" type="primary" class="w-full" @click="install(detail.item)">安装到我的工作台</ElButton>
          <ElButton v-else type="danger" plain class="w-full" @click="uninstall(detail.item)">卸载</ElButton>
        </div>
      </template>
    </ElDrawer>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { fetchMarketplace, fetchMarketplaceCategories, fetchMarketplaceDetail, fetchMarketplaceInstalled, marketplaceInstall, marketplaceUninstall, type MarketItem, type MarketplaceCategory } from '@/api/portal'
const loading = ref(false), detailVisible = ref(false), view = ref<'browse'|'installed'>('browse')
const items = ref<MarketItem[]>([]), installedItems = ref<MarketItem[]>([])
const categories = ref<MarketplaceCategory[]>([])
const installed = ref<Set<string>>(new Set())
const detail = ref<{ item: MarketItem; detail: Record<string, unknown> }>()
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' }
const key = (i: MarketItem) => `${i.type}:${i.code}`
async function loadInstalled() {
  installedItems.value = await fetchMarketplaceInstalled()
  installed.value = new Set(installedItems.value.map(key))
}
async function loadMarket() {
  loading.value = true
  try {
    const params: Record<string, string> = {}
    if (filter.type) params.type = filter.type
    if (filter.category_id) params.category_id = filter.category_id
    if (filter.q) params.q = filter.q
    items.value = await fetchMarketplace(params)
  } finally { loading.value = false }
}
async function toggleView() {
  view.value = view.value === 'browse' ? 'installed' : 'browse'
  if (view.value === 'installed') { loading.value = true; try { await loadInstalled() } finally { loading.value = false } }
}
async function install(item: MarketItem) {
  await marketplaceInstall(item.type, item.code)
  ElMessage.success('已安装')
  await Promise.all([loadInstalled(), loadMarket()])
}
async function uninstall(item: MarketItem) {
  await marketplaceUninstall(item.type, item.code)
  ElMessage.success('已卸载')
  await Promise.all([loadInstalled(), loadMarket()])
}
async function openDetail(item: MarketItem) {
  const data = await fetchMarketplaceDetail(item.type, item.code)
  detail.value = data; detailVisible.value = true
}
onMounted(async () => {
  categories.value = await fetchMarketplaceCategories()
  await loadInstalled()
  await loadMarket()
})
</script>
