<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/j24gyfkqk.png" alt="近24个月放款情况" class="w-8 h-8 object-contain" />
        </div>
        <span class="font-bold text-gray-800">近24个月放款情况</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">
                {{ lendingStatistics?.totalLendingInstitutionCount || 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]">
                {{ getTotalLendingStatus }}
              </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="institutionPieChartOption" autoresize />
          </div>
        </div>

        <!-- 放贷时间分布 -->
        <div class="mb-6">
          <LTitle title="放贷时间分布" />

          <!-- 柱状图展示 -->
          <div class="mb-4 h-64">
            <v-chart class="chart-container" :option="timeBarChartOption" 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">
                {{ lendingStatistics?.lendingCountLastMonth || 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">
                {{ lendingStatistics?.lendingCountLast3Months || 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">
                {{ lendingStatistics?.lendingCountLast6Months || 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">
                {{ lendingStatistics?.lendingCountLast12Months || 0 }}次
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近24个月放贷次数</span>
              <span class="text-[#333333] font-bold">
                {{ lendingStatistics?.lendingCountLast24Months || 0 }}次
              </span>
            </div>
          </div>
        </div>

        <!-- 放贷金额区间分布 -->
        <div class="">
          <LTitle title="放贷金额区间分布" />

          <!-- 柱状图展示 -->
          <div class="mb-4 h-64">
            <v-chart class="chart-container" :option="amountBarChartOption" 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">
                {{ lendingStatistics?.lendingAmountLastMonth || '-' }}
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近3个月放贷金额</span>
              <span class="text-[#333333] font-bold">
                {{ formatAmountInterval(lendingStatistics?.lendingAmountLast3Months) }}
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近6个月放贷金额</span>
              <span class="text-[#333333] font-bold">
                {{ formatAmountInterval(lendingStatistics?.lendingAmountLast6Months) }}
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近12个月放贷金额</span>
              <span class="text-[#333333] font-bold">
                {{ formatAmountInterval(lendingStatistics?.lendingAmountLast12Months) }}
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近24个月放贷金额</span>
              <span class="text-[#333333] font-bold">
                {{ formatAmountInterval(lendingStatistics?.lendingAmountLast24Months) }}
              </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">
                {{ lendingStatistics?.lastLendingDate || '-' }}
              </span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">距离最近一次放款日期已有(天)</span>
              <span class="text-gray-800 font-bold">
                {{ formatDaysInterval(lendingStatistics?.daysSinceLastLending) }}
              </span>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="放款情况统计展示近24个月的放款数据，包括放款金额、放款笔数和放款机构数等关键指标。数据按月度统计，可以反映申请人的借贷需求变化和资金使用情况。放款金额和频率的变化趋势可以帮助评估申请人的财务状况和还款能力。建议关注放款集中度、单笔大额放款和放款机构的多样化程度。" />
</template>

<script setup>
import { computed } from 'vue'
import LTitle from '@/components/LTitle.vue'
import LRemark from '@/components/LRemark.vue'
import { formatAmountInterval, 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 lendingStatistics = computed(() => {
  return props.data?.lendingStatistics || {}
})

// 是否有放款记录
const hasAnyLending = computed(() => {
  return (lendingStatistics.value?.totalLendingInstitutionCount || 0) > 0
})

// 是否有金额信息
const hasAmountInfo = computed(() => {
  const stats = lendingStatistics.value || {}
  return stats.lendingAmountLastMonth ||
    stats.lendingAmountLast3Months ||
    stats.lendingAmountLast6Months ||
    stats.lendingAmountLast12Months ||
    stats.lendingAmountLast24Months
})

// 是否有最近放款信息（保留用于其他逻辑，但模块始终显示）
const hasLastLendingInfo = computed(() => {
  const stats = lendingStatistics.value || {}
  return stats.lastLendingDate || stats.daysSinceLastLending
})

// 是否有高频放款风险
const hasHighFrequencyLending = computed(() => {
  const lastMonth = lendingStatistics.value?.lendingCountLastMonth || 0
  const last3Months = lendingStatistics.value?.lendingCountLast3Months || 0

  // 近1个月放款超过5次或近3个月放款超过10次视为高频
  return lastMonth > 5 || last3Months > 10
})

// 总放款状态
const getTotalLendingStatus = computed(() => {
  const total = lendingStatistics.value?.totalLendingInstitutionCount || 0
  if (total === 0) return '无放款'
  if (total >= 5) return '多机构'
  if (total >= 3) return '中等'
  return '少量'
})

// 总放款颜色
const getTotalLendingColor = computed(() => {
  const total = lendingStatistics.value?.totalLendingInstitutionCount || 0
  if (total === 0) return 'text-green-600'
  if (total >= 5) return 'text-red-600'
  if (total >= 3) return 'text-orange-600'
  return 'text-blue-600'
})

// 机构类型分布饼图配置
const institutionPieChartOption = computed(() => {
  const installmentCount = lendingStatistics.value?.installmentLendingInstitutionCount || 0
  const onlineCount = lendingStatistics.value?.onlineLendingInstitutionCount || 0

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

// 时间分布柱状图配置
const timeBarChartOption = computed(() => {
  const data = [
    lendingStatistics.value?.lendingCountLastMonth || 0,
    lendingStatistics.value?.lendingCountLast3Months || 0,
    lendingStatistics.value?.lendingCountLast6Months || 0,
    lendingStatistics.value?.lendingCountLast12Months || 0,
    lendingStatistics.value?.lendingCountLast24Months || 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个月', '近24个月'],
      axisLabel: {
        fontSize: 10,
        color: '#6b7280',
        rotate: 45
      },
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 11,
        color: '#6b7280',
        formatter: '{value} 次'
      },
      splitLine: {
        lineStyle: {
          color: '#f3f4f6'
        }
      }
    },
    series: [
      {
        name: '放贷次数',
        type: 'bar',
        data: data,
        barWidth: '25%',
        barMinHeight: 3,
        itemStyle: {
          color: '#5d7eeb',
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: '#7dd3fc'
          }
        }
      }
    ]
  }
})

// 解析金额区间字符串，转换为数值用于图表展示
const parseAmountRange = (amountStr) => {
  if (!amountStr || amountStr === '-') return 0

  // 提取数字，取区间中点值
  const matches = amountStr.match(/(\d+(?:\.\d+)?)/g)
  if (!matches) return 0

  if (matches.length === 1) {
    return parseFloat(matches[0])
  } else if (matches.length >= 2) {
    // 取区间中点
    const min = parseFloat(matches[0])
    const max = parseFloat(matches[1])
    return (min + max) / 2
  }

  return 0
}

// 金额区间柱状图配置
const amountBarChartOption = computed(() => {
  const amountData = [
    parseAmountRange(lendingStatistics.value?.lendingAmountLastMonth),
    parseAmountRange(lendingStatistics.value?.lendingAmountLast3Months),
    parseAmountRange(lendingStatistics.value?.lendingAmountLast6Months),
    parseAmountRange(lendingStatistics.value?.lendingAmountLast12Months),
    parseAmountRange(lendingStatistics.value?.lendingAmountLast24Months)
  ]

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        const originalAmount = [
          lendingStatistics.value?.lendingAmountLastMonth || '-',
          lendingStatistics.value?.lendingAmountLast3Months || '-',
          lendingStatistics.value?.lendingAmountLast6Months || '-',
          lendingStatistics.value?.lendingAmountLast12Months || '-',
          lendingStatistics.value?.lendingAmountLast24Months || '-'
        ]
        const index = params[0].dataIndex
        return `${params[0].name}: ${originalAmount[index]}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['近1个月', '近3个月', '近6个月', '近12个月', '近24个月'],
      axisLabel: {
        fontSize: 10,
        color: '#6b7280',
        rotate: 45
      },
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 11,
        color: '#6b7280',
        formatter: function (value) {
          if (value >= 10) return value + '万'
          if (value >= 1) return value + '万'
          return value
        }
      },
      splitLine: {
        lineStyle: {
          color: '#f3f4f6'
        }
      }
    },
    series: [
      {
        name: '放贷金额',
        type: 'bar',
        data: amountData,
        barWidth: '25%',
        barMinHeight: 3,
        itemStyle: {
          color: '#5d7eeb',
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: '#7dd3fc'
          }
        }
      }
    ]
  }
})

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

  const totalLendingInstitutionCount = stats.totalLendingInstitutionCount || 0;
  const lendingCountLastMonth = stats.lendingCountLastMonth || 0;
  const lendingCountLast3Months = stats.lendingCountLast3Months || 0;
  const lendingCountLast6Months = stats.lendingCountLast6Months || 0;

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

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

  // 近1个月放款次数
  if (lendingCountLastMonth >= 10) {
    score -= 35; // 极高频率放款
  } else if (lendingCountLastMonth >= 5) {
    score -= 25; // 高频率放款
  } else if (lendingCountLastMonth >= 3) {
    score -= 15; // 中高频率放款
  } else if (lendingCountLastMonth > 0) {
    score -= 8; // 有放款
  }

  // 近3个月放款次数
  if (lendingCountLast3Months >= 20) {
    score -= 25; // 极高频率放款
  } else if (lendingCountLast3Months >= 10) {
    score -= 18; // 高频率放款
  } else if (lendingCountLast3Months >= 5) {
    score -= 10; // 中高频率放款
  }

  // 近6个月放款次数
  if (lendingCountLast6Months >= 30) {
    score -= 15; // 极高频率放款
  } else if (lendingCountLast6Months >= 20) {
    score -= 10; // 高频率放款
  } else if (lendingCountLast6Months >= 10) {
    score -= 5; // 中高频率放款
  }

  // 确保分数在合理范围内
  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>
