<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted, watch } from "vue";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { useSseStoreHook } from "@/store/modules/sse";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  getRiskList,
  getRiskStatistics,
  deleteRisk,
  submitRiskAssessment,
  type RiskVO,
  type RiskStatisticsVO,
  type RiskQueryParams
} from "@/api/risk-workorder";
import { getProjectList, type ProjectItem } from "@/api/project";
import { message } from "@/utils/message";
import dayjs from "dayjs";
import * as echarts from "echarts";

import AddIcon from "~icons/ri/add-line";
import SearchIcon from "~icons/ri/search-line";
import RefreshIcon from "~icons/ri/refresh-line";
import FilterIcon from "~icons/ri/filter-3-line";
import MoreIcon from "~icons/ep/more-filled";
import DeleteIcon from "~icons/ep/delete";
import EditPenIcon from "~icons/ep/edit-pen";
import ViewIcon from "~icons/ri/eye-line";
import WarningIcon from "~icons/ri/alert-line";

defineOptions({
  name: "RiskAssessmentIndex"
});

const router = useRouter();
const loading = ref(false);
const dataList = ref<RiskVO[]>([]);
const statistics = ref<RiskStatisticsVO>({
  totalCount: 0,
  identifiedCount: 0,
  assignedCount: 0,
  mitigatingCount: 0,
  resolvedCount: 0,
  closedCount: 0,
  criticalCount: 0,
  highCount: 0,
  mediumCount: 0,
  lowCount: 0,
  categoryStats: {},
  levelStats: {},
  trendData: {},
  averageRiskScore: 0,
  unresolvedHighCount: 0
});

// 查询参数
const queryParams = ref<RiskQueryParams>({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
  category: "",
  riskLevel: "",
  status: ""
});

// 趋势周期
const trendPeriod = ref("month");

// 项目列表
const projectList = ref<ProjectItem[]>([]);

// SSE Store
const sseStore = useSseStoreHook();
const userStore = useUserStoreHook();

// 风险评估进度相关
const riskAssessProgress = computed(() => sseStore.riskAssessProgress);
const riskAssessStatus = computed(() => sseStore.riskAssessStatus);
const riskAssessTask = computed(() => sseStore.riskAssessTask);
const riskAssessErrorMessage = computed(() => sseStore.riskAssessErrorMessage);
const isAssessing = computed(
  () =>
    riskAssessStatus.value === "submitted" ||
    riskAssessStatus.value === "processing"
);

// 监听风险评估完成
watch(
  () => sseStore.riskAssessStatus,
  newStatus => {
    console.log("风险状态变化:", newStatus);
    if (newStatus === "completed") {
      message("风险评估完成！", { type: "success" });
      loadRiskList();
      loadStatistics();
      // 延迟重置状态，让用户看到完成效果
      setTimeout(() => {
        sseStore.resetRiskAssessStatus();
      }, 2000);
    } else if (newStatus === "error") {
      message(riskAssessErrorMessage.value || "风险评估失败", {
        type: "error"
      });
      sseStore.resetRiskAssessStatus();
    }
  },
  { immediate: false }
);

// 分页
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 图表引用
const pieChartRef = ref<HTMLDivElement>();
const trendChartRef = ref<HTMLDivElement>();
let pieChart: echarts.ECharts | null = null;
let trendChart: echarts.ECharts | null = null;

// 统计卡片数据
const statCards = computed(() => [
  {
    title: "总风险数",
    value: statistics.value.totalCount || 0,
    trend: "↑ 12% 较上月",
    trendUp: true,
    icon: "ri:information-line",
    color: "#409eff",
    bgColor: "#ecf5ff"
  },
  {
    title: "严重风险",
    value: statistics.value.criticalCount || 0,
    trend: "↑ 5% 较上月",
    trendUp: true,
    icon: "ri:alert-line",
    color: "#f56c6c",
    bgColor: "#fef0f0"
  },
  {
    title: "高风险",
    value: statistics.value.highCount || 0,
    trend: "↓ 3% 较上月",
    trendUp: false,
    icon: "ri:error-warning-line",
    color: "#e6a23c",
    bgColor: "#fdf6ec"
  },
  {
    title: "中低风险",
    value:
      (statistics.value.mediumCount || 0) + (statistics.value.lowCount || 0),
    trend: "↓ 2% 较上月",
    trendUp: false,
    icon: "ri:checkbox-circle-line",
    color: "#67c23a",
    bgColor: "#f0f9eb"
  }
]);

