<template>
  <el-card v-if="visible" shadow="never" class="plugin-list-card">
    <template #header>
      <div class="plg-header">
        <span class="plg-title">已加载插件 ({{ plugins.length }})</span>
        <el-button text size="small" :icon="ArrowDown" class="plg-collapse" @click="collapsed = !collapsed">
          {{ collapsed ? '展开' : '折叠' }}
        </el-button>
        <el-button size="small" :loading="loading" :icon="Refresh" @click="refresh">刷新</el-button>
      </div>
    </template>
    <div v-if="!collapsed">
      <el-empty
        v-if="!loading && plugins.length === 0"
        description="尚未通过 PluginManager 加载任何插件 (重启 SimpleLite 后会自动迁移现有 plugins/ 内的 dll)"
      />
      <el-table
        v-else
        v-loading="loading"
        :data="plugins"
        size="small"
        stripe
        border
        class="plg-table"
      >
        <el-table-column prop="name" label="插件名" width="200" show-overflow-tooltip />
        <el-table-column prop="assemblyVersion" label="版本" width="120" />
        <el-table-column label="类型贡献" width="200">
          <template #default="{ row }">
            <el-tag size="small" type="success" effect="plain" class="plg-tag">
              进程 {{ row.missionTypes }}
            </el-tag>
            <el-tag size="small" type="primary" effect="plain" class="plg-tag">
              车/脚本 {{ row.carTypes }}
            </el-tag>
            <el-tag size="small" type="info" effect="plain" class="plg-tag">
              共 {{ row.loadedTypes }} type
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dllPath" label="路径" min-width="240" show-overflow-tooltip />
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.collectible" size="small" type="success">可卸载</el-tag>
            <el-tooltip
              v-else
              content="此插件被加到 default ALC（旧路径加载），重启 SimpleLite 后会自动迁移到 collectible"
              placement="top"
            >
              <el-tag size="small" type="warning">不可卸载</el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button
              text
              size="small"
              type="danger"
              :disabled="!row.collectible"
              :loading="unloading === row.name"
              @click="onUnload(row as PluginEntry)"
            >
              卸载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-card>
</template>

<script setup lang="ts">
/**
 * 插件管理面板（仅展示 + 卸载入口；增量加载走父组件的 「刷新插件」 按钮）。
 *
 * - 列出 PluginManager 跟踪的所有插件，标注 collectible / 不可卸载；
 * - 「卸载」按钮：调用 POST /plugins/{name}/unload；后端会先检查没有 Mission/Car 实例
 *   仍在用插件类型，否则 409 失败；卸载完毕后会重建 UiDiscoveryCache。
 */

import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Refresh } from '@element-plus/icons-vue'
import { reflectionApi, type PluginEntry } from '@/api/reflection'

const props = defineProps<{ visible?: boolean }>()
const emit = defineEmits<{ (e: 'changed'): void }>()

const visible = computed(() => props.visible !== false)
const plugins = ref<PluginEntry[]>([])
const loading = ref(false)
const collapsed = ref(true)
const unloading = ref<string | null>(null)

async function refresh() {
  loading.value = true
  try {
    plugins.value = await reflectionApi.listPlugins()
  } catch (err) {
    ElMessage.warning(`插件列表加载失败：${(err as Error).message}（旧版 SimpleLite 可能未带 /plugins 接口，请重启）`)
  } finally {
    loading.value = false
  }
}

async function onUnload(p: PluginEntry) {
  try {
    await ElMessageBox.confirm(
      `确认卸载插件 ${p.name}？\n\n` +
      `此插件贡献了 ${p.missionTypes} 个进程类型 / ${p.carTypes} 个车/脚本类型；` +
      `如果当前还有这些类型的实例存在，卸载会失败（请先在管理面板里删除）。`,
      '卸载插件',
      { type: 'warning', confirmButtonText: '卸载', cancelButtonText: '取消' }
    )
  } catch {
    return
  }
  unloading.value = p.name
  try {
    const r = await reflectionApi.unloadPlugin(p.name)
    ElMessage.success(r.message ?? `已卸载 ${p.name}`)
    emit('changed')
    await refresh()
  } catch (err) {
    ElMessage.error(`卸载失败：${(err as Error).message}`)
  } finally {
    unloading.value = null
  }
}

watch(() => props.visible, (v) => { if (v) refresh() })
onMounted(() => { if (visible.value) refresh() })

defineExpose({ refresh })
</script>

<style scoped>
.plugin-list-card {
  background: rgba(var(--mg-bg-card-rgb, 255, 255, 255), 0.94) !important;
  border: 1px solid var(--mg-veil-border, rgba(40, 33, 58, 0.10)) !important;
  border-radius: 8px !important;
  box-shadow: none !important;
  backdrop-filter: none;
  margin-bottom: 0;
  flex: none;
}
.plg-header {
  display: flex;
  align-items: center;
  gap: 8px;
}
.plg-title {
  font-size: 12.5px;
  font-weight: 650;
  color: var(--el-text-color-primary, #28213a);
}
.plg-collapse { margin-left: auto; }
.plg-tag { margin-right: 4px; margin-bottom: 2px; }
.plg-table {
  background: transparent;
}
:deep(.el-table) { background: transparent; }
:deep(.el-table tr),
:deep(.el-table th.el-table__cell),
:deep(.el-table td.el-table__cell) {
  background: transparent !important;
  color: var(--mg-text-light);
  border-color: var(--mg-divider);
}
:deep(.el-card__header) {
  padding: 10px 14px;
  border-bottom: 1px solid var(--mg-divider);
}
</style>
