<template>
  <div class="rounded-lg border border-[#99999933]">
    <div class="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/xypf2.png" alt="信用评分" class="w-8 h-8 object-contain" />
        </div>
        <span class="font-bold text-gray-800">信用评分</span>
      </div>

      <div class="pb-4">
        <!-- 综合信用指数 -->
        <div class="mb-6">
          <LTitle title="综合信用指数" class="mb-2" />
          <p class="text-gray-400 text-sm mb-4 px-4">基于多维度风险评估的综合评分</p>

          <!-- 信用分仪表盘 -->
          <div class="flex flex-col items-center mb-4">
            <div ref="chartRef" :style="{ width: '100%', height: '200px' }"></div>
            <div class="text-center mt-[-14px]">
              <div class=" text-[#999999]">评分范围: 150-1000</div>
              <div class="px-10 py-1 rounded-full font-medium inline-block mt-2" :class="getCreditScoreBadgeClass()">
                {{ getCreditScoreLevel() }}
              </div>
            </div>
          </div>

          <!-- 详细指标 -->
          <div class="space-y-3 px-4 ">
            <div class="bg-green-50 rounded-lg p-4 border border-green-200">
              <div class="flex items-start">
                <img src="@/assets/images/report/zq.png" alt="信用风险评分"
                  class="w-10 h-10 object-contain mr-4 flex-shrink-0" />
                <div class="flex-1">
                  <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-medium text-gray-800">信用风险评分</span>
                    <span class="text-sm font-bold" :class="getScoreTextClass()">{{ (creditRiskScore * 100).toFixed(0)
                      }}%</span>
                  </div>
                  <div class="h-2" :style="`background-color: ${getLightScoreColor()}`">
                    <div class="h-2 transition-all duration-500"
                      :style="`width: ${Math.max(creditRiskScore * 100, 2)}%; background-color: ${getScoreColor()}`">
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="bg-green-50 rounded-lg p-4 border border-green-200">
              <div class="flex items-start">
                <img src="@/assets/images/report/zq.png" alt="履约金额综合指数"
                  class="w-10 h-10 object-contain mr-4 flex-shrink-0" />
                <div class="flex-1">
                  <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-medium text-gray-800">履约金额综合指数</span>
                    <span class="text-sm font-bold" :class="getScoreTextClass()">{{ (amountComplianceIndex *
                      100).toFixed(0)
                      }}%</span>
                  </div>
                  <div class="h-2" :style="`background-color: ${getLightScoreColor()}`">
                    <div class="h-2 transition-all duration-500"
                      :style="`width: ${Math.max(amountComplianceIndex * 100, 2)}%; background-color: ${getScoreColor()}`">
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="bg-green-50 rounded-lg p-4 border border-green-200">
              <div class="flex items-start">
                <img src="@/assets/images/report/zq.png" alt="履约笔数综合指数"
                  class="w-10 h-10 object-contain mr-4 flex-shrink-0" />
                <div class="flex-1">
                  <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-medium text-gray-800">履约笔数综合指数</span>
                    <span class="text-sm font-bold" :class="getScoreTextClass()">{{ (countComplianceIndex *
                      100).toFixed(0)
                      }}%</span>
                  </div>
                  <div class="h-2" :style="`background-color: ${getLightScoreColor()}`">
                    <div class="h-2 transition-all duration-500"
                      :style="`width: ${Math.max(countComplianceIndex * 100, 2)}%; background-color: ${getScoreColor()}`">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 专业模型评分 -->
    <div class=" mb-4">
      <div class="">
        <LTitle title="专业模型评分" class="mb-2" />
        <p class="text-gray-400 text-sm mb-4 px-4">星耀Pro系列AI评分模型</p>

        <div class="space-y-3 px-4">
          <!-- 小额网贷分 V1 -->
          <div :class="getModelCardClass(highRiskScore)">
            <div class="flex items-center mb-2">
              <img :src="getModelIcon(highRiskScore)" alt="小额网贷分 V1"
                class="w-10 h-10 object-contain mr-3 flex-shrink-0" />
              <div class="flex-1">
                <div class="font-medium text-gray-800 mb-1">小额网贷分 V1</div>
                <div class="text-sm text-gray-600">针对小额网贷风险评估</div>
              </div>
            </div>
            <div class="text-sm text-gray-600 ml-[52px]">评分: <span class="font-bold">350-950</span></div>
            <div class="absolute top-0 right-0 bg-[#999999] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
              {{ formatModelScore(highRiskScore) }}
            </div>
          </div>

          <!-- 小额分期分 V1 -->
          <div :class="getModelCardClass(midRiskScore)">
            <div class="flex items-center mb-2">
              <img :src="getModelIcon(midRiskScore)" alt="小额分期分 V1"
                class="w-10 h-10 object-contain mr-3 flex-shrink-0" />
              <div class="flex-1">
                <div class="font-medium text-gray-800 mb-1">小额分期分 V1</div>
                <div class="text-sm text-gray-600">针对小额分期产品评估</div>
              </div>
            </div>
            <div class="text-sm text-gray-600 ml-[52px]">评分: <span class="font-bold">350-950</span></div>
            <div class="absolute top-0 right-0 bg-[#999999] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
              {{ formatModelScore(midRiskScore) }}
            </div>
          </div>

          <!-- 中大额分期分 V1 -->
          <div :class="getModelCardClass(lowRiskScore)">
            <div class="flex items-center mb-2">
              <img :src="getModelIcon(lowRiskScore)" alt="中大额分期分 V1"
                class="w-10 h-10 object-contain mr-3 flex-shrink-0" />
              <div class="flex-1">
                <div class="font-medium text-gray-800 mb-1">中大额分期分 V1</div>
                <div class="text-sm text-gray-600">针对中大额分期产品评估</div>
              </div>
            </div>
            <div class="text-sm text-gray-600 ml-[52px]">评分: <span class="font-bold">350-950</span></div>
            <div class="absolute top-0 right-0 bg-[#999999] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
              {{ formatModelScore(lowRiskScore) }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 还款表现指标 -->
    <div class="mb-8">
      <div class="">
        <LTitle title="还款表现指标" class="mb-2" />
        <p class="text-gray-400 text-sm mb-4 px-4">近期还款成功率统计</p>

        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3 px-4">
          <!-- 近5次 -->
          <div class="bg-[#ECF9EF] rounded-lg p-3 border border-[#91D69F]">
            <div class="flex flex-col items-center justify-center h-full w-full">
              <div class="flex flex-col items-center justify-center w-full h-full text-center">
                <div class="text-lg text-[#999999] mt-1">金额: <span class="font-bold text-green-600 text-2xl">{{
  (recent5AmountRatio * 100).toFixed(0) }}</span> %</div>
                <div class="font-medium text-[#666666] mb-2">近5次</div>
              </div>

            </div>
          </div>

          <!-- 近20次 -->
          <div class="bg-[#ECF9EF] rounded-lg p-3 border border-[#91D69F]">
            <div class="flex flex-col items-center justify-center h-full w-full">
              <div class="flex flex-col items-center justify-center w-full h-full text-center">
                <div class="text-lg text-[#999999] mt-1">小贷: <span class="font-bold text-green-600 text-2xl">{{
                  (recent20SmallLoanRatio * 100).toFixed(0) }}</span> %</div>
                <div class="font-medium text-[#666666] mb-2">近20次</div>
              </div>
            </div>
          </div>

          <!-- 近90天 -->
          <div class="bg-[#ECF9EF] rounded-lg p-3 border border-[#91D69F]">
            <div class="flex flex-col items-center justify-center h-full w-full">
              <div class="flex flex-col items-center justify-center w-full h-full text-center">
                <div class="text-lg text-[#999999] mt-1">金额: <span class="font-bold text-green-600 text-2xl">{{
                  (recent90AmountRatio * 100).toFixed(0) }}</span> %</div>
                <div class="font-medium text-[#666666] mb-2">近90天</div>
              </div>
            </div>
          </div>

          <!-- 近50次 -->
          <div class="bg-[#ECF9EF] rounded-lg p-3 border border-[#91D69F]">
            <div class="flex flex-col items-center justify-center h-full w-full">
              <div class="flex flex-col items-center justify-center w-full h-full text-center">
                <div class="text-lg text-[#999999] mt-1">成功率: <span class="font-bold text-green-600 text-2xl">{{
                  (recent50PaymentRatio * 100).toFixed(0) }}</span> %</div>
                <div class="font-medium text-[#666666] mb-2">近50次</div>
              </div>
            </div>
          </div>

          <!-- 近100次 -->
          <div class="bg-[#ECF9EF] rounded-lg p-3 border border-[#91D69F]">
            <div class="flex flex-col items-center justify-center h-full w-full">
              <div class="flex flex-col items-center justify-center w-full h-full text-center">
                <div class="text-lg text-[#999999] mt-1">成功率: <span class="font-bold text-green-600 text-2xl">{{
                  (recent100PaymentRatio * 100).toFixed(0) }}</span> %</div>
                <div class="font-medium text-[#666666] mb-2">近100次</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="信用评分系统基于多维度数据建立的综合信用评估模型，提供综合信用指数、分类信用评分和信用等级分析。评分范围为0-1000分，分数越高代表信用状况越好。系统会根据还款表现、借贷历史、负债情况等因素进行评分。建议结合具体业务场景设定信用门槛，并定期更新评分模型以提高预测准确性。" />
</template>

<script>
import LTitle from '@/components/LTitle.vue'
import LRemark from '@/components/LRemark.vue'
import * as echarts from 'echarts'

export default {
  name: 'CreditScores',
  components: {
    LTitle,
    LRemark
  },
  props: {
    data: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      chartInstance: null
    }
  },
  computed: {
    creditRiskScore() {
      return parseFloat(this.data.xyp_cpl0081) || 0
    },
    amountComplianceIndex() {
      return parseFloat(this.data.xyp_cpl0082) || 0
    },
    countComplianceIndex() {
      return parseFloat(this.data.xyp_cpl0083) || 0
    },

    // 模型评分
    highRiskScore() {
      const score = parseInt(this.data.xyp_model_score_high)
      return isNaN(score) || score === -1 ? null : score
    },
    midRiskScore() {
      const score = parseInt(this.data.xyp_model_score_mid)
      return isNaN(score) || score === -1 ? null : score
    },
    lowRiskScore() {
      const score = parseInt(this.data.xyp_model_score_low)
      return isNaN(score) || score === -1 ? null : score
    },

    // 综合信用评分计算
    creditScoreDisplay() {
      const avgRisk = (this.creditRiskScore + this.amountComplianceIndex + this.countComplianceIndex) / 3
      // 风险越高，信用分越低
      return Math.round((1 - avgRisk) * 850 + 150)
    },

    creditScoreColor() {
      if (this.creditScoreDisplay >= 750) return '#1FBE5D'
      if (this.creditScoreDisplay >= 650) return '#f59e0b'
      return '#ef4444'
    },

    // 还款比例计算
    recent5PaymentRatio() {
      return parseFloat(this.data.xyp_cpl0074) || 0
    },
    recent5AmountRatio() {
      return parseFloat(this.data.xyp_cpl0073) || 0
    },
    recent20PaymentRatio() {
      return parseFloat(this.data.xyp_t0400002) || 0
    },
    recent20SmallLoanRatio() {
      return parseFloat(this.data.xyp_cpl0075) || 0
    },
    recent90DayRatio() {
      return parseFloat(this.data.xyp_cpl0080) || 0
    },
    recent90AmountRatio() {
      return parseFloat(this.data.xyp_cpl0079) || 0
    },
    recent50PaymentRatio() {
      return parseFloat(this.data.xyp_t0400003) || 0
    },
    recent100PaymentRatio() {
      return parseFloat(this.data.xyp_t0400004) || 0
    }
  },

  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },

  beforeUnmount() {
    if (this.chartInstance) {
      this.chartInstance.dispose()
      this.chartInstance = null
    }
    window.removeEventListener('resize', this.handleResize)
  },

  watch: {
    creditScoreDisplay() {
      this.updateChart()
    }
  },

  methods: {
    initChart() {
      if (!this.$refs.chartRef) return
      this.chartInstance = echarts.init(this.$refs.chartRef)
      this.updateChart()
    },

    updateChart() {
      if (!this.chartInstance) return

      const scoreColor = this.creditScoreColor
      const gradientColors = this.getGradientColors()

      const option = {
        series: [
          {
            type: 'gauge',
            startAngle: 180,
            endAngle: 0,
            min: 150,
            max: 1000,
            radius: '100%',
            center: ['50%', '80%'],
            itemStyle: {
              color: scoreColor,
              shadowBlur: 6,
              shadowColor: scoreColor
            },
            progress: {
              show: true,
              width: 20,
              roundCap: true,
              clip: false
            },
            axisLine: {
              roundCap: true,
              lineStyle: {
                width: 20,
                color: [
                  [1, new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    { offset: 0, color: scoreColor + '30' },
                    { offset: 1, color: scoreColor + '25' }
                  ])]
                ]
              }
            },
            axisTick: {
              show: true,
              distance: -30,
              length: 6,
              splitNumber: 10,
              lineStyle: {
                color: scoreColor,
                width: 1,
                opacity: 0.5
              }
            },
            splitLine: {
              show: true,
              distance: -36,
              length: 12,
              splitNumber: 9,
              lineStyle: {
                color: scoreColor,
                width: 2,
                opacity: 0.5
              }
            },
            axisLabel: {
              show: false
            },
            anchor: {
              show: false
            },
            pointer: {
              show: false
            },
            detail: {
              valueAnimation: true,
              fontSize: 30,
              fontWeight: 'bold',
              color: scoreColor,
              offsetCenter: [0, 0],
              formatter: (value) => {
                return `{value|${value}}{label|信用分}`
              },
              rich: {
                value: {
                  fontSize: 30,
                  fontWeight: 'bold',
                  color: scoreColor,
                  padding: [0, 0, 5, 10]
                },
                label: {
                  fontSize: 14,
                  fontWeight: 'normal',
                  color: scoreColor,
                  padding: [0, 0, 0, 5]
                }
              }
            },
            data: [
              {
                value: this.creditScoreDisplay
              }
            ]
          }
        ]
      }

      this.chartInstance.setOption(option)
    },

    getGradientColors() {
      const color = this.creditScoreColor
      return [
        { offset: 0, color: color },
        { offset: 1, color: this.lightenColor(color, 0.3) }
      ]
    },

    lightenColor(color, amount) {
      const num = parseInt(color.replace('#', ''), 16)
      const r = Math.min(255, (num >> 16) + amount * 255)
      const g = Math.min(255, ((num >> 8) & 0x00ff) + amount * 255)
      const b = Math.min(255, (num & 0x0000ff) + amount * 255)
      return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, '0')}`
    },

    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize()
      }
    },

    formatModelScore(score) {
      return score === null ? '未命中' : score.toString()
    },

    getScoreClass(score) {
      if (score === null) return 'text-gray-400'
      if (score >= 750) return 'text-green-600'
      if (score >= 650) return 'text-yellow-600'
      return 'text-red-600'
    },

    getScoreTextClass() {
      if (this.creditScoreDisplay >= 750) return 'text-green-600'
      if (this.creditScoreDisplay >= 650) return 'text-yellow-600'
      return 'text-red-600'
    },

    getScoreColor() {
      return this.creditScoreColor
    },

    getLightScoreColor() {
      const color = this.creditScoreColor
      // 将颜色转换为淡色版本（增加透明度）
      if (color === '#1FBE5D') return '#E8F8F0' // 绿色淡色
      if (color === '#f59e0b') return '#FEF3C7' // 黄色淡色
      if (color === '#ef4444') return '#FEE2E2' // 红色淡色
      return '#F3F4F6' // 默认灰色
    },

    getModelIcon(score) {
      // 如果分数为null或未命中，返回灰色图标
      if (score === null) {
        return new URL('@/assets/images/report/wmz.png', import.meta.url).href
      }
      // 如果命中，返回绿色图标
      return new URL('@/assets/images/report/zq.png', import.meta.url).href
    },

    getModelCardClass(score) {
      // 如果分数为null或未命中，返回未命中样式
      if (score === null) {
        return 'bg-[#F0F0F0] rounded-lg p-4 border border-[#D4D4D4] relative'
      }
      // 如果命中，返回默认样式
      return 'bg-gray-50 rounded-lg p-4 border border-gray-200 relative'
    },

    getCircleStyle(ratio) {
      let color = '#ef4444'
      if (ratio >= 0.8) color = '#10b981'
      else if (ratio >= 0.6) color = '#f59e0b'

      // 确保至少显示10度，让用户知道是图表
      const minDegree = 10
      const actualDegree = Math.max(ratio * 360, minDegree)

      return {
        background: `conic-gradient(${color} ${actualDegree}deg, #e5e7eb 0deg)`
      }
    },

    getCreditScoreLevel() {
      if (this.creditScoreDisplay >= 800) return '优秀'
      if (this.creditScoreDisplay >= 700) return '良好'
      if (this.creditScoreDisplay >= 600) return '一般'
      if (this.creditScoreDisplay >= 500) return '较差'
      return '很差'
    },

    getCreditScoreBadgeClass() {
      if (this.creditScoreDisplay >= 800) return 'bg-[#1FBE5D] text-white'
      if (this.creditScoreDisplay >= 700) return 'bg-blue-600 text-white'
      if (this.creditScoreDisplay >= 600) return 'bg-yellow-600 text-white'
      if (this.creditScoreDisplay >= 500) return 'bg-orange-600 text-white'
      return 'bg-red-600 text-white'
    }
  }
}
</script>

<style scoped>
/* 组件容器样式 */
.credit-scores {
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  border: 1px solid #e5e7eb;
  padding: 1.5rem;
  margin-bottom: 1.25rem;
  transition: all 0.3s ease;
}

.credit-scores:hover {
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  transform: translateY(-0.25rem);
}

.section-spacing {
  height: 1.25rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .credit-scores {
    padding: 1rem;
  }
}

@media (max-width: 480px) {
  .credit-scores {
    padding: 0.75rem;
  }
}
</style>
