<template>
  <div class="page-content">
    <div class="mb-5 flex items-center justify-between gap-4">
      <div>
        <h2 class="text-xl font-semibold">我的申请</h2>
        <p class="text-g-500 mt-1 text-sm">资源(MCP/Skill/数字员工)与渠道使用权限申请，审批通过后自动开通</p>
      </div>
      <ElButton type="primary" @click="visible = true">发起申请</ElButton>
    </div>

    <ElTable v-loading="loading" :data="items" row-key="id">
      <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="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 prop="decision_note" label="审批意见" min-width="150" />
      <ElTableColumn label="操作" width="90" fixed="right">
        <template #default="{ row }">
          <ElButton v-if="row.status === 'pending'" link type="danger" @click="cancel(row)">撤回</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElDialog v-model="visible" title="申请资源 / 渠道权限" width="560px">
      <ElForm label-width="110px">
        <ElFormItem label="类型" required>
          <ElSelect v-model="form.resource_type" class="w-full">
            <ElOption label="MCP 服务器" value="mcp_server" />
            <ElOption label="Skill" value="skill" />
            <ElOption label="数字员工" value="digital_employee" />
            <ElOption label="渠道" value="channel" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="资源代码" required>
          <ElInput v-model="form.resource_code" placeholder="例如 resource_code（需与管理员确认的唯一代码）" />
        </ElFormItem>
        <ElFormItem label="申请理由" required>
          <ElInput v-model="form.reason" type="textarea" :rows="4" maxlength="4000" show-word-limit />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" :loading="saving" @click="submit">提交</ElButton>
      </template>
    </ElDialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { ResourceRequest, cancelResourceRequest, createResourceRequest, fetchMyResourceRequests } from '@/api/portal'

const loading = ref(false)
const saving = ref(false)
const visible = ref(false)
const items = ref<ResourceRequest[]>([])
const form = reactive({ resource_type: 'mcp_server', resource_code: '', reason: '' })

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

async function load() {
  loading.value = true
  try {
    items.value = await fetchMyResourceRequests()
  } finally {
    loading.value = false
  }
}

async function submit() {
  if (!form.resource_code.trim() || !form.reason.trim()) {
    ElMessage.warning('请填写资源代码与申请理由')
    return
  }
  saving.value = true
  try {
    await createResourceRequest({ ...form, resource_code: form.resource_code.trim(), reason: form.reason.trim() })
    ElMessage.success('申请已提交，等待管理员审批')
    visible.value = false
    form.resource_code = ''
    form.reason = ''
    await load()
  } catch (error) {
    ElMessage.error((error as Error)?.message || '提交失败')
  } finally {
    saving.value = false
  }
}

async function cancel(row: ResourceRequest) {
  await ElMessageBox.confirm('撤回后需重新提交，确定撤回该申请？', '撤回申请', { type: 'warning' })
  await cancelResourceRequest(row.id)
  row.status = 'cancelled'
  ElMessage.success('已撤回')
}

onMounted(load)
</script>
