<template>
  <div class="card">
    <div class="rounded-lg border border-gray-200 pb-2 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/lsjdxw.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-6">
          <LTitle title="借贷行为概览" />
          <div class="grid grid-cols-2 gap-4 p-4">
            <div class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-blue-500">
                {{ applicationStatistics?.totalApplicationCount || 0 }}
              </div>
              <div class="text-sm text-gray-600 mt-1">总申请机构数</div>
            </div>
            <div class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-[#1FBE5D]">
                {{ formatDaysSinceLastApplication }}
              </div>
              <div class="text-sm text-gray-600 mt-1">距最近申请</div>
            </div>
          </div>
        </div>

        <!-- 机构类型分布 -->
        <div class="mb-6">
          <LTitle title="机构类型分布" />

          <!-- 饼图 -->
          <div class="w-full h-64">
            <v-chart class="chart-container" :option="pieChartOption" autoresize />
          </div>
        </div>

        <!-- 时间分布统计 -->
        <div class="">
          <LTitle title="时间分布统计" />

          <!-- 柱状图展示 -->
          <div class="mb-4 h-64">
            <v-chart class="chart-container" :option="barChartOption" autoresize />
          </div>

          <!-- 数据详情 -->
          <div class="space-y-2 p-4">
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近1个月申请机构数</span>
              <span class="text-[#333333] font-bold">
                {{ applicationStatistics?.applicationCountLastMonth || 0 }}家
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近3个月申请机构数</span>
              <span class="text-[#333333] font-bold">
                {{ applicationStatistics?.applicationCountLast3Months || 0 }}家
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近6个月申请机构数</span>
              <span class="text-[#333333] font-bold">
                {{ applicationStatistics?.applicationCountLast6Months || 0 }}家
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近12个月申请机构数</span>
              <span class="text-[#333333] font-bold">
                {{ applicationStatistics?.applicationCountLast12Months || 0 }}家
              </span>
            </div>
          </div>
        </div>

        <!-- 最近申请信息 -->
        <div class="">
          <div class="space-y-3 p-4">
            <div class="text-[#333333] font-bold text-sm">近期申请时间</div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">最后一次申请时间</span>
              <span class="text-gray-800 font-bold">
                {{ applicationStatistics?.lastApplicationDate || '-' }}
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">距离最近一次申请</span>
              <span class="text-gray-800 font-bold">
                {{ formatDaysSinceLastApplication }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 温馨提示 -->
  <LRemark
    content="申请统计展示申请人在不同时间段的申请行为统计，包括申请次数、申请机构数和申请频率等指标。数据来源于各金融机构的申请记录。申请频率过高可能暗示资金紧张或过度借贷风险，特别是短期内在多个机构频繁申请的情况。建议结合申请成功率和实际放款情况进行综合判断。数据更新频率为T+1。" />
</template>

<script setup>
import { computed } from 'vue'
import LTitle from '@/components/LTitle.vue'
import LRemark from '@/components/LRemark.vue'
import { formatDaysInterval } from '../utils/intervalFormatter.js'
import VChart from 'vue-echarts'
import { useRiskNotifier } from '@/composables/useRiskNotifier'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'

// 注册ECharts组件
use([
  CanvasRenderer,
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

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

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

// 是否有申请记录
const hasAnyApplication = computed(() => {
  return (applicationStatistics.value?.totalApplicationCount || 0) > 0
})

// 是否有高频申请风险
const hasHighFrequencyRisk = computed(() => {
  const lastMonth = applicationStatistics.value?.applicationCountLastMonth || 0
  const last3Months = applicationStatistics.value?.applicationCountLast3Months || 0

  // 近1个月申请超过3家或近3个月申请超过5家视为高频
  return lastMonth > 3 || last3Months > 5
})

// 最近申请时间颜色
const getLastApplicationColor = computed(() => {
  const daysSince = applicationStatistics.value?.daysSinceLastApplication || ''

  if (daysSince.includes('(0,30)') || daysSince.includes('近期')) {
    return 'text-red-600' // 30天内申请，红色警告
  } else if (daysSince.includes('(30,90)')) {
    return 'text-orange-600' // 30-90天，橙色注意
  } else {
    return 'text-green-600' // 90天以上，绿色正常
  }
})

// 格式化距离最近申请时间
const formatDaysSinceLastApplication = computed(() => {
  const daysSince = applicationStatistics.value?.daysSinceLastApplication || '-'
  return formatDaysInterval(daysSince)
})

// 饼图配置
const pieChartOption = computed(() => {
  const consumptionCount = applicationStatistics.value?.consumptionInstallmentApplicationCount || 0
  const onlineCount = applicationStatistics.value?.onlineLoanApplicationCount || 0
  const otherCount = applicationStatistics.value?.otherApplicationCount || 0

  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} 家 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      itemWidth: 12,
      itemHeight: 12,
      textStyle: {
        fontSize: 14,
        color: '#374151'
      },
      formatter: function (name) {
        let count = 0;
        if (name === '消费分期类') count = consumptionCount;
        else if (name === '网络贷款类') count = onlineCount;
        else if (name === '其他类型') count = otherCount;
        return `${name}  ${count}家`;
      }
    },
    series: [
      {
        name: '机构类型分布',
        type: 'pie',
        radius: ['40%', '55%'],
        center: ['35%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: [
          {
            value: consumptionCount,
            name: '消费分期类',
            itemStyle: { color: '#3b82f6' }
          },
          {
            value: onlineCount,
            name: '网络贷款类',
            itemStyle: { color: '#8b5cf6' }
          },
          {
            value: otherCount,
            name: '其他类型',
            itemStyle: { color: '#7dd3fc' }
          }
        ]
      }
    ]
  }
})

// 柱状图配置
const barChartOption = computed(() => {
  const data = [
    applicationStatistics.value?.applicationCountLastMonth || 0,
    applicationStatistics.value?.applicationCountLast3Months || 0,
    applicationStatistics.value?.applicationCountLast6Months || 0,
    applicationStatistics.value?.applicationCountLast12Months || 0
  ]

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 家'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['近1个月', '近3个月', '近6个月', '近12个月'],
      axisLabel: {
        fontSize: 11,
        color: '#6b7280'
      },
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 11,
        color: '#6b7280',
        formatter: '{value} 家'
      },
      splitLine: {
        lineStyle: {
          color: '#f3f4f6'
        }
      }
    },
    series: [
      {
        name: '申请机构数',
        type: 'bar',
        barWidth: '25%',
        barMinHeight: 3,
        data: data,
        itemStyle: {
          color: '#5d7eeb',
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: '#7dd3fc'
          }
        }
      }
    ]
  }
})

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

  const totalApplicationCount = stats.totalApplicationCount || 0;
  const applicationCountLastMonth = stats.applicationCountLastMonth || 0;
  const applicationCountLast3Months = stats.applicationCountLast3Months || 0;
  const applicationCountLast6Months = stats.applicationCountLast6Months || 0;

  // 没有申请记录 -> 100分（无借贷行为）
  if (totalApplicationCount === 0) {
    return 100;
  }

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

  // 近1个月申请机构数
  if (applicationCountLastMonth >= 10) {
    score -= 40; // 极高频率申请
  } else if (applicationCountLastMonth >= 5) {
    score -= 30; // 高频率申请
  } else if (applicationCountLastMonth >= 3) {
    score -= 20; // 中高频率申请
  } else if (applicationCountLastMonth > 0) {
    score -= 10; // 有申请
  }

  // 近3个月申请机构数
  if (applicationCountLast3Months >= 20) {
    score -= 30; // 极高频率申请
  } else if (applicationCountLast3Months >= 10) {
    score -= 20; // 高频率申请
  } else if (applicationCountLast3Months >= 5) {
    score -= 10; // 中高频率申请
  }

  // 近6个月申请机构数
  if (applicationCountLast6Months >= 30) {
    score -= 20; // 极高频率申请
  } else if (applicationCountLast6Months >= 20) {
    score -= 15; // 高频率申请
  } else if (applicationCountLast6Months >= 10) {
    score -= 10; // 中高频率申请
  }

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

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

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

<style lang="scss" scoped>
.border-b:last-child {
  @apply border-b-0;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>
