<template>
  <div class="page-content">
    <div class="mb-5">
      <h2 class="text-xl font-semibold">审批中心</h2>
      <p class="text-g-500 mt-1 text-sm">统一处理模型访问、资源/渠道权限与工具使用申请，审批通过后自动开通</p>
    </div>

    <ElTabs v-model="activeTab" @tab-change="load">
      <ElTabPane label="模型申请" name="model" />
      <ElTabPane label="资源 / 渠道申请" name="resource" />
      <ElTabPane label="工具审批" name="tool" />
    </ElTabs>

    <ElTable v-if="activeTab === 'model'" v-loading="loading" :data="modelRequests" row-key="id">
      <ElTableColumn prop="user_login" label="申请人" width="140" />
      <ElTableColumn prop="model" label="模型" min-width="180" />
      <ElTableColumn prop="provider_code" label="供应商" width="120" />
      <ElTableColumn prop="reason" label="理由" min-width="200" show-overflow-tooltip />
      <ElTableColumn prop="requested_rpm" label="RPM" width="90" />
      <ElTableColumn prop="requested_monthly_tokens" label="月 Token" width="120" />
      <ElTableColumn label="状态" width="100">
        <template #default="{ row }"><ElTag :type="statusType(row.status)">{{ statusText(row.status) }}</ElTag></template>
      </ElTableColumn>
      <ElTableColumn label="操作" width="170" fixed="right">
        <template #default="{ row }">
          <template v-if="row.status === 'pending'">
            <ElButton link type="success" @click="decide('model', row, 'approve')">通过</ElButton>
            <ElButton link type="danger" @click="decide('model', row, 'reject')">驳回</ElButton>
          </template>
          <span v-else class="text-g-400 text-xs">{{ row.decision_note || '—' }}</span>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElTable v-else-if="activeTab === 'resource'" v-loading="loading" :data="resourceRequests" row-key="id">
      <ElTableColumn prop="user_login" label="申请人" width="140" />
      <ElTableColumn label="类型" width="130">
        <template #default="{ row }">{{ typeName(row.resource_type) }}</template>
      </ElTableColumn>
      <ElTableColumn prop="resource_code" label="资源" min-width="180" />
      <ElTableColumn prop="reason" label="理由" min-width="200" show-overflow-tooltip />
      <ElTableColumn prop="created_at" label="申请时间" width="180" />
      <ElTableColumn label="状态" width="100">
        <template #default="{ row }"><ElTag :type="statusType(row.status)">{{ statusText(row.status) }}</ElTag></template>
      </ElTableColumn>
      <ElTableColumn label="操作" width="170" fixed="right">
        <template #default="{ row }">
          <template v-if="row.status === 'pending'">
            <ElButton link type="success" @click="decide('resource', row, 'approve')">通过并开通</ElButton>
            <ElButton link type="danger" @click="decide('resource', row, 'reject')">驳回</ElButton>
          </template>
          <span v-else class="text-g-400 text-xs">{{ row.decision_note || '—' }}</span>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElTable v-else v-loading="loading" :data="toolApprovals" row-key="id">
      <ElTableColumn prop="tool_name" label="工具" min-width="180" />
      <ElTableColumn prop="tool_code" label="编码" width="160" />
      <ElTableColumn prop="reason" label="原因" min-width="220" show-overflow-tooltip />
      <ElTableColumn prop="created_at" label="申请时间" width="180" />
      <ElTableColumn label="状态" width="100">
        <template #default="{ row }"><ElTag :type="statusType(row.status)">{{ statusText(row.status) }}</ElTag></template>
      </ElTableColumn>
      <ElTableColumn label="操作" width="170" fixed="right">
        <template #default="{ row }">
          <template v-if="row.status === 'pending'">
            <ElButton link type="success" @click="decide('tool', row, 'approve')">通过</ElButton>
            <ElButton link type="danger" @click="decide('tool', row, 'reject')">驳回</ElButton>
          </template>
          <span v-else class="text-g-400 text-xs">{{ row.decision_note || '—' }}</span>
        </template>
      </ElTableColumn>
    </ElTable>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ModelRequest, ResourceRequest, ToolApproval,
  decideModelRequest, decideResourceRequest, decideToolApproval,
  fetchModelRequests, fetchResourceRequests, fetchToolApprovals
} from '@/api/governance'

const activeTab = ref('model')
const loading = ref(false)
const modelRequests = ref<ModelRequest[]>([])
const resourceRequests = ref<ResourceRequest[]>([])
const toolApprovals = ref<ToolApproval[]>([])

const statusText = (v: string) => ({ pending: '待审批', approved: '已通过', rejected: '已驳回', cancelled: '已取消' }[v] || v)
const statusType = (v: string) => (v === 'approved' ? 'success' : v === 'rejected' || v === 'cancelled' ? 'danger' : 'warning')
const typeName = (v: string) => ({ mcp_server: 'MCP 服务器', skill: 'Skill', digital_employee: '数字员工', channel: '渠道' }[v] || v)

async function load() {
  loading.value = true
  try {
    if (activeTab.value === 'model') modelRequests.value = await fetchModelRequests('pending')
    if (activeTab.value === 'resource') resourceRequests.value = await fetchResourceRequests('pending')
    if (activeTab.value === 'tool') toolApprovals.value = await fetchToolApprovals('pending')
  } finally {
    loading.value = false
  }
}

async function decide(kind: 'model' | 'resource' | 'tool', row: any, action: 'approve' | 'reject') {
  const { value } = await ElMessageBox.prompt(
    action === 'approve' ? '通过后申请自动开通，可填写审批备注' : '填写驳回原因（将通知申请人）',
    action === 'approve' ? '通过申请' : '驳回申请',
    { inputPlaceholder: '审批备注（可选）' }
  )
  const note = (value as string) || ''
  try {
    if (kind === 'model') await decideModelRequest(row.id, action, note)
    if (kind === 'resource') await decideResourceRequest(row.id, action, note)
    if (kind === 'tool') await decideToolApproval(row.id, action === 'approve' ? 'approved' : 'rejected', note)
    ElMessage.success(action === 'approve' ? '已通过' : '已驳回')
    await load()
  } catch (error) {
    ElMessage.error((error as Error)?.message || '操作失败')
  }
}

onMounted(load)
</script>
