<template>
  <PermissionGuard widget-id="OpsActionPanel">
    <el-card shadow="never">
      <template #header>
        <div style="display: flex; align-items: center; gap: 8px">
          <span>运维操作（架构 §5.1 白名单）</span>
          <el-tag size="small" type="info">scope=RCSMonitor</el-tag>
          <el-tag size="small" type="success">{{ allowedOps.length }} / {{ OPS_WHITELIST.length }} 可用</el-tag>
        </div>
      </template>
      <el-table :data="OPS_WHITELIST" size="small" border>
        <el-table-column prop="code" label="权限码" width="200">
          <template #default="s"><code>{{ s.row.code }}</code></template>
        </el-table-column>
        <el-table-column prop="label" label="操作" width="140" />
        <el-table-column prop="target" label="目标" width="80" />
        <el-table-column prop="needConfirm" label="二次确认" width="100">
          <template #default="s">
            <el-tag v-if="s.row.needConfirm" size="small" type="warning">是</el-tag>
            <el-tag v-else size="small" effect="plain">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" />
        <el-table-column label="操作" width="200">
          <template #default="s">
            <el-input v-model="targets[s.row.code]" placeholder="目标 ID" size="small" style="width: 100px; margin-right: 6px" />
            <el-button
              size="small"
              :type="s.row.needConfirm ? 'warning' : 'primary'"
              :disabled="!auth.hasOp(s.row.code)"
              @click="execute(s.row)">执行</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card shadow="never" style="margin-top: 12px">
      <template #header><span>本地操作记录（占位 Mock）</span></template>
      <el-timeline>
        <el-timeline-item v-for="a in audits" :key="a.id" :timestamp="a.ts" :type="a.result === 'ok' ? 'success' : 'danger'">
          <strong>{{ a.opCode }}</strong> → {{ a.target }}（{{ a.user }}）
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </PermissionGuard>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PermissionGuard from '@/components/PermissionGuard.vue'
import { OPS_WHITELIST, type OpsAction, type OpsAuditEntry } from '@/types/ops'
import { useAuthStore } from '@/stores/auth'
import { executeOp, listAudits } from '@/api/ops'

const auth = useAuthStore()
const targets = reactive<Record<string, string>>({})
const audits = ref<OpsAuditEntry[]>([])

const allowedOps = computed(() => OPS_WHITELIST.filter((op) => auth.hasOp(op.code)))

async function execute(op: OpsAction) {
  const tid = targets[op.code]
  if (!tid && op.target !== 'note') {
    ElMessage.warning('请填写目标 ID')
    return
  }
  if (op.needConfirm) {
    try {
      await ElMessageBox.confirm(`确认执行 [${op.label}]？\n目标：${tid}`, '二次确认', { type: 'warning' })
    } catch { return }
  }
  try {
    const resp = await executeOp({ opCode: op.code, targetId: tid })
    ElMessage.success(`成功，auditId=${resp.auditId}`)
    audits.value = await listAudits()
  } catch (e) {
    ElMessage.error(`失败：${e instanceof Error ? e.message : String(e)}`)
  }
}

onMounted(async () => {
  audits.value = await listAudits()
})
</script>
