<template>
  <div class="card">
    <div class="rounded-lg border border-gray-200 pb-4 mb-4">
      <div class="flex items-center mb-4 p-4">
        <div class="w-8 h-8 flex items-center justify-center mr-2">
          <img src="@/assets/images/report/mzfxbz.png" alt="命中风险标注" class="w-8 h-8 object-contain" />
        </div>
        <span class="font-bold text-gray-800">命中风险标注</span>
      </div>

      <div class="mt-4">
        <!-- 风险概览统计 -->
        <div class="mb-4">
          <LTitle title="风险概览" />
        </div>
        <div class="px-4">

          <div class="grid grid-cols-2 gap-4">
            <div class="rounded-lg border p-2 text-center" :class="getOverviewCardStyle()">
              <div class="text-xl font-bold mb-1" :class="getOverviewTextStyle()">{{ totalRiskCount }}</div>
              <div class="text-sm font-medium text-gray-700">风险点总数</div>
            </div>
            <div class="rounded-lg border p-2 text-center" :class="getOverviewCardStyle()">
              <div class="text-xl font-bold mb-1" :class="getOverviewTextStyle()">
                {{ totalRiskCount > 0 ? '有风险' : '无风险' }}
              </div>
              <div class="text-sm font-medium text-gray-700">综合评估</div>
            </div>
          </div>
        </div>

        <!-- 详细风险项 -->
        <div class="space-y-3 p-4">
          <div v-for="(riskItem, key) in riskItems" :key="key"
            class="relative rounded-lg border p-3 transition-all duration-300" :class="getRiskItemCardStyle(riskItem)">
            <!-- 右上角风险标签 -->
            <div class="absolute top-0 right-0">
              <div class="px-2 py-1 text-xs text-white rounded-bl-lg rounded-tr-lg" :class="getRiskTagClass(riskItem)">
                {{ getRiskLevelText(riskItem) }}
              </div>
            </div>

            <div class="flex items-center">
              <div class="w-8 h-8 flex items-center justify-center mr-3">
                <img :src="getRiskItemIcon(riskItem)" :alt="riskItem.name" class="w-8 h-8 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-gray-800 mb-1">{{ riskItem.name }}</div>
                <div class="text-sm text-[#999999]">{{ riskItem.description }}</div>
              </div>
            </div>

            <!-- 风险进度条（仅命中时显示） -->
            <div v-if="riskItem.hasRisk" class="mt-3">
              <div class="w-full bg-gray-200 rounded-full h-1.5">
                <div class="h-1.5 rounded-full transition-all duration-500" :class="getRiskProgressBarStyle(riskItem)"
                  :style="{ width: getRiskProgressWidth(riskItem) }"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- 特殊风险提示 -->
        <div v-if="hasHighRisk" class="px-4">
          <div class="flex items-center mb-3">
            <div class="w-4 h-4 flex items-center justify-center mr-2">
              <img src="@/assets/images/report/wxts_icon.png" alt="风险提示" class="w-4 h-4 object-contain" />
            </div>
            <div class="font-bold" :class="getRiskTitleColor">高风险警告</div>
          </div>
          <div class="ml-6 text-sm mb-1" :class="getRiskContentColor">
            检测到多个高风险项目，建议谨慎处理。特别关注司法涉诉、公安重点人员等关键风险指标。
          </div>
        </div>

        <!-- 无风险提示 -->
        <div v-if="!totalRiskCount" class="px-4 mt-4">
          <div class="flex items-center mb-3">
            <div class="w-4 h-4 flex items-center justify-center mr-2">
              <img src="@/assets/images/report/wxts_icon.png" alt="风险评估" class="w-4 h-4 object-contain" />
            </div>
            <div class="font-bold" :class="getRiskTitleColor">风险评估通过</div>
          </div>
          <div class="ml-6 text-sm" :class="getRiskContentColor">
            未检测到明显风险项目，各项指标表现良好。
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 温馨提示 -->
  <LRemark
    content="风险点分析展示申请人的具体风险点和风险等级评估。包括各类风险因子的详细分析和风险权重计算。风险点基于多个风险模型和算法计算得出，包括但不限于信用历史、行为模式、关联关系等。不同风险点有不同的权重和影响度。建议重点关注高权重的风险点，并结合具体业务场景进行风险等级判定。" />