// 风险等级选项
const riskLevelOptions = [
  { label: "严重", value: "critical", color: "#f56c6c" },
  { label: "高", value: "high", color: "#e6a23c" },
  { label: "中", value: "medium", color: "#409eff" },
  { label: "低", value: "low", color: "#67c23a" }
];

// 风险分类选项
const categoryOptions = [
  { label: "技术风险", value: "technical" },
  { label: "进度风险", value: "schedule" },
  { label: "成本风险", value: "cost" },
  { label: "质量风险", value: "quality" },
  { label: "资源风险", value: "resource" },
  { label: "外部风险", value: "external" },
  { label: "其他", value: "other" }
];

// 状态选项
const statusOptions = [
  { label: "已识别", value: "identified" },
  { label: "已分派", value: "assigned" },
  { label: "缓解中", value: "mitigating" },
  { label: "已解决", value: "resolved" },
  { label: "已关闭", value: "closed" }
];

// 获取风险等级标签类型
function getRiskLevelType(
  level?: string
): "danger" | "warning" | "info" | "success" {
  switch (level) {
    case "critical":
      return "danger";
    case "high":
      return "warning";
    case "medium":
      return "info";
    case "low":
      return "success";
    default:
      return "info";
  }
}

// 获取风险等级显示文本
function getRiskLevelLabel(level?: string): string {
  const option = riskLevelOptions.find(o => o.value === level);
  return option?.label || level || "未知";
}

// 获取分类显示文本
function getCategoryLabel(category?: string): string {
  const option = categoryOptions.find(o => o.value === category);
  return option?.label || category || "未知";
}

// 获取状态标签类型
function getStatusType(
  status?: string
): "success" | "warning" | "info" | "primary" | "danger" {
  switch (status) {
    case "resolved":
    case "closed":
      return "success";
    case "mitigating":
      return "warning";
    case "assigned":
      return "primary";
    case "identified":
      return "info";
    default:
      return "info";
  }
}

// 获取状态显示文本
function getStatusLabel(status?: string): string {
  const option = statusOptions.find(o => o.value === status);
  return option?.label || status || "未知";
}

// 加载风险列表
async function loadRiskList() {
  loading.value = true;
  try {
    const params: any = {
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      keyword: queryParams.value.keyword,
      category: queryParams.value.category,
      riskLevel: queryParams.value.riskLevel,
      status: queryParams.value.status
    };
    // projectId 转换为字符串避免精度丢失
    if (queryParams.value.projectId) {
      params.projectId = String(queryParams.value.projectId);
    }
    const res = await getRiskList(params);
    const businessData = res.data as any;
    if (businessData.code === 200) {
      const rows = businessData.rows || [];
      dataList.value = rows;
      pagination.value.total = parseInt(businessData.total) || rows.length || 0;
    }
  } catch (error) {
    message("加载风险列表失败", { type: "error" });
  } finally {
    loading.value = false;
  }
}

async function loadProjectList() {
  try {
    const res = await getProjectList({ pageNum: 1, pageSize: 100 });
    const businessData = res.data as any;
    if (businessData.code === 200) {
      projectList.value = businessData.rows || [];
    }
  } catch (error) {
    console.error("加载项目列表失败", error);
  }
}

async function loadStatistics() {
  try {
    const res = await getRiskStatistics();
    const data = res.data as any;

    statistics.value = {
      totalCount: parseInt(data.totalCount) || 0,
      identifiedCount: parseInt(data.identifiedCount) || 0,
      assignedCount: parseInt(data.assignedCount) || 0,
      mitigatingCount: parseInt(data.mitigatingCount) || 0,
      resolvedCount: parseInt(data.resolvedCount) || 0,
      closedCount: parseInt(data.closedCount) || 0,
      criticalCount: parseInt(data.criticalCount) || 0,
      highCount: parseInt(data.highCount) || 0,
      mediumCount: parseInt(data.mediumCount) || 0,
      lowCount: parseInt(data.lowCount) || 0,
      categoryStats: data.categoryStats || {},
      levelStats: data.levelStats || {},
      trendData: data.trendData || {},
      averageRiskScore: parseFloat(data.averageRiskScore) || 0,
      unresolvedHighCount: parseInt(data.unresolvedHighCount) || 0
    };
    setTimeout(() => {
      updateCharts();
    }, 100);
  } catch (error) {
    console.error("加载统计数据失败", error);
  }
}

