<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/lyqk.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]">
                {{ performanceStatistics?.settledLoanOrderCount || 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]">
                {{ performanceStatistics?.creditLoanDuration || 0 }}
              </div>
              <div class="text-sm text-gray-600 mt-1">信用贷款时长</div>
            </div>
          </div>
        </div>

        <!-- 还款质量 -->
        <div v-if="performanceStatistics?.normalRepaymentRatio" class="mb-6">
          <LTitle title="还款质量" />
          <div class="grid grid-cols-1 gap-4 p-4">
            <div class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-3xl font-bold text-[#1FBE5D] mb-2">
                {{ performanceStatistics.normalRepaymentRatio }}
              </div>
              <div class="text-sm text-gray-600">正常还款占总订单比例</div>
            </div>
          </div>
        </div>

        <!-- 履约次数统计 -->
        <div class="mb-6">
          <LTitle title="履约次数统计" />

          <!-- 柱状图展示 -->
          <div class="mb-4 h-64">
            <v-chart class="chart-container" :option="performanceBarChartOption" 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">
                {{ performanceStatistics?.performanceCountLastMonth || 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">
                {{ performanceStatistics?.performanceCountLast3Months || 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">
                {{ performanceStatistics?.performanceCountLast6Months || 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">
                {{ performanceStatistics?.performanceCountLast12Months || 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">
                {{ performanceStatistics?.performanceCountLast24Months || 0 }}次
              </span>
            </div>
          </div>
        </div>

        <!-- 履约金额区间 -->
        <div v-if="hasAmountInfo" class="mb-6">
          <LTitle title="履约金额区间" />
          <div class="space-y-2 p-4">
            <div v-if="performanceStatistics?.performanceAmountLastMonth"
              class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近1个月履约金额</span>
              <span class="text-[#333333] font-bold">
                {{ performanceStatistics.performanceAmountLastMonth }}
              </span>
            </div>
            <div v-if="performanceStatistics?.performanceAmountLast3Months"
              class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近3个月履约金额</span>
              <span class="text-[#333333] font-bold">
                {{ formatAmountInterval(performanceStatistics.performanceAmountLast3Months) }}
              </span>
            </div>
            <div v-if="performanceStatistics?.performanceAmountLast6Months"
              class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近6个月履约金额</span>
              <span class="text-[#333333] font-bold">
                {{ formatAmountInterval(performanceStatistics.performanceAmountLast6Months) }}
              </span>
            </div>
            <div v-if="performanceStatistics?.performanceAmountLast12Months"
              class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近12个月履约金额</span>
              <span class="text-[#333333] font-bold">
                {{ formatAmountInterval(performanceStatistics.performanceAmountLast12Months) }}
              </span>
            </div>
            <div v-if="performanceStatistics?.performanceAmountLast24Months"
              class="flex justify-between items-center text-sm">
              <span class="text-gray-600">近24个月履约金额</span>
              <span class="text-[#333333] font-bold">
                {{ formatAmountInterval(performanceStatistics.performanceAmountLast24Months) }}
              </span>
            </div>
          </div>
        </div>

        <!-- 还款异常统计 -->
        <div class="">
          <LTitle title="还款异常统计" />

          <!-- 柱状图展示 -->
          <div class="mb-4 h-64">
            <v-chart class="chart-container" :option="exceptionBarChartOption" 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">
                {{ performanceStatistics?.repaymentExceptionCountLastMonth || 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">
                {{ performanceStatistics?.repaymentExceptionCountLast3Months || 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">
                {{ performanceStatistics?.repaymentExceptionCountLast6Months || 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">
                {{ performanceStatistics?.repaymentExceptionCountLast12Months || 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">
                {{ performanceStatistics?.repaymentExceptionCountLast24Months || 0 }}次
              </span>
            </div>
          </div>
        </div>

        <!-- 最近履约信息 -->
        <div v-if="performanceStatistics?.daysSinceLastPerformance" class="mb-6">
          <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">
                {{ formatDaysInterval(performanceStatistics.daysSinceLastPerformance) }}
              </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 { 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 { 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 performanceStatistics = computed(() => {
  return props.data?.performanceStatistics || {}
})

// 是否有金额信息
const hasAmountInfo = computed(() => {
  const stats = performanceStatistics.value || {}
  return stats.performanceAmountLastMonth ||
    stats.performanceAmountLast3Months ||
    stats.performanceAmountLast6Months ||
    stats.performanceAmountLast12Months ||
    stats.performanceAmountLast24Months
})

// 是否有高异常率
const hasHighExceptionRate = computed(() => {
  const stats = performanceStatistics.value || {}
  const lastMonth = stats.repaymentExceptionCountLastMonth || 0
  const last3Months = stats.repaymentExceptionCountLast3Months || 0

  return lastMonth > 2 || last3Months > 5
})

// 是否有良好履约表现
const hasGoodPerformance = computed(() => {
  const stats = performanceStatistics.value || {}
  const settledCount = stats.settledLoanOrderCount || 0
  const totalExceptions = (stats.repaymentExceptionCountLast12Months || 0)

  return settledCount > 0 && totalExceptions <= 1
})

// 获取异常次数颜色
const getExceptionColor = (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 performanceBarChartOption = computed(() => {
  const data = [
    performanceStatistics.value?.performanceCountLastMonth || 0,
    performanceStatistics.value?.performanceCountLast3Months || 0,
    performanceStatistics.value?.performanceCountLast6Months || 0,
    performanceStatistics.value?.performanceCountLast12Months || 0,
    performanceStatistics.value?.performanceCountLast24Months || 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 exceptionBarChartOption = computed(() => {
  const data = [
    performanceStatistics.value?.repaymentExceptionCountLastMonth || 0,
    performanceStatistics.value?.repaymentExceptionCountLast3Months || 0,
    performanceStatistics.value?.repaymentExceptionCountLast6Months || 0,
    performanceStatistics.value?.repaymentExceptionCountLast12Months || 0,
    performanceStatistics.value?.repaymentExceptionCountLast24Months || 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'
          }
        }
      }
    ]
  }
})

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

  const settledLoanOrderCount = stats.settledLoanOrderCount || 0;
  const normalRepaymentRatio = stats.normalRepaymentRatio || '';
  const repaymentExceptionCountLastMonth = stats.repaymentExceptionCountLastMonth || 0;
  const repaymentExceptionCountLast3Months = stats.repaymentExceptionCountLast3Months || 0;
  const repaymentExceptionCountLast6Months = stats.repaymentExceptionCountLast6Months || 0;
  const repaymentExceptionCountLast12Months = stats.repaymentExceptionCountLast12Months || 0;

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

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

  // 正常还款率
  const ratioMatch = normalRepaymentRatio.match(/(\d+(?:\.\d+)?)/);
  if (ratioMatch) {
    const ratio = parseFloat(ratioMatch[1]);
    if (ratio < 50) {
      score -= 40; // 正常还款率低于50%
    } else if (ratio < 70) {
      score -= 30; // 正常还款率50-70%
    } else if (ratio < 85) {
      score -= 20; // 正常还款率70-85%
    } else if (ratio < 95) {
      score -= 10; // 正常还款率85-95%
    }
  }

  // 近1个月还款异常次数
  if (repaymentExceptionCountLastMonth >= 5) {
    score -= 30; // 极高异常率
  } else if (repaymentExceptionCountLastMonth >= 3) {
    score -= 20; // 高异常率
  } else if (repaymentExceptionCountLastMonth >= 1) {
    score -= 10; // 有异常
  }

  // 近3个月还款异常次数
  if (repaymentExceptionCountLast3Months >= 10) {
    score -= 25; // 极高异常率
  } else if (repaymentExceptionCountLast3Months >= 5) {
    score -= 15; // 高异常率
  } else if (repaymentExceptionCountLast3Months >= 2) {
    score -= 8; // 有异常
  }

  // 近6个月还款异常次数
  if (repaymentExceptionCountLast6Months >= 15) {
    score -= 20; // 极高异常率
  } else if (repaymentExceptionCountLast6Months >= 8) {
    score -= 12; // 高异常率
  } else if (repaymentExceptionCountLast6Months >= 3) {
    score -= 6; // 有异常
  }

  // 近12个月还款异常次数
  if (repaymentExceptionCountLast12Months >= 20) {
    score -= 15; // 极高异常率
  } else if (repaymentExceptionCountLast12Months >= 10) {
    score -= 10; // 高异常率
  } else if (repaymentExceptionCountLast12Months >= 5) {
    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>
