<template>
  <div class="api-asset-page">
    <el-page-header title="API资产扫描" content="自动发现API接口并检测敏感字段暴露" />

    <el-row class="mt-4 mb-4">
      <el-col :span="6">
        <el-button type="primary" @click="openCreate">新增API资产</el-button>
      </el-col>
    </el-row>

    <el-table :data="assets" v-loading="loading" border>
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="base_url" label="Base URL" />
      <el-table-column prop="scan_status" label="扫描状态" width="100">
        <template #default="scope">
          <el-tag :type="statusType(scope.row.scan_status)" size="small">{{ scope.row.scan_status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="total_endpoints" label="接口数" width="80" />
      <el-table-column prop="sensitive_endpoints" label="敏感接口" width="90" />
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" @click="scanAsset(scope.row)">扫描</el-button>
          <el-button size="small" type="primary" @click="viewEndpoints(scope.row)">接口</el-button>
          <el-button size="small" type="danger" @click="deleteAsset(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="page.page" :page-size="page.page_size" :total="page.total" layout="prev, pager, next" @current-change="fetchAssets" class="mt-4" />

    <el-dialog v-model="createVisible" title="新增API资产" width="600px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="Base URL">
          <el-input v-model="form.base_url" />
        </el-form-item>
        <el-form-item label="Swagger URL">
          <el-input v-model="form.swagger_url" />
        </el-form-item>
        <el-form-item label="认证类型">
          <el-select v-model="form.auth_type">
            <el-option label="无" value="none" />
            <el-option label="Bearer" value="bearer" />
            <el-option label="API Key" value="api_key" />
            <el-option label="Basic" value="basic" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">创建</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="endpointVisible" title="接口详情" width="900px">
      <el-row class="mb-4">
        <el-col :span="6">
          <el-select v-model="epFilter.risk_level" placeholder="风险等级" clearable @change="fetchEndpoints">
            <el-option label="低危" value="low" />
            <el-option label="中危" value="medium" />
            <el-option label="高危" value="high" />
            <el-option label="严重" value="critical" />
          </el-select>
        </el-col>
      </el-row>
      <el-table :data="endpoints" v-loading="loadingEp" border>
        <el-table-column prop="method" label="方法" width="80">
          <template #default="scope">
            <el-tag :type="methodType(scope.row.method)" size="small">{{ scope.row.method }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" />
        <el-table-column prop="summary" label="描述" />
        <el-table-column prop="risk_level" label="风险等级" width="100">
          <template #default="scope">
            <el-tag :type="riskType(scope.row.risk_level)" size="small">{{ scope.row.risk_level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sensitive_fields" label="敏感字段">
          <template #default="scope">
            <el-tag v-for="f in scope.row.sensitive_fields" :key="f.name" size="small" class="mr-1">{{ f.name }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="epPage.page" :page-size="epPage.page_size" :total="epPage.total" layout="prev, pager, next" @current-change="fetchEndpoints" class="mt-4" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/api/request';

const assets = ref([]);
const loading = ref(false);
const page = reactive({ page: 1, page_size: 20, total: 0 });

const createVisible = ref(false);
const form = reactive({ name: '', base_url: '', swagger_url: '', auth_type: 'none', description: '' });

const endpointVisible = ref(false);
const endpoints = ref([]);
const loadingEp = ref(false);
const epPage = reactive({ page: 1, page_size: 20, total: 0 });
const epFilter = reactive({ risk_level: '' });
const currentAssetId = ref<number | null>(null);

const statusType = (s: string) => {
  if (s === 'completed') return 'success';
  if (s === 'scanning') return 'warning';
  if (s === 'failed') return 'danger';
  return 'info';
};
const methodType = (m: string) => {
  const map: Record<string, string> = { GET: 'success', POST: 'primary', PUT: 'warning', DELETE: 'danger', PATCH: '' };
  return map[m] || 'info';
};
const riskType = (r: string) => {
  if (r === 'critical') return 'danger';
  if (r === 'high') return 'warning';
  if (r === 'medium') return '';
  return 'info';
};

const fetchAssets = async () => {
  loading.value = true;
  const res: any = await request.get('/api-assets', { params: { page: page.page, page_size: page.page_size } });
  assets.value = res.data || [];
  page.total = res.total || 0;
  loading.value = false;
};
const openCreate = () => {
  Object.assign(form, { name: '', base_url: '', swagger_url: '', auth_type: 'none', description: '' });
  createVisible.value = true;
};
const submitCreate = async () => {
  await request.post('/api-assets', form);
  ElMessage.success('创建成功');
  createVisible.value = false;
  fetchAssets();
};
const scanAsset = async (row: any) => {
  await request.post(`/api-assets/${row.id}/scan`);
  ElMessage.success('扫描已提交');
  fetchAssets();
};
const deleteAsset = async (row: any) => {
  await ElMessageBox.confirm('确认删除该资产？', '提示', { type: 'warning' });
  await request.delete(`/api-assets/${row.id}`);
  ElMessage.success('删除成功');
  fetchAssets();
};
const viewEndpoints = (row: any) => {
  currentAssetId.value = row.id;
  epPage.page = 1;
  epFilter.risk_level = '';
  endpointVisible.value = true;
  fetchEndpoints();
};
const fetchEndpoints = async () => {
  if (!currentAssetId.value) return;
  loadingEp.value = true;
  const res: any = await request.get(`/api-assets/${currentAssetId.value}/endpoints`, {
    params: { risk_level: epFilter.risk_level, page: epPage.page, page_size: epPage.page_size },
  });
  endpoints.value = res.data || [];
  epPage.total = res.total || 0;
  loadingEp.value = false;
};

onMounted(fetchAssets);
</script>