// 更新饼图 - 使用 categoryStats 分类统计数据
function updatePieChart() {
  if (!pieChartRef.value) return;
  if (!pieChart) {
    pieChart = echarts.init(pieChartRef.value);
  }

  const categoryStats = statistics.value.categoryStats || {};
  const categoryColors: Record<string, string> = {
    schedule: "#409eff", // 进度 - 蓝色
    external: "#e6a23c", // 外部 - 橙色
    technical: "#67c23a", // 技术 - 绿色
    resource: "#909399", // 资源 - 灰色
    personnel: "#f56c6c", // 人员 - 红色
    quality: "#9c27b0", // 质量 - 紫色
    cost: "#ff9800", // 成本 - 深橙
    other: "#795548" // 其他 - 棕色
  };
  const categoryNames: Record<string, string> = {
    schedule: "进度风险",
    external: "外部风险",
    technical: "技术风险",
    resource: "资源风险",
    personnel: "人员风险",
    quality: "质量风险",
    cost: "成本风险",
    other: "其他风险"
  };

  // 构建饼图数据 - 处理字符串类型的值
  const data = Object.entries(categoryStats)
    .map(([key, value]) => {
      const numValue =
        typeof value === "string" ? parseInt(value) : (value as number) || 0;
      return {
        value: numValue,
        name: categoryNames[key] || key,
        itemStyle: { color: categoryColors[key] || "#909399" }
      };
    })
    .filter(item => item.value > 0)
    .sort((a, b) => b.value - a.value);

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)"
    },
    legend: {
      bottom: "5%",
      left: "center",
      itemWidth: 10,
      itemHeight: 10,
      textStyle: { fontSize: 12 }
    },
    series: [
      {
        name: "风险分类分布",
        type: "pie",
        radius: ["50%", "70%"],
        center: ["50%", "45%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 6,
          borderColor: "#fff",
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data:
          data.length > 0
            ? data
            : [{ value: 1, name: "暂无数据", itemStyle: { color: "#e0e0e0" } }]
      }
    ]
  };
  pieChart.setOption(option);
}

function initTrendChart() {
  if (!trendChartRef.value) return;
  trendChart = echarts.init(trendChartRef.value);
  updateTrendChart();
}

function updateTrendChart() {
  if (!trendChartRef.value) return;
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value);
  }

  const levelStats = statistics.value.levelStats || {};
  const levelData = [
    {
      name: "严重",
      value:
        typeof levelStats.critical === "string"
          ? parseInt(levelStats.critical)
          : (levelStats.critical as number) || 0,
      color: "#f56c6c"
    },
    {
      name: "高",
      value:
        typeof levelStats.high === "string"
          ? parseInt(levelStats.high)
          : (levelStats.high as number) || 0,
      color: "#e6a23c"
    },
    {
      name: "中",
      value:
        typeof levelStats.medium === "string"
          ? parseInt(levelStats.medium)
          : (levelStats.medium as number) || 0,
      color: "#409eff"
    },
    {
      name: "低",
      value:
        typeof levelStats.low === "string"
          ? parseInt(levelStats.low)
          : (levelStats.low as number) || 0,
      color: "#67c23a"
    }
  ].filter(item => item.value > 0);

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" },
      formatter: (params: any) => {
        const data = params[0];
        return `${data.name}: ${data.value} 个`;
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "10%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: levelData.map(item => item.name),
      axisLine: { lineStyle: { color: "#dcdfe6" } },
      axisLabel: { color: "#606266", fontSize: 12 },
      axisTick: { show: false }
    },
    yAxis: {
      type: "value",
      axisLine: { show: false },
      splitLine: { lineStyle: { color: "#ebeef5" } },
      axisLabel: { color: "#606266" }
    },
    series: [
      {
        name: "风险数量",
        type: "bar",
        data: levelData.map((item, index) => ({
          value: item.value,
          itemStyle: {
            color: item.color,
            borderRadius: [4, 4, 0, 0]
          }
        })),
        barWidth: "50%",
        label: {
          show: true,
          position: "top",
          color: "#606266",
          fontSize: 12,
          formatter: "{c}"
        }
      }
    ]
  };
  trendChart.setOption(option);
}

function updateCharts() {
  updatePieChart();
  updateTrendChart();
}

// 搜索
function onSearch() {
  pagination.value.currentPage = 1;
  loadRiskList();
}

// 重置
function resetForm() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    category: "",
    riskLevel: "",
    status: ""
  };
  onSearch();
}

// 分页大小变化
function handleSizeChange(val: number) {
  pagination.value.pageSize = val;
  loadRiskList();
}

// 页码变化
function handleCurrentChange(val: number) {
  pagination.value.currentPage = val;
  loadRiskList();
}

