<template>
  <div class="card shadow-sm rounded-xl overflow-hidden flex flex-col gap-4">
    <!-- 申请次数 -->
    <ApplicationCountSection :data="variableValue" />

    <!-- 申请总次数 (银行+非银) -->
    <ApplicationTotalSection :data="variableValue" />

    <!-- 申请机构总数 (银行+非银) -->
    <InstitutionTotalSection :data="variableValue" />
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRiskNotifier } from '@/composables/useRiskNotifier'
import { extractVariableValue } from './utils/dataParser'
import ApplicationCountSection from './components/ApplicationCountSection.vue'
import ApplicationTotalSection from './components/ApplicationTotalSection.vue'
import InstitutionTotalSection from './components/InstitutionTotalSection.vue'

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

// 获取数据
const rawData = computed(() => props.data?.data || props.data || {})

// 提取 variableValue
const variableValue = computed(() => extractVariableValue(rawData.value))

// 计算风险评分（0-100分，分数越高越安全）
const riskScore = computed(() => {
  const data = variableValue.value
  
  if (!data || Object.keys(data).length === 0) {
    return 100 // 无数据视为最安全
  }

  let score = 100 // 初始满分

  // 近7天申请次数评估
  const d7Total = parseInt(data.als_d7_id_bank_allnum || 0) + parseInt(data.als_d7_id_nbank_allnum || 0)
  if (d7Total > 5) {
    score -= 20 // 近7天申请过多
  } else if (d7Total > 3) {
    score -= 10
  }

  // 近15天申请次数评估
  const d15Total = parseInt(data.als_d15_id_bank_allnum || 0) + parseInt(data.als_d15_id_nbank_allnum || 0)
  if (d15Total > 10) {
    score -= 15
  } else if (d15Total > 5) {
    score -= 8
  }

  // 近1个月申请次数评估
  const m1Total = parseInt(data.als_m1_id_bank_allnum || 0) + parseInt(data.als_m1_id_nbank_allnum || 0)
  if (m1Total > 15) {
    score -= 20
  } else if (m1Total > 8) {
    score -= 10
  }

  // 近3个月申请次数评估
  const m3Total = parseInt(data.als_m3_id_bank_allnum || 0) + parseInt(data.als_m3_id_nbank_allnum || 0)
  if (m3Total > 20) {
    score -= 15
  } else if (m3Total > 10) {
    score -= 8
  }

  // 近6个月申请次数评估
  const m6Total = parseInt(data.als_m6_id_bank_allnum || 0) + parseInt(data.als_m6_id_nbank_allnum || 0)
  if (m6Total > 30) {
    score -= 10
  } else if (m6Total > 15) {
    score -= 5
  }

  // 确保分数在10-100范围内
  return Math.max(10, Math.min(100, score))
})

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

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

<style scoped>
.card {
  background: #ffffff;
  border: 1px solid #e5e7eb;
}
</style>