</template>

<script setup>
import { computed } from 'vue'
import LTitle from '@/components/LTitle.vue'
import LRemark from '@/components/LRemark.vue'
import { useRiskNotifier } from '@/composables/useRiskNotifier'

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

// 从data中解构出需要的字段
const riskPoint = computed(() => {
  return props.data?.riskPoint || {}
})

// 风险项配置
const riskConfig = {
  multiQuery: {
    name: '多头查询次数多',
    description: '近期申请网贷的查询次数较多',
    isHighRisk: false,
    icon: '🔍',
    color: 'orange'
  },
  riskList: {
    name: '命中风险关注名单',
    description: '命中信贷高风险或租赁关注类名单库',
    isHighRisk: true,
    icon: '📋',
    color: 'red'
  },
  newRiskFeature: {
    name: '命中新增风险特征规则',
    description: '命中报告中未展示的内容，数据的模型评分较低',
    isHighRisk: true,
    icon: '🆕',
    color: 'red'
  },
  deductFail: {
    name: '近期扣款失败次数较多',
    description: '近期代扣还款失败次数较多',
    isHighRisk: false,
    icon: '💳',
    color: 'orange'
  },
  judicialRisk: {
    name: '命中司法涉诉案件',
    description: '用户历史上有过失信、犯罪、纠纷等严重影响信用记录的法院案件记录',
    isHighRisk: true,
    icon: '⚖️',
    color: 'red'
  },
  hitPreservationReview: {
    name: '命中非诉保全',
    description: '命中非诉保全案件',
    isHighRisk: true,
    icon: '🛡️',
    color: 'red'
  },
  legalCasesFlag: {
    name: '涉案公告',
    description: '命中涉案相关公告',
    isHighRisk: true,
    icon: '📢',
    color: 'red'
  },
  executionCasesFlag: {
    name: '执行公告',
    description: '命中执行案件公告',
    isHighRisk: true,
    icon: '⚡',
    color: 'red'
  },
  disinCasesFlag: {
    name: '失信公告',
    description: '命中失信被执行人公告',
    isHighRisk: true,
    icon: '🚫',
    color: 'red'
  },
  limitCasesFlag: {
    name: '限高公告',
    description: '命中限制高消费公告',
    isHighRisk: true,
    icon: '🚷',
    color: 'red'
  },
  securityRisk: {
    name: '命中公安重点人员',
    description: '命中公安重点人员名单',
    isHighRisk: true,
    icon: '👮',
    color: 'red'
  },
  antiFraudRisk: {
    name: '命中涉赌涉诈',
    description: '命中涉赌涉诈风险名单',
    isHighRisk: true,
    icon: '🎰',
    color: 'red'
  }
}

// 处理风险项数据
const riskItems = computed(() => {
  const items = {}

  Object.keys(riskConfig).forEach(key => {
    const value = riskPoint.value?.[key] || 0
    let hasRisk = false

    // 判断是否有风险
    if (typeof value === 'number') {
      hasRisk = value > 0
    } else if (typeof value === 'string') {
      hasRisk = value !== '0' && value !== ''
    }

    items[key] = {
      ...riskConfig[key],
      hasRisk,
      value
    }
  })

  return items
})

// 计算总风险数量
const totalRiskCount = computed(() => {
  return Object.values(riskItems.value).filter(item => item.hasRisk).length
})

// 是否有高风险项
const hasHighRisk = computed(() => {
  return Object.values(riskItems.value).some(item => item.hasRisk && item.isHighRisk)
})

// 是否有中风险项
const hasMediumRisk = computed(() => {
  return Object.values(riskItems.value).some(item => item.hasRisk && !item.isHighRisk)
})

// 获取概览卡片样式 - 根据风险情况动态变化
const getOverviewCardStyle = () => {
  if (totalRiskCount.value === 0) {
    return 'border-[#4CAF508F] bg-[#4CAF501A]' // 无风险：绿色
  } else if (hasHighRisk.value) {
    return 'border-[#EB3C3C8F] bg-[#EB3C3C1A]' // 高风险：红色
  } else {
    return 'border-[#D6943E8F] bg-[#D6943E1A]' // 中风险：橙色
  }
}

