<template>
  <div class="">
    <div class="rounded-lg border border-[#99999933] mb-4">
      <div class="pb-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/dkxwfx.png" alt="贷款行为分析" class="w-8 h-8 object-contain" />
          </div>
          <span class="font-bold text-gray-800">贷款行为分析</span>
        </div>

        <!-- 机构类型分布 -->
        <div class="mb-6">
          <LTitle title="机构类型分布" class="mb-2" />
          <p class="text-gray-400 text-sm mb-4 px-4">不同类型贷款机构数量统计</p>

          <div class="space-y-3 px-4">
            <!-- 消费金融类 -->
            <div class="bg-[#ECF2FD] rounded-lg p-4 border border-[#CADAF9] relative">
              <div class="flex items-center">
                <div class="flex-1">
                  <div class="font-bold text-[#333333] mb-1">消费金融类</div>
                  <div class="text-sm text-[#999999]">有场景分期贷款</div>
                </div>
              </div>
              <div class="absolute top-0 right-0 bg-[#5079EA] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
                {{ formatMetricValue(consumerFinanceInstitutions) }} 家机构
              </div>
            </div>

            <!-- 小贷担保类 -->
            <div class="bg-[#ECF2FD] rounded-lg p-4 border border-[#CADAF9] relative">
              <div class="flex items-center">
                <div class="flex-1">
                  <div class="font-bold text-[#333333] mb-1">小贷担保类</div>
                  <div class="text-sm text-[#999999]">现金贷等小额贷款</div>
                </div>
              </div>
              <div class="absolute top-0 right-0 bg-[#5079EA] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
                {{ formatMetricValue(smallLoanInstitutions) }} 家机构
              </div>
            </div>

            <!-- 网络贷款类 -->
            <div class="bg-[#ECF2FD] rounded-lg p-4 border border-[#CADAF9] relative">
              <div class="flex items-center">
                <div class="flex-1">
                  <div class="font-bold text-[#333333] mb-1">网络贷款类</div>
                  <div class="text-sm text-[#999999]">网络现金贷</div>
                </div>
              </div>
              <div class="absolute top-0 right-0 bg-[#5079EA] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
                {{ formatMetricValue(networkLoanInstitutions) }} 家机构
              </div>
            </div>
          </div>
        </div>

        <!-- 还款表现统计 -->
        <div class="">
          <LTitle title="还款表现统计" class="mb-2" />
          <p class="text-gray-400 text-sm mb-4 px-4">历史还款成功与失败记录</p>

          <div class="space-y-3 px-4">
            <!-- 历史成功还款 -->
            <div class="bg-[#ECF9EF] rounded-lg p-4 border border-[#CAECD3] relative">
              <div class="flex items-center">
                <div class="flex-1">
                  <div class="font-bold text-[#333333] mb-1">历史成功还款</div>
                  <div class="text-sm text-[#999999]">成功还款记录</div>
                </div>
              </div>
              <div class="absolute top-0 right-0 bg-[#5EBC62] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
                {{ formatMetricValue(historicalSuccessPayments) }} 笔
              </div>
            </div>

            <!-- 历史交易失败 -->
            <div class="bg-[#F9ECEC] rounded-lg p-4 border border-[#F0CACA] relative">
              <div class="flex items-center">
                <div class="flex-1">
                  <div class="font-bold text-[#333333] mb-1">历史交易失败</div>
                  <div class="text-sm text-[#999999]">失败交易记录</div>
                </div>
              </div>
              <div class="absolute top-0 right-0 bg-[#D44643] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
                {{ formatMetricValue(historicalFailurePayments) }} 笔
              </div>
            </div>

            <!-- 整体成功率 -->
            <div class="bg-[#ECF2FD] rounded-lg p-4 border border-[#CADAF9] relative">
              <div class="flex items-center">
                <div class="flex-1">
                  <div class="font-bold text-[#333333] mb-1">整体成功率</div>
                  <div class="text-sm text-[#999999]">还款成功比例</div>
                </div>
              </div>
              <div class="absolute top-0 right-0 bg-[#5079EA] text-white px-2 py-1 rounded-bl-lg rounded-tr-lg text-xs">
                {{ overallSuccessRate }} %
              </div>
            </div>
          </div>
        </div>
      </div>


      <!-- 时间维度还款分析 -->
      <div class="mb-6">
        <LTitle title="时间维度还款分析" class="mb-2" />
        <p class="text-gray-400 text-sm mb-4 px-4">不同时间段的还款成功和失败统计</p>

        <!-- ECharts 图表 -->
        <div class="mb-6">
          <div ref="chartRef" :style="{ width: '100%', height: '300px' }"></div>
        </div>

        <!-- 标签页布局 -->
        <div class="">
          <div class="space-y-4">
            <div class="performance-item">
              <div class="loan-evaluation-wrap">
                <!-- 标签页 -->
                <div class="mb-3">
                  <van-tabs v-model:active="activeTimePeriod" line-width="20" line-height="2"
                    color="var(--color-primary)" class="loan-evaluation-tabs">
                    <van-tab v-for="period in timePeriods" :key="period.name" :name="period.name"
                      :title="period.name" />
                  </van-tabs>
                </div>

                <!-- 内容显示 -->
                <div class="loan-evaluation-content">
                  <!-- 总笔数 -->
                  <div class="text-lg text-gray-800 mb-3">
                    总 <span class="font-bold">{{ currentPeriod.total }}</span> 笔
                  </div>

                  <div class="space-y-3">
                    <!-- 还款成功率 -->
                    <div class="space-y-2">
                      <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">还款成功率</span>
                        <span class="text-sm font-bold text-gray-800">{{ currentPeriod.successRate.toFixed(1) }}%</span>
                      </div>
                      <div class="h-2 rounded-full" :style="`background-color: ${getSuccessRateLightColor()}`">
                        <div class="h-2 rounded-full transition-all duration-500"
                          :style="`width: ${Math.max(currentPeriod.successRate, 2)}%; background-color: ${getSuccessRateColor()}`">
                        </div>
                      </div>
                    </div>

                    <!-- 成功笔数 -->
                    <div class="flex justify-between items-center">
                      <span class="text-sm text-gray-600">成功笔数</span>
                      <span class="text-sm font-bold text-gray-800">{{ currentPeriod.success }} 笔</span>
                    </div>

                    <!-- 失败笔数 -->
                    <div class="flex justify-between items-center">
                      <span class="text-sm text-gray-600">失败笔数</span>
                      <span class="text-sm font-bold text-gray-800">{{ currentPeriod.failure }} 笔</span>
                    </div>

                    <!-- 成功金额 -->
                    <div class="flex justify-between items-center" v-if="currentPeriod.amounts">
                      <span class="text-sm text-gray-600">成功金额</span>
                      <span class="text-sm font-bold text-gray-800">{{ formatAmount(currentPeriod.amounts.success)
                        }}</span>
                    </div>

                    <!-- 失败金额 -->
                    <div class="flex justify-between items-center" v-if="currentPeriod.amounts">
                      <span class="text-sm text-gray-600">失败金额</span>
                      <span class="text-sm font-bold text-gray-800">{{ formatAmount(currentPeriod.amounts.failure)
                        }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>


      <!-- 逾期行为分析 -->
      <div class="mb-6">
        <LTitle title="逾期行为分析" class="mb-2" />
        <p class="text-gray-400 text-sm mb-4 px-4">各时间段逾期情况统计</p>

        <div class="space-y-3 px-4">
          <div class="rounded-xl p-4 relative" :class="getOverdueTimelineCardClass(item.hasOverdue)"
            v-for="item in overdueTimeline" :key="item.period">
            <div class="absolute top-0 right-0">
              <div class="px-2 py-1 text-xs text-white rounded-bl-xl rounded-tr-xl"
                :class="getOverdueTimelineTagClass(item.hasOverdue)">
                {{ item.hasOverdue ? '有逾期' : '无逾期' }}
              </div>
            </div>
            <div class="flex items-center">
              <div class="w-10 h-10 mr-4">
                <img :src="getOverdueTimelineIcon(item.hasOverdue)" :alt="item.hasOverdue ? '有逾期' : '无逾期'"
                  class="w-10 h-10 object-contain" />
              </div>
              <div class="flex-1">
                <div class="font-bold text-gray-800">{{ item.period }}</div>
                <div class="text-sm text-[#999999] mt-1">{{ item.description }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 当前逾期详情 -->
      <div class="mb-6" v-if="hasCurrentOverdue">
        <LTitle title="当前逾期提醒" class="mb-2" />
        <p class="text-gray-400 text-sm mb-4 px-4">需要立即处理的逾期情况</p>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 px-4">
          <div class="bg-[#F9ECEC] rounded-lg p-4 border border-[#F0CACA]">
            <div class="flex items-center justify-between">
              <span class="text-[#999999] text-sm">逾期机构数量</span>
              <span class="font-bold text-[#D44643] text-lg">{{ formatMetricValue(currentOverdueInstitutions) }}家</span>
            </div>
          </div>
          <div class="bg-[#F9ECEC] rounded-lg p-4 border border-[#F0CACA]">
            <div class="flex items-center justify-between">
              <span class="text-[#999999] text-sm">逾期金额</span>
              <span class="font-bold text-[#D44643] text-lg">{{ formatAmount(currentOverdueAmount) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="贷款行为分析通过多维度数据展示申请人的借贷行为模式，包括机构类型分布、交易金额分析、申请频率统计和风险事件分析。消费金融类、小贷担保类和网络贷款类机构的数据分别统计，有助于了解申请人的借贷偏好。建议重点关注短期内频繁申请和大额借贷行为，这可能暗示资金紧张或过度借贷风险。分析结果可为风险评估提供重要参考。" />
</template>

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

export default {
  name: 'LoanBehaviorAnalysis',
  components: {
    LTitle,
    LRemark
  },
  props: {
    data: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      chartInstance: null,
      activeTimePeriod: '最近1天'
    }
  },
  computed: {
    // 平均成功率
    averageSuccessRate() {
      if (this.timePeriods.length === 0) return 0
      const totalRate = this.timePeriods.reduce((sum, period) => sum + period.successRate, 0)
      return totalRate / this.timePeriods.length
    },

    // 最高成功率
    maxSuccessRate() {
      if (this.timePeriods.length === 0) return 0
      return Math.max(...this.timePeriods.map(period => period.successRate))
    },

    // 最低成功率
    minSuccessRate() {
      if (this.timePeriods.length === 0) return 0
      return Math.min(...this.timePeriods.map(period => period.successRate))
    },

    // 机构类型统计
    consumerFinanceInstitutions() {
      return this.parseIntervalValue(this.data.xyp_cpl0007)
    },
    smallLoanInstitutions() {
      // 通过总机构数减去消费金融和网络贷款推算
      const total = this.parseIntervalValue(this.data.xyp_cpl0001)
      const consumer = this.consumerFinanceInstitutions
      const network = this.networkLoanInstitutions
      return Math.max(0, total - consumer - network)
    },
    networkLoanInstitutions() {
      return this.parseIntervalValue(this.data.xyp_cpl0008)
    },

    // 机构类型比例
    totalInstitutions() {
      return this.consumerFinanceInstitutions + this.smallLoanInstitutions + this.networkLoanInstitutions || 1
    },
    consumerFinanceRatio() {
      return this.consumerFinanceInstitutions / this.totalInstitutions
    },
    smallLoanRatio() {
      return this.smallLoanInstitutions / this.totalInstitutions
    },
    networkLoanRatio() {
      return this.networkLoanInstitutions / this.totalInstitutions
    },

    // 还款表现统计
    historicalSuccessPayments() {
      return this.parseIntervalValue(this.data.xyp_cpl0014)
    },
    historicalFailurePayments() {
      return this.parseIntervalValue(this.data.xyp_cpl0015)
    },
    overallSuccessRate() {
      const total = this.historicalSuccessPayments + this.historicalFailurePayments
      if (total === 0) return 0
      return Math.round((this.historicalSuccessPayments / total) * 100)
    },

    // 时间维度分析
    timePeriods() {
      return [
        {
          name: '最近1天',
          success: this.parseIntervalValue(this.data.xyp_cpl0017),
          failure: this.parseIntervalValue(this.data.xyp_cpl0016),
          amounts: {
            success: this.parseIntervalValue(this.data.xyp_cpl0033),
            failure: this.parseIntervalValue(this.data.xyp_cpl0032)
          }
        },
        {
          name: '最近7天',
          success: this.parseIntervalValue(this.data.xyp_cpl0019),
          failure: this.parseIntervalValue(this.data.xyp_cpl0018),
          amounts: {
            success: this.parseIntervalValue(this.data.xyp_cpl0035),
            failure: this.parseIntervalValue(this.data.xyp_cpl0034)
          }
        },
        {
          name: '最近14天',
          success: this.parseIntervalValue(this.data.xyp_cpl0021),
          failure: this.parseIntervalValue(this.data.xyp_cpl0020),
          amounts: {
            success: this.parseIntervalValue(this.data.xyp_cpl0037),
            failure: this.parseIntervalValue(this.data.xyp_cpl0036)
          }
        },
        {
          name: '最近21天',
          success: this.parseIntervalValue(this.data.xyp_cpl0064),
          failure: this.parseIntervalValue(this.data.xyp_cpl0065),
          amounts: {
            success: this.parseIntervalValue(this.data.xyp_cpl0067),
            failure: this.parseIntervalValue(this.data.xyp_cpl0066)
          }
        },
        {
          name: '最近30天',
          success: this.parseIntervalValue(this.data.xyp_cpl0023),
          failure: this.parseIntervalValue(this.data.xyp_cpl0022),
          amounts: {
            success: this.parseIntervalValue(this.data.xyp_cpl0039),
            failure: this.parseIntervalValue(this.data.xyp_cpl0038)
          }
        },
        {
          name: '最近90天',
          success: this.parseIntervalValue(this.data.xyp_cpl0025),
          failure: this.parseIntervalValue(this.data.xyp_cpl0024),
          amounts: {
            success: this.parseIntervalValue(this.data.xyp_cpl0041),
            failure: this.parseIntervalValue(this.data.xyp_cpl0040)
          }
        },
        {
          name: '最近180天',
          success: this.parseIntervalValue(this.data.xyp_cpl0027),
          failure: this.parseIntervalValue(this.data.xyp_cpl0026),
          amounts: {
            success: this.parseIntervalValue(this.data.xyp_cpl0043),
            failure: this.parseIntervalValue(this.data.xyp_cpl0042)
          }
        }
      ].map(period => {
        const total = period.success + period.failure || 1
        return {
          ...period,
          total,
          successRate: (period.success / total) * 100,
          failureRate: (period.failure / total) * 100
        }
      })
    },

    // 逾期时间线
    overdueTimeline() {
      return [
        {
          period: '最近1天',
          hasOverdue: this.data.xyp_cpl0028 === '1',
          description: this.data.xyp_cpl0028 === '1' ? '检测到逾期行为' : '无逾期记录'
        },
        {
          period: '最近7天',
          hasOverdue: this.data.xyp_cpl0029 === '1',
          description: this.data.xyp_cpl0029 === '1' ? '检测到逾期行为' : '无逾期记录'
        },
        {
          period: '最近14天',
          hasOverdue: this.data.xyp_cpl0030 === '1',
          description: this.data.xyp_cpl0030 === '1' ? '检测到逾期行为' : '无逾期记录'
        },
        {
          period: '最近30天',
          hasOverdue: this.data.xyp_cpl0031 === '1',
          description: this.data.xyp_cpl0031 === '1' ? '检测到逾期行为' : '无逾期记录'
        }
      ]
    },

    // 当前逾期状态
    hasCurrentOverdue() {
      return this.data.xyp_cpl0044 === '1'
    },
    currentOverdueInstitutions() {
      return this.parseIntervalValue(this.data.xyp_cpl0071)
    },
    currentOverdueAmount() {
      return this.parseIntervalValue(this.data.xyp_cpl0072)
    },

    // 当前选中的时间段
    currentPeriod() {
      return this.timePeriods.find(p => p.name === this.activeTimePeriod) || this.timePeriods[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: {
    timePeriods() {
      this.updateChart()
    }
  },

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

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

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            const data = params[0]
            const period = this.timePeriods[data.dataIndex]
            return `${data.name}<br/>成功率: ${period.successRate.toFixed(1)}%<br/>${period.success}/${period.total}笔`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.timePeriods.map(p => p.name),
          axisLabel: {
            rotate: 45,
            fontSize: 12,
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#e0e0e0'
            }
          }
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%',
            fontSize: 12,
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#e0e0e0'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        series: [
          {
            name: '还款成功率',
            type: 'bar',
            data: this.timePeriods.map(p => Math.max(p.successRate, 2)),
            barWidth: '25%',
            barMinHeight: 2,
            itemStyle: {
              color: '#10b981',
              borderRadius: [4, 4, 0, 0]
            },
            label: {
              show: true,
              position: 'top',
              formatter: (params) => {
                const period = this.timePeriods[params.dataIndex]
                return period.successRate > 0 ? `${period.successRate.toFixed(1)}%` : '0%'
              },
              fontSize: 11,
              color: '#333'
            }
          }
        ]
      }

      this.chartInstance.setOption(option)
    },

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

    getSuccessRateColor() {
      const rate = this.currentPeriod.successRate
      if (rate >= 80) return '#10b981'
      if (rate >= 60) return '#f59e0b'
      return '#ef4444'
    },

    getSuccessRateLightColor() {
      const rate = this.currentPeriod.successRate
      if (rate >= 80) return '#E8F8F0'
      if (rate >= 60) return '#FEF3C7'
      return '#FEE2E2'
    },

    getOverdueTimelineCardClass(hasOverdue) {
      if (hasOverdue) return 'bg-[#FFF0F0] border border-red-200'
      return 'bg-[#F0FFF0] border border-green-200'
    },

    getOverdueTimelineTagClass(hasOverdue) {
      if (hasOverdue) return 'bg-[#E53935]'
      return 'bg-[#4CAF50]'
    },

    getOverdueTimelineIcon(hasOverdue) {
      if (hasOverdue) return new URL('@/assets/images/report/gfx.png', import.meta.url).href
      return new URL('@/assets/images/report/zq.png', import.meta.url).href
    },

    parseIntervalValue(value) {
      if (!value || value === '' || value === '-1') return 0
      const num = parseInt(value)
      if (isNaN(num)) return 0

      // 根据区间映射返回大致范围的中值
      switch (num) {
        case 1: return 1
        case 2: return 3
        case 3: return 7
        case 4: return 15
        case 5: return 25
        default: return num
      }
    },

    formatMetricValue(value) {
      if (value === 0) return '0'
      if (value < 5) return `${value}`
      return `${value}+`
    },

    formatAmount(value) {
      if (value === 0) return '0元'
      if (value < 1000) return `${value}元`
      if (value < 10000) return `${(value / 1000).toFixed(1)}千元`
      return `${(value / 10000).toFixed(1)}万元`
    },

    getSliceStyle(ratio, startAngle) {
      const angle = ratio * 360
      return {
        '--start-angle': `${startAngle * 360}deg`,
        '--end-angle': `${(startAngle + ratio) * 360}deg`,
        '--slice-percent': `${ratio * 100}%`
      }
    }
  }
}
</script>

<style scoped>
.loan-behavior-analysis {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
  padding: 24px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.section-spacing {
  height: 20px;
}

.loan-behavior-analysis: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(-2px);
}

/* 标签页样式 */
.loan-evaluation-tabs {}

.loan-evaluation-tabs :deep(.van-tabs__wrap) {
  height: 32px !important;
  background-color: transparent !important;
  padding: 0 !important;
  border-bottom: 1px solid #DDDDDD !important;
}

.loan-evaluation-tabs :deep(.van-tabs__nav) {
  background-color: transparent !important;
  gap: 0;
  height: 32px !important;
}

.loan-evaluation-tabs :deep(.van-tab) {
  color: #999999 !important;
  font-size: 14px !important;
  font-weight: 400 !important;
}

.loan-evaluation-tabs :deep(.van-tab--active) {
  color: var(--van-theme-primary) !important;
  background-color: unset !important;
}

.loan-evaluation-tabs :deep(.van-tabs__line) {
  height: 2px !important;
  border-radius: 1px !important;
}

/* 内容区域样式 */
.loan-evaluation-wrap {
  @apply mx-4 my-1;
  border: 1px solid #DDDDDD;
  background-color: #F9F9F9;
  border-radius: 8px;
}

.loan-evaluation-content {
  padding: 8px 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .loan-behavior-analysis {
    padding: 16px;
  }

  .grid {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
}

@media (max-width: 480px) {
  .loan-behavior-analysis {
    padding: 12px;
  }
}
</style>
