<template>
  <div class="card rounded-lg border border-gray-200 mb-2">
    <div class="mt-4">
      <LTitle title="还款成功 / 失败次数趋势" />
      <div class="h-64 px-2">
        <v-chart class="chart-container" :option="chartOption" autoresize />
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
import LTitle from '@/components/LTitle.vue'
import { PERIODS, getRepayCountsByPeriod } from '../utils/dataParser'

use([CanvasRenderer, BarChart, GridComponent, LegendComponent, TooltipComponent])

const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => ({})
  }
})

const chartOption = computed(() => {
  const counts = getRepayCountsByPeriod(props.data || {})
  const labels = PERIODS.map(p => p.label)

  const successData = PERIODS.map(p => counts[p.key]?.success || 0)
  const failData = PERIODS.map(p => counts[p.key]?.fail || 0)

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      top: 0,
      icon: 'circle',
      textStyle: {
        fontSize: 11,
        color: '#4b5563'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      top: 24,
      bottom: 0,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: labels,
      axisLabel: {
        fontSize: 10,
        color: '#6b7280'
      },
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 11,
        color: '#6b7280',
        formatter: '{value} 次'
      },
      splitLine: {
        lineStyle: {
          color: '#f3f4f6'
        }
      }
    },
    series: [
      {
        name: '还款成功次数',
        type: 'bar',
        data: successData,
        barWidth: '30%',
        barMinHeight: 3,
        itemStyle: {
          color: '#34D399',
          borderRadius: [4, 4, 0, 0]
        }
      },
      {
        name: '还款失败次数',
        type: 'bar',
        data: failData,
        barWidth: '30%',
        barMinHeight: 3,
        itemStyle: {
          color: '#F97316',
          borderRadius: [4, 4, 0, 0]
        }
      }
    ]
  }
})
</script>

<style scoped>
.card {
  background: #ffffff;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>