// 新建风险评估 - 使用SSE异步评估
async function handleCreate() {
  if (!queryParams.value.projectId) {
    message("请先选择项目", { type: "warning" });
    return;
  }

  const userId = userStore.userId;
  if (!userId) {
    message("用户信息不存在", { type: "error" });
    return;
  }

  // 确保SSE连接已建立
  if (!sseStore.getIsConnected) {
    sseStore.initSse(String(userId));
  }

  try {
    const res = await submitRiskAssessment(String(queryParams.value.projectId));
    const responseData = res.data as any;
    if (responseData.code === 200) {
      message("风险评估任务已提交，AI 正在分析中...", { type: "success" });
    } else {
      message(responseData.message || "提交失败", { type: "error" });
    }
  } catch (error) {
    console.error("风险评估请求异常", error);
    message("提交风险评估任务失败", { type: "error" });
  }
}

// 查看风险详情
function handleView(row: RiskVO) {
  message(`查看风险: ${row.riskName}`, { type: "info" });
}

// 编辑风险
function handleEdit(row: RiskVO) {
  message(`编辑风险: ${row.riskName}`, { type: "info" });
}

// 删除风险
async function handleDelete(row: RiskVO) {
  if (!row.id) return;
  try {
    await deleteRisk(row.id);
    message("删除成功", { type: "success" });
    loadRiskList();
    loadStatistics();
  } catch (error) {
    message("删除失败", { type: "error" });
  }
}

// 分配工单
function handleAssignWorkOrder(row: RiskVO) {
  message(`为风险分配工单: ${row.riskName}`, { type: "info" });
}

// 标记已完成
function handleComplete(row: RiskVO) {
  message(`标记风险已完成: ${row.riskName}`, { type: "success" });
}

// 窗口大小变化时重新渲染图表
function handleResize() {
  pieChart?.resize();
  trendChart?.resize();
}

onMounted(() => {
  loadProjectList();
  loadRiskList();
  loadStatistics();
  // 初始化的图表会在数据加载后通过 updateCharts 自动渲染
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});
</script>

