<template>
  <div class="risk-warning-tab card">
    <!-- 风险总览卡片 -->
    <div class="risk-overview-card mb-6">
      <div class="rounded-xl border border-red-200 p-4 shadow-sm">
        <div class="flex items-center justify-between mb-3">
          <div class="flex items-center">
            <div class="w-12 h-12">
              <img src="@/assets/images/report/fxzl.png" alt="风险总览" class="w-8 h-8 object-contain" />
            </div>
            <div>
              <h2 class="text-lg font-bold text-gray-800">风险总览</h2>
              <p class="text-xs text-[#999999]">系统检测到的所有风险点汇总</p>
            </div>
          </div>
        </div>

        <!-- 风险统计 -->
        <div class="bg-[#FFF0F0] border border-red-200 rounded-lg p-4">
          <div class="grid grid-cols-3 gap-4">
            <div class="text-center">
              <div class="text-sm text-[#666666] mb-1">总风险点</div>
              <div class="text-lg font-bold text-[#E53935]">{{ riskWarning.value?.totalRiskCounts || 0 }}条</div>
            </div>

            <div class="text-center">
              <div class="text-sm text-[#666666] mb-1">高风险</div>
              <div class="text-lg font-bold text-[#E53935]">{{ getHighRiskCount() }}条</div>
            </div>

            <div class="text-center">
              <div class="text-sm text-[#666666] mb-1">中风险</div>
              <div class="text-lg font-bold text-[#FFC107]">{{ getMiddleRiskCount() }}条</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 风险模块列表 -->
    <div class="risk-modules">

      <div class="space-y-4">
        <!-- 要素核查 -->
        <div class="risk-module-card relative" :class="getModuleCardClass('element')">
          <div v-if="getElementVerificationRisks().length > 0"
            :class="['absolute top-0 right-0 px-2 py-1 text-xs text-white rounded-bl-xl rounded-tr-xl', getRiskBadgeBgColor(getModuleHighestRiskLevel('element'))]">
            {{ getElementVerificationRisks().length }}条风险
          </div>
          <div class="flex items-center mb-3">
            <div class="w-12 h-12">
              <img src="@/assets/images/report/yshc.png" alt="要素核查" class="w-8 h-8 object-contain" />
            </div>
            <div class="flex-1">
              <h4 class="font-bold text-lg text-[#333333]">要素核查</h4>
              <p class="text-sm text-[#999999]">身份证、手机号等基础信息验证</p>
            </div>
          </div>

          <div v-if="getElementVerificationRisks().length > 0"
            class="bg-[#FFF0F0] border border-red-200 rounded-lg p-4 relative">
            <div
              :class="['absolute top-0 right-0 px-1.5 py-0.5 text-xs text-white rounded-bl-lg rounded-tr-lg', getRiskBadgeColor(getElementVerificationRisks()[0])]">
              {{ getElementVerificationRisks()[0]?.level || '高风险' }}
            </div>
            <div class="flex items-center">
              <div class="w-8 h-8 mr-3 flex-shrink-0">
                <img :src="getRiskIcon(getElementVerificationRisks()[0])"
                  :alt="getElementVerificationRisks()[0]?.level || '高风险'" class="w-8 h-8 object-contain" />
              </div>
              <div class="flex-1 pr-12">
                <div class="font-bold text-[#333333] text-sm">{{ getElementVerificationRisks()[0]?.description ||
                  '检测到风险' }}
                </div>
                <div class="text-xs text-[#999999] mt-0.5">{{ getElementVerificationRisks()[0]?.detail || '该模块检测到风险' }}
                </div>
              </div>
            </div>
          </div>

          <div v-else class="bg-[#F0FFF0] border border-green-200 rounded-lg p-4">
            <div class="flex items-center">
              <div class="w-10 h-10 mr-4">
                <img src="@/assets/images/report/zq.png" alt="暂无风险" class="w-10 h-10 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-[#333333]">暂无风险</div>
                <div class="text-sm text-[#999999]">该模块未检测到风险</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 运营商核验 -->
        <div class="risk-module-card relative" :class="getModuleCardClass('operator')">
          <div v-if="getOperatorVerificationRisks().length > 0"
            :class="['absolute top-0 right-0 px-2 py-1 text-xs text-white rounded-bl-xl rounded-tr-xl', getRiskBadgeBgColor(getModuleHighestRiskLevel('operator'))]">
            {{ getOperatorVerificationRisks().length }}条风险
          </div>
          <div class="flex items-center mb-3">
            <div class="w-12 h-12">
              <img src="@/assets/images/report/yyshy.png" alt="运营商核验" class="w-8 h-8 object-contain" />
            </div>
            <div class="flex-1">
              <h4 class="font-bold text-lg text-[#333333]">运营商核验</h4>
              <p class="text-sm text-[#999999]">手机号状态、在网时长等运营商信息</p>
            </div>
          </div>

          <div v-if="getOperatorVerificationRisks().length > 0"
            class="bg-[#FFF0F0] border border-red-200 rounded-lg p-4 relative">
            <div
              :class="['absolute top-0 right-0 px-1.5 py-0.5 text-xs text-white rounded-bl-lg rounded-tr-lg', getRiskBadgeColor(getOperatorVerificationRisks()[0])]">
              {{ getOperatorVerificationRisks()[0]?.level || '高风险' }}
            </div>
            <div class="flex items-center">
              <div class="w-8 h-8 mr-3 flex-shrink-0">
                <img :src="getRiskIcon(getOperatorVerificationRisks()[0])"
                  :alt="getOperatorVerificationRisks()[0]?.level || '高风险'" class="w-8 h-8 object-contain" />
              </div>
              <div class="flex-1 pr-12">
                <div class="font-bold text-[#333333] text-sm">{{ getOperatorVerificationRisks()[0]?.description ||
                  '手机在网状态为风险号'
                }}</div>
                <div class="text-xs text-[#999999] mt-0.5">{{ getOperatorVerificationRisks()[0]?.detail ||
                  '手机号状态异常,存在风险' }}
                </div>
              </div>
            </div>
          </div>

          <div v-else class="bg-[#F0FFF0] border border-green-200 rounded-lg p-4">
            <div class="flex items-center">
              <div class="w-10 h-10 mr-4">
                <img src="@/assets/images/report/zq.png" alt="暂无风险" class="w-10 h-10 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-[#333333]">暂无风险</div>
                <div class="text-sm text-[#999999]">该模块未检测到风险</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 公安重点人员核验 -->
        <div class="risk-module-card relative" :class="getModuleCardClass('police')">
          <div v-if="getPoliceVerificationRisks().length > 0"
            :class="['absolute top-0 right-0 px-2 py-1 text-xs text-white rounded-bl-xl rounded-tr-xl', getRiskBadgeBgColor(getModuleHighestRiskLevel('police'))]">
            {{ getPoliceVerificationRisks().length }}条风险
          </div>
          <div class="flex items-center mb-3">
            <div class="w-10 h-10">
              <img src="@/assets/images/report/gazdryhy.png" alt="公安重点人员核验" class="w-8 h-8 object-contain" />
            </div>
            <div class="flex-1">
              <h4 class="font-bold text-lg text-[#333333]">公安重点人员核验</h4>
              <p class="text-sm text-[#999999]">前科记录、重点人员、涉赌涉诈等</p>
            </div>
          </div>

          <!-- 风险等级显示 -->
          <div v-if="riskWarning.value?.level" class="mb-3">
            <div class="bg-gray-50 rounded-lg p-3 border border-gray-200">
              <div class="flex items-center mb-2">
                <div class="w-10 h-10 flex items-center justify-center mr-3">
                  <img src="@/assets/images/report/zfx.png" alt="风险等级" class="w-10 h-10 object-contain" />
                </div>
                <span class="font-bold text-lg text-gray-800">风险等级</span>
              </div>
              <div class="space-y-2">
                <div v-for="level in getRiskLevels()" :key="level"
                  class="flex flex-col gap-1 p-3 bg-white rounded-lg border border-gray-200">
                  <div class="flex items-center gap-2">
                    <span :class="['px-2 py-1 rounded text-xs font-bold', getRiskLevelTagClass(level)]">{{ level
                    }}</span>
                    <span class="text-sm font-medium text-[#333333]">{{ getRiskLevelText(level) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 具体风险列表 -->
          <div v-if="getPoliceVerificationRisks().length > 0" class="space-y-2">
            <div v-for="risk in getPoliceVerificationRisks()" :key="risk.key"
              class="bg-[#FFF0F0] border border-red-200 rounded-lg p-4 relative">
              <div
                :class="['absolute top-0 right-0 px-1.5 py-0.5 text-xs text-white rounded-bl-lg rounded-tr-lg', getRiskBadgeColor(risk)]">
                {{ risk.level }}
              </div>
              <div class="flex items-center">
                <div class="w-8 h-8 mr-3 flex-shrink-0">
                  <img :src="getRiskIcon(risk)" :alt="risk.level" class="w-8 h-8 object-contain" />
                </div>
                <div class="flex-1 pr-12">
                  <div class="font-bold text-[#333333] text-sm">{{ risk.description }}</div>
                  <div class="text-xs text-[#999999] mt-0.5">{{ risk.detail }}</div>
                </div>
              </div>
            </div>
          </div>

          <div v-else class="bg-[#F0FFF0] border border-green-200 rounded-lg p-4">
            <div class="flex items-center">
              <div class="w-10 h-10 mr-4">
                <img src="@/assets/images/report/zq.png" alt="暂无风险" class="w-10 h-10 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-[#333333]">暂无风险</div>
                <div class="text-sm text-[#999999]">该模块未检测到风险</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 逾期风险 -->
        <div class="risk-module-card relative" :class="getModuleCardClass('overdue')">
          <div v-if="getOverdueRiskRisks().length > 0"
            :class="['absolute top-0 right-0 px-2 py-1 text-xs text-white rounded-bl-xl rounded-tr-xl', getRiskBadgeBgColor(getModuleHighestRiskLevel('overdue'))]">
            {{ getOverdueRiskRisks().length }}条风险
          </div>
          <div class="flex items-center mb-3">
            <div class="w-10 h-10">
              <img src="@/assets/images/report/yqfx.png" alt="逾期风险" class="w-8 h-8 object-contain" />
            </div>
            <div class="flex-1">
              <h4 class="font-bold text-lg text-[#333333]">逾期风险</h4>
              <p class="text-sm text-[#999999]">银行、非银机构逾期记录</p>
            </div>
          </div>

          <div v-if="getOverdueRiskRisks().length > 0" class="space-y-2">
            <div v-for="risk in getOverdueRiskRisks()" :key="risk.key"
              class="bg-[#FFF0F0] border border-red-200 rounded-lg p-4 relative">
              <div
                :class="['absolute top-0 right-0 px-1.5 py-0.5 text-xs text-white rounded-bl-lg rounded-tr-lg', getRiskBadgeColor(risk)]">
                {{ risk.level }}
              </div>
              <div class="flex items-center">
                <div class="w-8 h-8 mr-3 flex-shrink-0">
                  <img :src="getRiskIcon(risk)" :alt="risk.level" class="w-8 h-8 object-contain" />
                </div>
                <div class="flex-1 pr-12">
                  <div class="font-bold text-[#333333] text-sm">{{ risk.description }}</div>
                  <div class="text-xs text-[#999999] mt-0.5">{{ risk.detail }}</div>
                </div>
              </div>
            </div>
          </div>

          <div v-else class="bg-[#F0FFF0] border border-green-200 rounded-lg p-4">
            <div class="flex items-center">
              <div class="w-10 h-10 mr-4">
                <img src="@/assets/images/report/zq.png" alt="暂无风险" class="w-10 h-10 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-[#333333]">暂无风险</div>
                <div class="text-sm text-[#999999]">该模块未检测到风险</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 法院曝光台信息 -->
        <div class="risk-module-card relative" :class="getModuleCardClass('court')">
          <div v-if="getCourtRiskRisks().length > 0"
            :class="['absolute top-0 right-0 px-2 py-1 text-xs text-white rounded-bl-xl rounded-tr-xl', getRiskBadgeBgColor(getModuleHighestRiskLevel('court'))]">
            {{ getCourtRiskRisks().length }}条风险
          </div>
          <div class="flex items-center mb-3">
            <div class="w-12 h-12">
              <img :src="courtIconPath" alt="法院曝光台信息" class="w-8 h-8 object-contain" />
            </div>
            <div class="flex-1">
              <h4 class="font-bold text-lg text-[#333333]">法院曝光台信息</h4>
              <p class="text-sm text-[#999999]">民事、刑事、行政案件等司法记录</p>
            </div>
          </div>

          <div v-if="getCourtRiskRisks().length > 0" class="space-y-2">
            <div v-for="risk in getCourtRiskRisks()" :key="risk.key"
              class="bg-[#FFF0F0] border border-red-200 rounded-lg p-4 relative">
              <div
                :class="['absolute top-0 right-0 px-1.5 py-0.5 text-xs text-white rounded-bl-lg rounded-tr-lg', getRiskBadgeColor(risk)]">
                {{ risk.level }}
              </div>
              <div class="flex items-center">
                <div class="w-8 h-8 mr-3 flex-shrink-0">
                  <img :src="getRiskIcon(risk)" :alt="risk.level" class="w-8 h-8 object-contain" />
                </div>
                <div class="flex-1 pr-12">
                  <div class="font-bold text-[#333333] text-sm">{{ risk.description }}</div>
                  <div class="text-xs text-[#999999] mt-0.5">{{ risk.detail }}</div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="bg-[#F0FFF0] border border-green-200 rounded-lg p-4">
            <div class="flex items-center">
              <div class="w-10 h-10 mr-4">
                <img :src="safeIconPath" alt="暂无风险" class="w-10 h-10 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-[#333333]">暂无风险</div>
                <div class="text-sm text-[#999999]">该模块未检测到风险</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 借贷评估 -->
        <div class="risk-module-card relative" :class="getModuleCardClass('loan')">
          <div v-if="getLoanEvaluationRisks().length > 0"
            :class="['absolute top-0 right-0 px-2 py-1 text-xs text-white rounded-bl-xl rounded-tr-xl', getRiskBadgeBgColor(getModuleHighestRiskLevel('loan'))]">
            {{ getLoanEvaluationRisks().length }}条风险
          </div>
          <div class="flex items-center mb-3">
            <div class="w-10 h-10">
              <img src="@/assets/images/report/jdpg.png" alt="借贷评估" class="w-8 h-8 object-contain" />
            </div>
            <div class="flex-1">
              <h4 class="font-bold text-lg text-[#333333]">借贷评估</h4>
              <p class="text-sm text-[#999999]">申请频率、偿债压力、欺诈团伙等</p>
            </div>
          </div>

          <div v-if="getLoanEvaluationRisks().length > 0" class="space-y-2">
            <div v-for="risk in getLoanEvaluationRisks()" :key="risk.key"
              class="bg-[#FFF0F0] border border-red-200 rounded-lg p-4 relative">
              <div
                :class="['absolute top-0 right-0 px-1.5 py-0.5 text-xs text-white rounded-bl-lg rounded-tr-lg', getRiskBadgeColor(risk)]">
                {{ risk.level }}
              </div>
              <div class="flex items-center">
                <div class="w-8 h-8 mr-3 flex-shrink-0">
                  <img :src="getRiskIcon(risk)" :alt="risk.level" class="w-8 h-8 object-contain" />
                </div>
                <div class="flex-1 pr-12">
                  <div class="font-bold text-[#333333] text-sm">{{ risk.description }}</div>
                  <div class="text-xs text-[#999999] mt-0.5">{{ risk.detail }}</div>
                </div>
              </div>
            </div>
          </div>

          <div v-else class="bg-[#F0FFF0] border border-green-200 rounded-lg p-4">
            <div class="flex items-center">
              <div class="w-10 h-10 mr-4">
                <img src="@/assets/images/report/zq.png" alt="暂无风险" class="w-10 h-10 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-[#333333]">暂无风险</div>
                <div class="text-sm text-[#999999]">该模块未检测到风险</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 租赁风险评估 -->
        <div class="risk-module-card relative" :class="getModuleCardClass('leasing')">
          <div v-if="getLeasingRiskRisks().length > 0"
            :class="['absolute top-0 right-0 px-2 py-1 text-xs text-white rounded-bl-xl rounded-tr-xl', getRiskBadgeBgColor(getModuleHighestRiskLevel('leasing'))]">
            {{ getLeasingRiskRisks().length }}条风险
          </div>
          <div class="flex items-center mb-3">
            <div class="w-10 h-10">
              <img src="@/assets/images/report/zlfxpg.png" alt="租赁风险评估" class="w-8 h-8 object-contain" />
            </div>
            <div class="flex-1">
              <h4 class="font-bold text-lg text-[#333333]">租赁风险评估</h4>
              <p class="text-sm text-[#999999]">租赁机构申请频率等风险</p>
            </div>
          </div>

          <div v-if="getLeasingRiskRisks().length > 0" class="space-y-2">
            <div v-for="risk in getLeasingRiskRisks()" :key="risk.key"
              class="bg-[#FFF0F0] border border-red-200 rounded-lg p-4 relative">
              <div
                :class="['absolute top-0 right-0 px-1.5 py-0.5 text-xs text-white rounded-bl-lg rounded-tr-lg', getRiskBadgeColor(risk)]">
                {{ risk.level }}
              </div>
              <div class="flex items-center">
                <div class="w-8 h-8 mr-3 flex-shrink-0">
                  <img :src="getRiskIcon(risk)" :alt="risk.level" class="w-8 h-8 object-contain" />
                </div>
                <div class="flex-1 pr-12">
                  <div class="font-bold text-[#333333] text-sm">{{ risk.description }}</div>
                  <div class="text-xs text-[#999999] mt-0.5">{{ risk.detail }}</div>
                </div>
              </div>
            </div>
          </div>

          <div v-else class="bg-[#F0FFF0] border border-green-200 rounded-lg p-4">
            <div class="flex items-center">
              <div class="w-10 h-10 mr-4">
                <img src="@/assets/images/report/zq.png" alt="暂无风险" class="w-10 h-10 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-[#333333]">暂无风险</div>
                <div class="text-sm text-[#999999]">该模块未检测到风险</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="风险总览以标签化形式展示各类风险模块的详细信息。每个模块都有独立的风险检测机制和评估标准。要素核查验证基础信息的一致性，运营商核验关注手机号状态，公安重点人员核验检查前科记录，逾期风险分析还款表现，司法风险关注涉诉情况，借贷评估分析申请行为，租赁风险评估关注租赁申请。建议重点关注高风险模块的具体风险项目。" />
</template>

<script setup>
import LRemark from '@/components/LRemark.vue'
import { useRiskNotifier } from '@/composables/useRiskNotifier'
import {
  formatAmountInterval,
  formatCountInterval,
  formatDaysInterval,
  formatInstitutionInterval,
  formatTimeInterval,
  formatApplicationInterval,
  formatRiskLevel,
  formatRiskFlag,
  formatVerificationResult
} from '@/ui/CDWBG8B4D/utils/intervalFormatter.js'

// 导入风险类型图标
import iconZfx from '@/assets/images/report/zfx.png'
import iconGfx from '@/assets/images/report/gfx.png'

// 图标路径
const courtIconPath = new URL('@/assets/images/report/fybgt.png', import.meta.url).href
const safeIconPath = new URL('@/assets/images/report/zq.png', import.meta.url).href

// 风险类型图标映射
const riskTypeIcons = {
  'zfx.png': iconZfx,
  'gfx.png': iconGfx
}

const props = defineProps({
  data: {
    type: Object,
    required: true,
  },
  apiId: {
    type: String,
    default: '',
  },
  index: {
    type: Number,
    default: 0,
  },
  notifyRiskStatus: {
    type: Function,
    default: () => { },
  },
})

// 从data中解构出riskWarning
const riskWarning = computed(() => (props.data && props.data.riskWarning) ? props.data.riskWarning : {});

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 风险等级相关函数
const getRiskLevels = () => {
  if (!riskWarning.value?.level) return []
  return riskWarning.value.level.split(',').map(level => level.trim()).filter(level => level)
}

const getRiskLevelText = (level) => {
  return formatRiskLevel(level)
}

const getRiskLevelTagClass = (level) => {
  if (level === '0' || level === 'B3') return 'bg-green-100 text-green-700 border-green-200'
  if (level.startsWith('A')) return 'bg-red-100 text-red-700 border-red-200'
  if (level.startsWith('B')) return 'bg-orange-100 text-orange-700 border-orange-200'
  if (level.startsWith('C')) return 'bg-yellow-100 text-yellow-700 border-yellow-200'
  if (level.startsWith('D')) return 'bg-purple-100 text-purple-700 border-purple-200'
  if (level.startsWith('E')) return 'bg-blue-100 text-blue-700 border-blue-200'
  if (level.startsWith('F')) return 'bg-gray-100 text-gray-700 border-gray-200'
  return 'bg-gray-100 text-gray-700 border-gray-200'
}

// 风险等级样式
const getRiskLevelClass = (level) => {
  if (level === '高风险') return 'bg-red-100 text-red-700 border-red-200'
  if (level === '中风险') return 'bg-orange-100 text-orange-700 border-orange-200'
  return 'bg-gray-100 text-gray-700 border-gray-200'
}

// 根据风险等级获取对应的图标路径
const getRiskIconPath = (level) => {
  if (level === '高风险') {
    return new URL('@/assets/images/report/gfx.png', import.meta.url).href
  } else if (level === '中风险') {
    return new URL('@/assets/images/report/zfx.png', import.meta.url).href
  }
  return new URL('@/assets/images/report/zfx.png', import.meta.url).href // 默认使用中风险图标
}

// 根据风险等级获取对应的背景色
const getRiskBadgeBgColor = (level) => {
  if (level === '高风险') {
    return 'bg-[#E53935]'
  } else if (level === '中风险') {
    return 'bg-[#D6943E]'
  }
  return 'bg-[#D6943E]' // 默认使用中风险颜色
}

// 根据风险代码获取对应的图标和背景色
const getRiskTypeConfig = (levelCode) => {
  if (!levelCode) return { icon: 'zfx.png', bgColor: 'bg-[#D6943E]' }

  // A类：红色系
  if (levelCode.startsWith('A')) {
    return { icon: 'gfx.png', bgColor: 'bg-[#E53935]' }
  }
  // B类：橙色系
  if (levelCode.startsWith('B')) {
    return { icon: 'zfx.png', bgColor: 'bg-[#D6943E]' }
  }
  // C类：黄色系
  if (levelCode.startsWith('C')) {
    return { icon: 'zfx.png', bgColor: 'bg-[#D6943E]' }
  }
  // D类：紫色系
  if (levelCode.startsWith('D')) {
    return { icon: 'gfx.png', bgColor: 'bg-[#E53935]' }
  }
  // E类：蓝色系
  if (levelCode.startsWith('E')) {
    return { icon: 'zfx.png', bgColor: 'bg-[#D6943E]' }
  }
  // F类：灰色系
  if (levelCode.startsWith('F')) {
    return { icon: 'zfx.png', bgColor: 'bg-[#999999]' }
  }

  return { icon: 'zfx.png', bgColor: 'bg-[#D6943E]' }
}

// 获取风险图标路径（根据 risk 对象）
const getRiskIcon = (risk) => {
  // 优先根据风险等级（高风险/中风险）来决定图标
  if (risk?.level === '高风险') {
    return iconGfx
  } else if (risk?.level === '中风险') {
    return iconZfx
  }
  // 如果没有level，使用levelCode来判断
  if (risk?.levelCode) {
    const config = getRiskTypeConfig(risk.levelCode)
    return riskTypeIcons[config.icon] || iconZfx
  }
  return iconZfx
}

// 获取风险标签颜色（根据 risk 对象）
const getRiskBadgeColor = (risk) => {
  // 优先根据风险等级（高风险/中风险）来决定背景色
  if (risk?.level === '高风险') {
    return 'bg-[#E53935]'
  } else if (risk?.level === '中风险') {
    return 'bg-[#D6943E]'
  }
  // 如果没有level，使用levelCode来判断
  if (risk?.levelCode) {
    const config = getRiskTypeConfig(risk.levelCode)
    return config.bgColor
  }
  return 'bg-[#D6943E]'
}

// 模块卡片样式
const getModuleCardClass = (module) => {
  const riskCount = getModuleRiskCount(module)
  if (riskCount > 0) return 'border-red-200'
  return 'border-green-200'
}

// 模块状态样式
const getModuleStatusClass = (module) => {
  const riskCount = getModuleRiskCount(module)
  if (riskCount > 0) return 'bg-red-100 text-red-700'
  return 'bg-green-100 text-green-700'
}

// 获取模块风险数量
const getModuleRiskCount = (module) => {
  switch (module) {
    case 'element':
      return getElementVerificationRisks().length
    case 'operator':
      return getOperatorVerificationRisks().length
    case 'police':
      return getPoliceVerificationRisks().length
    case 'overdue':
      return getOverdueRiskRisks().length
    case 'court':
      return getCourtRiskRisks().length
    case 'loan':
      return getLoanEvaluationRisks().length
    case 'leasing':
      return getLeasingRiskRisks().length
    default:
      return 0
  }
}

// 获取模块的风险列表
const getModuleRisks = (moduleType) => {
  switch (moduleType) {
    case 'element':
      return getElementVerificationRisks()
    case 'operator':
      return getOperatorVerificationRisks()
    case 'police':
      return getPoliceVerificationRisks()
    case 'overdue':
      return getOverdueRiskRisks()
    case 'court':
      return getCourtRiskRisks()
    case 'loan':
      return getLoanEvaluationRisks()
    case 'leasing':
      return getLeasingRiskRisks()
    default:
      return []
  }
}

// 获取模块的最高风险等级
const getModuleHighestRiskLevel = (moduleType) => {
  const risks = getModuleRisks(moduleType)
  if (risks.length === 0) return '中风险'
  const hasHighRisk = risks.some(risk => risk.level === '高风险')
  return hasHighRisk ? '高风险' : '中风险'
}

// 获取高风险数量
const getHighRiskCount = () => {
  const highRiskFields = [
    'idCardTwoElementMismatch', 'phoneThreeElementMismatch',
    'shortPhoneDuration', 'noPhoneDuration',
    'hasCriminalRecord', 'isEconomyFront', 'isDisrupSocial', 'isKeyPerson', 'isTrafficRelated',
    'hitHighRiskBankLastTwoYears', 'hitHighRiskNonBankLastTwoYears',
    'hitCivilCase', 'hitCriminalRisk', 'hitAdministrativeCase', 'hitPreservationReview',
    'hitExecutionCase', 'hitBankruptcyAndLiquidation', 'hitDirectlyUnderCase', 'hitCompensationCase',
    'frequentApplicationRecent', 'frequentNonBankApplications', 'highDebtPressure', 'frequentBankApplications',
    'frequentRentalApplications', 'veryFrequentRentalApplications'
  ]

  return highRiskFields.reduce((count, field) => {
    return count + (riskWarning.value[field] || 0)
  }, 0)
}

// 获取中风险数量
const getMiddleRiskCount = () => {
  const middleRiskFields = [
    'idCardPhoneProvinceMismatch', 'isAntiFraudInfo',
    'hitCurrentOverdue',
    'moreFrequentNonBankApplications', 'highFraudGangLevel', 'moreFrequentBankApplications'
  ]

  return middleRiskFields.reduce((count, field) => {
    return count + (riskWarning.value[field] || 0)
  }, 0)
}

// 要素核查风险
const getElementVerificationRisks = () => {
  const risks = []

  if (riskWarning.value.idCardTwoElementMismatch) {
    risks.push({
      key: 'idCardTwoElementMismatch',
      description: '身份证二要素信息对比结果不一致',
      detail: '身份证号与姓名信息不匹配',
      level: '高风险'
    })
  }

  if (riskWarning.value.phoneThreeElementMismatch) {
    risks.push({
      key: 'phoneThreeElementMismatch',
      description: '手机三要素简版不一致',
      detail: '手机号与身份证号、姓名信息不匹配',
      level: '高风险'
    })
  }

  return risks
}

// 运营商核验风险
const getOperatorVerificationRisks = () => {
  const risks = []

  if (riskWarning.value.shortPhoneDuration) {
    risks.push({
      key: 'shortPhoneDuration',
      description: '手机在网时长极短',
      detail: '手机号在网时间过短，存在风险',
      level: '高风险'
    })
  }

  if (riskWarning.value.shortPhoneDurationSlight) {
    risks.push({
      key: 'shortPhoneDurationSlight',
      description: '手机在网时长较短',
      detail: '手机号在网时间较短，存在风险',
      level: '高风险'
    })
  }

  if (riskWarning.value.idCardPhoneProvinceMismatch) {
    risks.push({
      key: 'idCardPhoneProvinceMismatch',
      description: '身份证号手机号归属省不一致',
      detail: '身份证归属地与手机号归属地不匹配',
      level: '中风险'
    })
  }

  if (riskWarning.value.noPhoneDuration) {
    risks.push({
      key: 'noPhoneDuration',
      description: '手机在网状态为风险号',
      detail: '手机号状态异常，存在风险',
      level: '高风险'
    })
  }

  return risks
}

// 根据 level 字段生成风险项
const getLevelBasedRisks = () => {
  const risks = []
  const levels = riskWarning.value?.level

  if (!levels) return risks

  const levelList = levels.split(',').map(l => l.trim()).filter(l => l && l !== '0' && l !== 'B3')

  // 获取统计数据，确定整体风险等级
  const highCounts = riskWarning.value.gazdyrhyRiskHighCounts || 0
  const middleCounts = riskWarning.value.gazdyrhyRiskMiddleCounts || 0

  // 根据统计数据判断整体风险等级
  // 如果有高风险，整体显示为高风险；如果只有中风险，整体显示为中风险
  let overallRiskLevel = '高风险'
  if (highCounts > 0) {
    overallRiskLevel = '高风险'
  } else if (middleCounts > 0 && highCounts === 0) {
    overallRiskLevel = '中风险'
  }

  levelList.forEach((level, index) => {
    const levelDescription = getRiskLevelText(level)
    risks.push({
      key: `level_${level}_${index}`,
      description: `命中${levelDescription}`,
      detail: levelDescription,
      level: overallRiskLevel,
      levelCode: level
    })
  })

  return risks
}

// 公安重点人员核验风险
const getPoliceVerificationRisks = () => {
  const risks = []

  // 只添加基于 level 字段的风险项
  risks.push(...getLevelBasedRisks())

  return risks
}

// 逾期风险
const getOverdueRiskRisks = () => {
  const risks = []

  if (riskWarning.value.hitHighRiskBankLastTwoYears) {
    risks.push({
      key: 'hitHighRiskBankLastTwoYears',
      description: '近两年命中银行高风险',
      detail: '近两年在银行机构存在高风险记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitHighRiskNonBankLastTwoYears) {
    risks.push({
      key: 'hitHighRiskNonBankLastTwoYears',
      description: '近两年命中非银高风险',
      detail: '近两年在非银行机构存在高风险记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitCurrentOverdue) {
    risks.push({
      key: 'hitCurrentOverdue',
      description: '该用户命中当前逾期',
      detail: '用户当前存在逾期记录',
      level: '中风险'
    })
  }

  return risks
}

// 法院曝光台信息
const getCourtRiskRisks = () => {
  const risks = []

  if (riskWarning.value.hitCivilCase) {
    risks.push({
      key: 'hitCivilCase',
      description: '该用户命中民事案件',
      detail: '用户存在民事案件记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitCriminalRisk) {
    risks.push({
      key: 'hitCriminalRisk',
      description: '该用户命中刑事风险',
      detail: '用户存在刑事风险记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitAdministrativeCase) {
    risks.push({
      key: 'hitAdministrativeCase',
      description: '该用户命中行政案件',
      detail: '用户存在行政案件记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitPreservationReview) {
    risks.push({
      key: 'hitPreservationReview',
      description: '该用户命中保全审查',
      detail: '用户存在保全审查记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitExecutionCase) {
    risks.push({
      key: 'hitExecutionCase',
      description: '该用户命中执行案件',
      detail: '用户存在执行案件记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitBankruptcyAndLiquidation) {
    risks.push({
      key: 'hitBankruptcyAndLiquidation',
      description: '该用户命中强制清算与破产案件',
      detail: '用户存在破产清算案件记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitDirectlyUnderCase) {
    risks.push({
      key: 'hitDirectlyUnderCase',
      description: '该用户命中直辖案件',
      detail: '用户存在直辖案件记录',
      level: '高风险'
    })
  }

  if (riskWarning.value.hitCompensationCase) {
    risks.push({
      key: 'hitCompensationCase',
      description: '该用户命中赔偿案件',
      detail: '用户存在赔偿案件记录',
      level: '高风险'
    })
  }

  return risks
}

// 借贷评估风险
const getLoanEvaluationRisks = () => {
  const risks = []

  if (riskWarning.value.frequentApplicationRecent) {
    risks.push({
      key: 'frequentApplicationRecent',
      description: '近期申请机构极为频繁',
      detail: '近期在多个机构频繁申请贷款',
      level: '高风险'
    })
  }

  if (riskWarning.value.frequentNonBankApplications) {
    risks.push({
      key: 'frequentNonBankApplications',
      description: '在非银机构申请次数极多',
      detail: '在非银行机构申请次数过多',
      level: '高风险'
    })
  }

  if (riskWarning.value.highDebtPressure) {
    risks.push({
      key: 'highDebtPressure',
      description: '偿债压力极高',
      detail: '用户偿债压力过大',
      level: '高风险'
    })
  }

  if (riskWarning.value.frequentBankApplications) {
    risks.push({
      key: 'frequentBankApplications',
      description: '在银行机构申请次数极多',
      detail: '在银行机构申请次数过多',
      level: '高风险'
    })
  }

  if (riskWarning.value.moreFrequentNonBankApplications) {
    risks.push({
      key: 'moreFrequentNonBankApplications',
      description: '在非银机构申请次数较多',
      detail: '在非银行机构申请次数较多',
      level: '中风险'
    })
  }

  if (riskWarning.value.highFraudGangLevel) {
    risks.push({
      key: 'highFraudGangLevel',
      description: '欺诈团伙等级较高',
      detail: '用户存在欺诈团伙关联风险',
      level: '中风险'
    })
  }

  if (riskWarning.value.moreFrequentBankApplications) {
    risks.push({
      key: 'moreFrequentBankApplications',
      description: '在银行机构申请次数较多',
      detail: '在银行机构申请次数较多',
      level: '中风险'
    })
  }

  return risks
}

// 租赁风险评估风险
const getLeasingRiskRisks = () => {
  const risks = []

  if (riskWarning.value.frequentRentalApplications) {
    risks.push({
      key: 'frequentRentalApplications',
      description: '在租赁机构申请极为频繁',
      detail: '在租赁机构申请过于频繁',
      level: '高风险'
    })
  }

  if (riskWarning.value.veryFrequentRentalApplications) {
    risks.push({
      key: 'veryFrequentRentalApplications',
      description: '在租赁机构申请次数极多',
      detail: '在租赁机构申请次数过多',
      level: '高风险'
    })
  }

  return risks
}

// 计算风险评分（0-100分，分数越高越安全）
const riskScore = computed(() => {
  const riskWarningData = riskWarning.value || {};

  // 获取高风险数量
  const highRiskCount = getHighRiskCount();
  const middleRiskCount = getMiddleRiskCount();

  // 高风险数量越多，分数越低
  let score = 100;

  // 高风险扣分（每个高风险扣10分）
  score -= highRiskCount * 10;

  // 中风险扣分（每个中风险扣5分）
  score -= middleRiskCount * 5;

  // 确保分数在合理范围内
  return Math.max(20, Math.min(100, score));
});

// 使用 composable 通知父组件风险评分
useRiskNotifier(props, riskScore);

// 暴露给父组件
defineExpose({
  riskScore
});
</script>

<style lang="scss" scoped>
.risk-warning-tab {
  @apply space-y-6;
}

.page-header {
  @apply bg-white rounded-2xl border border-gray-200 p-6 shadow-sm;
}

.risk-overview-card {
  .stat-card-compact {
    @apply bg-white rounded-lg p-3 shadow-sm border border-gray-100;

    .stat-icon-compact {
      @apply w-6 h-6 rounded-md flex items-center justify-center mb-1;
    }

    .stat-content-compact {
      .stat-number-compact {
        @apply text-lg font-bold;
      }

      .stat-label-compact {
        @apply text-xs text-gray-600;
      }
    }
  }
}

.section-title {
  @apply border-b border-gray-200 pb-2;
}

.risk-module-card {
  @apply rounded-xl border-2 p-6 shadow-sm transition-all duration-200 hover:shadow-md;

  .module-header {
    @apply flex items-center mb-4;

    .module-icon {
      @apply w-10 h-10 rounded-xl flex items-center justify-center mr-4 shadow-sm;
    }

    .module-info {
      @apply flex-1;

      .module-title {
        @apply text-lg font-semibold text-gray-800 mb-1;
      }

      .module-desc {
        @apply text-sm text-gray-600;
      }
    }

    .module-status {
      .status-badge {
        @apply px-3 py-1 rounded-full text-sm font-medium;
      }
    }
  }

  .module-content {
    .risk-list {
      @apply space-y-3;

      .risk-item {
        @apply flex items-center p-4 bg-gray-50 rounded-xl border border-gray-200;

        .risk-indicator {
          @apply w-3 h-3 rounded-full mr-3 flex-shrink-0;
        }

        .risk-details {
          @apply flex-1;

          .risk-title {
            @apply font-medium text-gray-800 mb-1;
          }

          .risk-desc {
            @apply text-sm text-gray-600;
          }
        }

        .risk-level {
          @apply px-2 py-1 rounded-full text-xs font-medium border;
        }
      }
    }
  }

  .no-risk-content {
    @apply flex items-center justify-center p-8 bg-green-50 rounded-xl border border-green-200;

    .no-risk-icon {
      @apply mr-3;
    }

    .no-risk-text {
      @apply text-center;
    }
  }

  .risk-level-section {
    .risk-level-tags {
      @apply flex flex-wrap gap-2;

      .risk-level-tag {
        @apply px-2 py-1 rounded-md text-xs font-medium border;
      }
    }
  }
}
</style>