<template>
  <div class="page-container">
    <h2 class="page-title">合规检查</h2>
    <div class="action-bar card-shadow" style="padding: 16px; margin-bottom: 16px; display: flex; gap: 12px; align-items: center;">
      <el-select v-model="scanProjectId" placeholder="选择项目（可选）" clearable style="width: 200px">
        <el-option v-for="p in projects" :key="p.id" :label="p.name" :value="p.id" />
      </el-select>
      <el-button type="primary" :loading="scanLoading" @click="handleScan">执行扫描</el-button>
      <el-button type="info" @click="handleInit">初始化规则库</el-button>
    </div>
    <div class="table-card card-shadow">
      <el-table :data="issueList" v-loading="listLoading" stripe size="default" border>
        <el-table-column prop="severity" label="严重级别" width="100">
          <template #default="{ row }">
            <el-tag :type="severityColor(row.severity)" size="small">{{ row.severity }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="entity_name" label="对象" min-width="120" />
        <el-table-column prop="description" label="问题描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="suggestion" label="修复建议" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === 'resolved' ? 'success' : 'danger'" size="small">{{ row.status === 'resolved' ? '已解决' : '待处理' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status !== 'resolved'" type="primary" link size="small" @click="handleResolve(row)">标记解决</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: flex-end; margin-top: 16px;">
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :total="total" layout="total, prev, pager, next" @change="fetchIssues" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { scanCompliance, getComplianceIssues, resolveIssue, initComplianceRules } from '@/api/compliance'
import { getProjects } from '@/api/project'

const scanLoading = ref(false)
const listLoading = ref(false)
const issueList = ref<any[]>([])
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const scanProjectId = ref<number | undefined>(undefined)
const projects = ref<any[]>([])

function severityColor(v: string) {
  const map: Record<string, string> = { critical: 'danger', high: 'warning', medium: '', low: 'info' }
  return map[v] || ''
}

async function fetchIssues() {
  listLoading.value = true
  try {
    const res: any = await getComplianceIssues({ page: page.value, page_size: pageSize.value })
    issueList.value = res.data || []
    total.value = res.total || 0
  } catch (e: any) { ElMessage.error(e?.message || '加载失败') }
  finally { listLoading.value = false }
}

async function handleScan() {
  scanLoading.value = true
  try {
    const res: any = await scanCompliance(scanProjectId.value)
    ElMessage.success('扫描完成，发现 ' + (res.data?.issues_found || 0) + ' 个问题')
    fetchIssues()
  } catch (e: any) { ElMessage.error(e?.message || '扫描失败') }
  finally { scanLoading.value = false }
}

async function handleInit() {
  try {
    await initComplianceRules()
    ElMessage.success('规则库初始化完成')
  } catch (e: any) { ElMessage.error(e?.message || '初始化失败') }
}

async function handleResolve(row: any) {
  try {
    await resolveIssue(row.id)
    ElMessage.success('已标记为已解决')
    fetchIssues()
  } catch (e: any) { ElMessage.error(e?.message || '操作失败') }
}

async function fetchProjects() {
  try {
    const res: any = await getProjects({ page: 1, page_size: 100 })
    projects.value = res.data || []
  } catch (e) { }
}

onMounted(() => { fetchProjects(); fetchIssues() })
</script>