<template>
  <div class="risk-assessment w-full">
    <!-- 页面标题 -->
    <div class="flex-bc mb-4">
      <div>
        <h2 class="text-xl font-bold">风险评估</h2>
        <p class="text-gray-500 text-sm mt-1">
          根据项目资产资料进行风险评估，推送告警给相关人员
        </p>
      </div>
      <div class="flex gap-2">
        <el-select
          v-model="queryParams.projectId"
          placeholder="选择项目"
          clearable
          style="width: 200px"
          @change="onSearch"
        >
          <el-option
            v-for="project in projectList"
            :key="project.id"
            :label="project.projectName"
            :value="project.id"
          />
        </el-select>
        <el-select placeholder="最近30天" style="width: 120px">
          <el-option label="最近7天" value="7" />
          <el-option label="最近30天" value="30" />
          <el-option label="最近90天" value="90" />
        </el-select>
        <el-button>
          <template #icon>
            <component :is="useRenderIcon(FilterIcon)" />
          </template>
          筛选
        </el-button>
        <el-button type="primary" :loading="isAssessing" @click="handleCreate">
          <template #icon>
            <component :is="useRenderIcon(AddIcon)" />
          </template>
          {{ isAssessing ? "评估中..." : "新建评估" }}
        </el-button>
      </div>
    </div>

    <!-- AI风险评估进度显示 -->
    <el-card v-if="isAssessing" class="mb-4" shadow="hover">
      <div class="flex-c gap-4">
        <el-icon class="is-loading text-primary" :size="24">
          <component :is="useRenderIcon('ri:loader-4-line')" />
        </el-icon>
        <div class="flex-1">
          <div class="flex-bc mb-2">
            <span class="font-medium">AI 正在进行风险评估</span>
            <span class="text-sm text-gray-500">{{ riskAssessProgress }}%</span>
          </div>
          <el-progress
            :percentage="riskAssessProgress"
            :stroke-width="8"
            :show-text="false"
          />
          <p class="text-sm text-gray-500 mt-2">
            {{ riskAssessTask?.progressMessage || "正在分析项目数据..." }}
          </p>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col
        v-for="(card, index) in statCards"
        :key="index"
        :xs="24"
        :sm="12"
        :md="6"
      >
        <el-card shadow="hover" class="stat-card">
          <div class="flex-bc">
            <div>
              <p class="text-gray-500 text-sm">{{ card.title }}</p>
              <p class="text-2xl font-bold mt-1" :style="{ color: card.color }">
                {{ card.value }}
              </p>
              <p
                class="text-xs mt-1"
                :class="card.trendUp ? 'text-red-500' : 'text-green-500'"
              >
                {{ card.trend }}
              </p>
            </div>
            <div class="stat-icon" :style="{ backgroundColor: card.bgColor }">
              <el-icon :size="24" :color="card.color">
                <component :is="useRenderIcon(card.icon)" />
              </el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="flex-bc">
              <span class="font-medium">风险分类分布</span>
              <el-button link>
                <component :is="useRenderIcon(MoreIcon)" />
              </el-button>
            </div>
          </template>
          <div ref="pieChartRef" class="chart-container" />
          <div class="risk-legend">
            <div class="legend-item">
              <span class="legend-dot" style="background-color: #409eff" />
              <span>进度</span>
              <span class="legend-value">{{
                statistics.categoryStats?.schedule || 0
              }}</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot" style="background-color: #e6a23c" />
              <span>外部</span>
              <span class="legend-value">{{
                statistics.categoryStats?.external || 0
              }}</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot" style="background-color: #67c23a" />
              <span>技术</span>
              <span class="legend-value">{{
                statistics.categoryStats?.technical || 0
              }}</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot" style="background-color: #909399" />
              <span>资源</span>
              <span class="legend-value">{{
                statistics.categoryStats?.resource || 0
              }}</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot" style="background-color: #f56c6c" />
              <span>人员</span>
              <span class="legend-value">{{
                statistics.categoryStats?.personnel || 0
              }}</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot" style="background-color: #9c27b0" />
              <span>质量</span>
              <span class="legend-value">{{
                statistics.categoryStats?.quality || 0
              }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="flex-bc">
              <span class="font-medium">风险状态分布</span>
              <div class="flex gap-2">
                <el-radio-group v-model="trendPeriod" size="small">
                  <el-radio-button label="月度" value="month" />
                  <el-radio-button label="季度" value="quarter" />
                  <el-radio-button label="年度" value="year" />
                </el-radio-group>
              </div>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 风险告警列表 -->
    <el-card shadow="hover">
      <template #header>
        <div class="flex-bc">
          <span class="font-medium">风险告警列表</span>
          <div class="flex gap-2">
            <el-input
              v-model="queryParams.keyword"
              placeholder="搜索风险..."
              clearable
              style="width: 200px"
              @keyup.enter="onSearch"
            >
              <template #prefix>
                <component :is="useRenderIcon(SearchIcon)" />
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="dataList" style="width: 100%">
        <el-table-column label="风险名称" min-width="200">
          <template #default="{ row }">
            <div class="flex items-center gap-2">
              <el-icon :size="20" color="#f56c6c">
                <component :is="useRenderIcon(WarningIcon)" />
              </el-icon>
              <div>
                <div class="font-medium">{{ row.riskName }}</div>
                <div class="text-xs text-gray-400">{{ row.description }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="项目" min-width="150">
          <template #default="{ row }">
            {{ row.projectName || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="风险等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getRiskLevelType(row.riskLevel)" size="small">
              {{ getRiskLevelLabel(row.riskLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发现时间" width="120">
          <template #default="{ row }">
            {{
              row.discoverTime
                ? dayjs(row.discoverTime).format("YYYY-MM-DD")
                : "-"
            }}
          </template>
        </el-table-column>
        <el-table-column label="负责人" width="120">
          <template #default="{ row }">
            <div class="flex items-center gap-2">
              <el-avatar :size="24" :src="row.ownerAvatar">
                {{ row.ownerName?.charAt(0) || "?" }}
              </el-avatar>
              <span>{{ row.ownerName || "未分配" }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
              effect="light"
            >
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              title="查看详情"
              @click="handleView(row)"
            >
              <component :is="useRenderIcon('ri:eye-line')" />
            </el-button>
            <el-button
              link
              type="primary"
              title="分配工单"
              @click="handleAssignWorkOrder(row)"
            >
              <component :is="useRenderIcon('ri:ticket-line')" />
            </el-button>
            <el-button
              link
              type="success"
              title="已完成"
              @click="handleComplete(row)"
            >
              <component :is="useRenderIcon('ri:check-double-line')" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.risk-assessment {
  padding: 16px 80px 16px 16px;

  .stat-card {
    .stat-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48px;
      height: 48px;
      border-radius: 8px;
    }
  }

  .chart-card {
    .chart-container {
      height: 280px;
    }
  }

  .risk-legend {
    display: flex;
    justify-content: space-around;
    padding-top: 16px;
    margin-top: 16px;
    border-top: 1px solid var(--el-border-color-lighter);

    .legend-item {
      display: flex;
      gap: 8px;
      align-items: center;
      font-size: 14px;
      color: var(--el-text-color-regular);

      .legend-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
      }

      .legend-value {
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }
  }
}
</style>
