<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/yqfx.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-[#1FBE5D]">
                {{ overdueRecord?.currentOverdueCount || 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]">
                {{ overdueRecord?.currentOverdueInstitution || '-' }}
              </div>
              <div class="text-sm text-gray-600 mt-1">当前逾期机构</div>
            </div>
          </div>
        </div>

        <!-- 逾期总体信息 -->
        <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-[#1FBE5D]">
                {{ overdueRecord?.totalOverdueAmount || '-' }}
              </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]">
                {{ overdueRecord?.lastOverdueDate || '-' }}
              </div>
              <div class="text-sm text-gray-600 mt-1">最近逾期时间</div>
            </div>
          </div>
        </div>

        <!-- 逾期统计汇总 -->
        <div class="mb-6">
          <LTitle title="逾期统计汇总" />

          <!-- 数据表格 -->
          <div class="mb-4 mt-4 border border-gray-200 rounded-lg overflow-hidden mx-4">
            <!-- 表头 -->
            <div class="bg-[#5d7eeb] text-white">
              <div class="grid grid-cols-4 text-sm">
                <div class="py-3 px-4 text-left font-semibold border-r border-white whitespace-nowrap">时间段</div>
                <div class="py-3 px-4 text-center font-semibold border-r border-white whitespace-nowrap">M0+笔数</div>
                <div class="py-3 px-4 text-center font-semibold border-r border-white whitespace-nowrap">M1+笔数</div>
                <div class="py-3 px-4 text-center font-semibold whitespace-nowrap">累计金额</div>
              </div>
            </div>

            <!-- 数据行 -->
            <div class="bg-white">
              <!-- 近6个月 -->
              <div class="grid grid-cols-4 border-b border-gray-200 text-sm">
                <div class="py-3 px-4 font-medium text-gray-800 border-r border-gray-200 whitespace-nowrap">近6个月</div>
                <div class="py-3 px-4 text-center text-[#333333] border-r border-gray-200 whitespace-nowrap">
                  {{ overdueRecord?.m0PlusCountLast6Months || 0 }} 笔
                </div>
                <div class="py-3 px-4 text-center text-[#333333] border-r border-gray-200 whitespace-nowrap">
                  {{ overdueRecord?.m1PlusCountLast6Months || 0 }} 笔
                </div>
                <div class="py-3 px-4 text-center text-[#333333] font-semibold whitespace-nowrap">
                  {{ overdueRecord?.totalAmountLast6Months || '-' }}
                </div>
              </div>

              <!-- 近12个月 -->
              <div class="grid grid-cols-4 border-b border-gray-200 text-sm">
                <div class="py-3 px-4 font-medium text-gray-800 border-r border-gray-200 whitespace-nowrap">近12个月</div>
                <div class="py-3 px-4 text-center text-[#333333] border-r border-gray-200 whitespace-nowrap">
                  {{ overdueRecord?.m0PlusCountLast12Months || 0 }} 笔
                </div>
                <div class="py-3 px-4 text-center text-[#333333] border-r border-gray-200 whitespace-nowrap">
                  {{ overdueRecord?.m1PlusCountLast12Months || 0 }} 笔
                </div>
                <div class="py-3 px-4 text-center text-[#333333] font-semibold whitespace-nowrap">
                  {{ overdueRecord?.totalAmountLast12Months || '-' }}
                </div>
              </div>

              <!-- 近24个月 -->
              <div class="grid grid-cols-4 text-sm">
                <div class="py-3 px-4 font-medium text-gray-800 border-r border-gray-200 whitespace-nowrap">近24个月</div>
                <div class="py-3 px-4 text-center text-[#333333] border-r border-gray-200 whitespace-nowrap">
                  {{ overdueRecord?.m0PlusCountLast24Months || 0 }} 笔
                </div>
                <div class="py-3 px-4 text-center text-[#333333] border-r border-gray-200 whitespace-nowrap">
                  {{ overdueRecord?.m1PlusCountLast24Months || 0 }} 笔
                </div>
                <div class="py-3 px-4 text-center text-[#333333] font-semibold whitespace-nowrap">
                  {{ overdueRecord?.totalAmountLast24Months || '-' }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 逾期笔数统计图表 -->
        <div class="mb-6">
          <LTitle title="逾期笔数统计" />

          <!-- M0+/M1+双柱状图 -->
          <div class="mb-4 h-64">
            <v-chart class="chart-container" :option="overdueCountBarChartOption" autoresize />
          </div>
        </div>

        <!-- 累计金额统计图表 -->
        <div class="mb-6">
          <LTitle title="累计金额统计" />

          <!-- 累计金额柱状图 -->
          <div class="mb-4 h-64">
            <v-chart class="chart-container" :option="overdueAmountBarChartOption" autoresize />
          </div>
        </div>

        <!-- 逾期风险警告 -->
        <div v-if="hasCurrentOverdue" class="mb-6">
          <div class="space-y-3 p-4">
            <div class="text-[#333333] font-bold text-sm">逾期风险提示</div>
            <div class="flex items-start">
              <div class="mr-3 mt-1">
                <img src="@/assets/images/report/zfx.png" alt="风险提示" class="w-6 h-6 object-contain" />
              </div>
              <div>
                <h4 class="font-semibold text-red-800 mb-2">当前逾期风险警告</h4>
                <p class="text-red-700 text-sm">
                  检测到当前存在逾期记录，存在较高的信用风险，建议谨慎处理。
                </p>
                <div class="mt-2">
                  <span class="text-red-800 font-medium">当前逾期：</span>
                  <span class="text-red-700">{{ overdueRecord?.currentOverdueCount || 0 }} 笔</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 历史逾期提示 -->
        <div v-else-if="hasHistoricalOverdue" class="mb-6">
          <div class="space-y-3 p-4 bg-yellow-100 border border-yellow-300 rounded-lg">
            <div class="flex items-start">
              <div class="mr-3 mt-1">
                <img src="@/assets/images/report/zfx.png" alt="风险提示" class="w-10 h-10 object-contain" />
              </div>
              <div>
                <h4 class="font-semibold text-gray-800 mb-2">历史逾期风险提示</h4>
                <p class="text-gray-400 text-sm">
                  存在历史逾期记录，需关注其还款意愿和能力。
                </p>
              </div>
            </div>
          </div>
        </div>

        <!-- 无逾期提示 -->
        <div v-if="!hasAnyOverdue" class="mb-6 mx-4">
          <div class="space-y-3 p-4 bg-[#ECF9EF] border border-[#CAECD3] rounded-lg">
            <div class="flex items-center">
              <div class="mr-3">
                <img src="@/assets/images/report/zq.png" alt="良好记录" class="w-10 h-10 object-contain" />
              </div>
              <div>
                <h4 class="font-semibold text-gray-800">逾期记录良好</h4>
                <p class="text-gray-400 text-sm">
                  未检测到逾期记录，信用表现良好。
                </p>
              </div>
            </div>
          </div>
        </div>

        <!-- 逾期等级说明 -->
        <div class="mb-6">
          <div class="space-y-2 p-4">
            <div class="font-bold text-sm">逾期等级说明</div>
            <div class="flex justify-between items-center">
              <span class="text-gray-600  text-sm">M0+</span>
              <span class="text-[#333333] font-bold text-md">逾期1-29天</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-gray-600  text-sm">M1+</span>
              <span class="text-[#333333] font-bold">逾期30天以上</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-gray-600  text-sm">当前逾期</span>
              <span class="text-[#333333] font-bold">尚未结清的逾期订单</span>
            </div>
          </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 VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { useRiskNotifier } from '@/composables/useRiskNotifier'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'

// 注册ECharts组件
use([
  CanvasRenderer,
  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 overdueRecord = computed(() => {
  return props.data?.overdueRecord || {}
})

// 是否有当前逾期
const hasCurrentOverdue = computed(() => {
  return (overdueRecord.value?.currentOverdueCount || 0) > 0
})

// 是否有历史逾期
const hasHistoricalOverdue = computed(() => {
  const record = overdueRecord.value || {}
  return (record.m0PlusCountLast24Months || 0) > 0 ||
    (record.m1PlusCountLast24Months || 0) > 0
})

// 是否有任何逾期记录
const hasAnyOverdue = computed(() => {
  return hasCurrentOverdue.value || hasHistoricalOverdue.value
})

// 当前逾期颜色
const getCurrentOverdueColor = computed(() => {
  const count = overdueRecord.value?.currentOverdueCount || 0
  if (count > 0) return 'text-red-600'
  return 'text-green-600'
})

// 获取逾期次数颜色
const getOverdueCountColor = (count) => {
  const num = count || 0
  if (num === 0) return 'text-green-600'
  if (num <= 2) return 'text-yellow-600'
  if (num <= 5) return 'text-orange-600'
  return 'text-red-600'
}

// 解析金额区间字符串
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
}

// M0+/M1+逾期笔数双柱状图配置
const overdueCountBarChartOption = computed(() => {
  const m0Data = [
    overdueRecord.value?.m0PlusCountLast6Months || 0,
    overdueRecord.value?.m0PlusCountLast12Months || 0,
    overdueRecord.value?.m0PlusCountLast24Months || 0
  ]

  const m1Data = [
    overdueRecord.value?.m1PlusCountLast6Months || 0,
    overdueRecord.value?.m1PlusCountLast12Months || 0,
    overdueRecord.value?.m1PlusCountLast24Months || 0
  ]

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        let result = params[0].name + '<br/>'
        params.forEach(item => {
          result += `${item.seriesName}: ${item.value} 笔<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['M0+笔数', 'M1+笔数'],
      top: '5%',
      textStyle: {
        fontSize: 12
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '20%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['近6个月', '近12个月', '近24个月'],
      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: 'M0+笔数',
        type: 'bar',
        data: m0Data,
        barWidth: '25%',
        barMinHeight: 3,
        itemStyle: {
          color: '#2B79EE',
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: '#1e5bb8'
          }
        }
      },
      {
        name: 'M1+笔数',
        type: 'bar',
        data: m1Data,
        barWidth: '25%',
        barMinHeight: 3,
        itemStyle: {
          color: '#61D2F4',
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: '#4bb8d4'
          }
        }
      }
    ]
  }
})

// 累计金额柱状图配置
const overdueAmountBarChartOption = computed(() => {
  const amountData = [
    parseAmountRange(overdueRecord.value?.totalAmountLast6Months),
    parseAmountRange(overdueRecord.value?.totalAmountLast12Months),
    parseAmountRange(overdueRecord.value?.totalAmountLast24Months)
  ]

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        const originalAmounts = [
          overdueRecord.value?.totalAmountLast6Months || '-',
          overdueRecord.value?.totalAmountLast12Months || '-',
          overdueRecord.value?.totalAmountLast24Months || '-'
        ]
        const index = params[0].dataIndex
        return `${params[0].name}: ${originalAmounts[index]}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['近6个月', '近12个月', '近24个月'],
      axisLabel: {
        fontSize: 11,
        color: '#6b7280'
      },
      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 record = overdueRecord.value || {};

  const currentOverdueCount = record.currentOverdueCount || 0;
  const m0PlusCountLast6Months = record.m0PlusCountLast6Months || 0;
  const m1PlusCountLast6Months = record.m1PlusCountLast6Months || 0;
  const m0PlusCountLast12Months = record.m0PlusCountLast12Months || 0;
  const m1PlusCountLast12Months = record.m1PlusCountLast12Months || 0;
  const m0PlusCountLast24Months = record.m0PlusCountLast24Months || 0;
  const m1PlusCountLast24Months = record.m1PlusCountLast24Months || 0;

  // 没有逾期记录 -> 100分
  if (currentOverdueCount === 0 &&
    m0PlusCountLast6Months === 0 && m1PlusCountLast6Months === 0 &&
    m0PlusCountLast12Months === 0 && m1PlusCountLast12Months === 0 &&
    m0PlusCountLast24Months === 0 && m1PlusCountLast24Months === 0) {
    return 100;
  }

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

  // 当前逾期笔数（最重要）
  if (currentOverdueCount >= 5) {
    score -= 50; // 当前逾期5笔以上
  } else if (currentOverdueCount >= 3) {
    score -= 40; // 当前逾期3-4笔
  } else if (currentOverdueCount >= 1) {
    score -= 30; // 当前逾期1-2笔
  }

  // 近6个月M1+逾期（严重逾期）
  if (m1PlusCountLast6Months >= 5) {
    score -= 30; // 严重逾期5笔以上
  } else if (m1PlusCountLast6Months >= 3) {
    score -= 20; // 严重逾期3-4笔
  } else if (m1PlusCountLast6Months >= 1) {
    score -= 10; // 严重逾期1-2笔
  }

  // 近6个月M0+逾期（轻微逾期）
  if (m0PlusCountLast6Months >= 10) {
    score -= 20; // 轻微逾期10笔以上
  } else if (m0PlusCountLast6Months >= 5) {
    score -= 15; // 轻微逾期5-9笔
  } else if (m0PlusCountLast6Months >= 3) {
    score -= 10; // 轻微逾期3-4笔
  } else if (m0PlusCountLast6Months >= 1) {
    score -= 5; // 轻微逾期1-2笔
  }

  // 近12个月M1+逾期
  if (m1PlusCountLast12Months >= 10) {
    score -= 20; // 严重逾期10笔以上
  } else if (m1PlusCountLast12Months >= 5) {
    score -= 15; // 严重逾期5-9笔
  } else if (m1PlusCountLast12Months >= 3) {
    score -= 10; // 严重逾期3-4笔
  } else if (m1PlusCountLast12Months >= 1) {
    score -= 5; // 严重逾期1-2笔
  }

  // 近24个月M1+逾期
  if (m1PlusCountLast24Months >= 20) {
    score -= 15; // 严重逾期20笔以上
  } else if (m1PlusCountLast24Months >= 10) {
    score -= 10; // 严重逾期10-19笔
  } else if (m1PlusCountLast24Months >= 5) {
    score -= 5; // 严重逾期5-9笔
  }

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

table {
  border-collapse: collapse;

  th,
  td {
    border: 1px solid #e5e7eb;
  }

  th {
    background-color: #f9fafb;
  }

  tr:hover {
    background-color: #f9fafb;
  }
}
</style>