// 获取概览文字样式 - 根据风险情况动态变化
const getOverviewTextStyle = () => {
  if (totalRiskCount.value === 0) {
    return 'text-[#4CAF50]' // 无风险：绿色
  } else if (hasHighRisk.value) {
    return 'text-[#EB3C3C]' // 高风险：红色
  } else {
    return 'text-[#D6943E]' // 中风险：橙色
  }
}

// 获取风险项卡片整体样式
const getRiskItemCardStyle = (riskItem) => {
  if (riskItem.hasRisk) {
    if (riskItem.isHighRisk) {
      return 'bg-[#F9ECEC] border-[#F0CACA]'
    } else {
      return 'bg-[#F9F5ED] border-[#FFB74D8F]'
    }
  }
  return 'bg-[#ECF9EF] border-[#CAECD3]'
}

// 获取风险项图标
const getRiskItemIcon = (riskItem) => {
  if (riskItem.hasRisk) {
    if (riskItem.isHighRisk) {
      return new URL('@/assets/images/report/gfx.png', import.meta.url).href
    } else {
      return new URL('@/assets/images/report/zfx.png', import.meta.url).href
    }
  }
  return new URL('@/assets/images/report/zq.png', import.meta.url).href
}

// 获取风险标签样式
const getRiskTagClass = (riskItem) => {
  if (riskItem.hasRisk) {
    if (riskItem.isHighRisk) {
      return 'bg-[#E53935]'
    } else {
      return 'bg-[#FF8C00]'
    }
  }
  return 'bg-[#4CAF50]'
}

// 获取风险等级文本
const getRiskLevelText = (riskItem) => {
  if (!riskItem.hasRisk) return '安全'

  if (riskItem.isHighRisk) {
    return '高风险'
  } else {
    return '中风险'
  }
}

// 获取风险进度条样式
const getRiskProgressBarStyle = (riskItem) => {
  if (riskItem.isHighRisk) {
    return 'bg-gradient-to-r from-red-400 to-red-600'
  } else {
    return 'bg-gradient-to-r from-orange-400 to-orange-600'
  }
}

// 获取风险进度宽度
const getRiskProgressWidth = (riskItem) => {
  if (!riskItem.hasRisk) return '0%'

  if (riskItem.isHighRisk) {
    return '85%' // 高风险
  } else {
    return '60%' // 中风险
  }
}

// 获取风险进度文字颜色
const getRiskProgressTextColor = (riskItem) => {
  if (riskItem.isHighRisk) {
    return 'text-red-600'
  } else {
    return 'text-orange-600'
  }
}

// 获取风险进度文字
const getRiskProgressText = (riskItem) => {
  if (!riskItem.hasRisk) return '无风险'

  if (riskItem.isHighRisk) {
    return '高风险'
  } else {
    return '中等风险'
  }
}

// 获取整体风险等级
const overallRiskLevel = computed(() => {
  if (hasHighRisk.value) return 'high'
  if (totalRiskCount.value > 0) return 'medium'
  return 'none'
})

// 获取风险提示标题颜色
const getRiskTitleColor = computed(() => {
  const level = overallRiskLevel.value
  const colors = {
    'high': 'text-[#EB3C3C]',
    'medium': 'text-[#FF8C00]',
    'none': 'text-gray-800'
  }
  return colors[level] || colors.none
})

// 获取风险提示内容颜色
const getRiskContentColor = computed(() => {
  const level = overallRiskLevel.value
  const colors = {
    'high': 'text-[#EB3C3C]',
    'medium': 'text-[#FF8C00]',
    'none': 'text-gray-600'
  }
  return colors[level] || colors.none
})

// 计算风险评分（0-100分，分数越高越安全）
const riskScore = computed(() => {
  // 计算高风险数量和中风险数量
  let highRiskCount = 0;
  let mediumRiskCount = 0;

  Object.values(riskItems.value).forEach(item => {
    if (item.hasRisk) {
      if (item.isHighRisk) {
        highRiskCount++;
      } else {
        mediumRiskCount++;
      }
    }
  });

  // 没有风险 -> 100分
  if (highRiskCount === 0 && mediumRiskCount === 0) {
    return 100;
  }

  // 计算风险分数
  let score = 100;

  // 每个高风险扣15分
  score -= highRiskCount * 15;

  // 每个中风险扣8分
  score -= mediumRiskCount * 8;

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

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

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

<style lang="scss" scoped>
// 组件样式</style>
