<template>
  <div class="card">
    <div class="rounded-lg border border-gray-200 pb-2 mb-4">
      <div class="mt-4">
        <LTitle title="产品类型申请分布（近12个月）" />
        <div class="h-64 mb-4">
          <v-chart class="chart-container" :option="chartOption" autoresize />
        </div>

        <!-- 详细列表：与图表颜色一致，包含 0 次的类型 -->
        <div class="space-y-2 px-4 pb-4">
          <div v-for="item in detailList" :key="item.key" class="flex items-center justify-between text-sm">
            <div class="flex items-center">
              <span class="w-2 h-2 rounded-full mr-2" :style="{ backgroundColor: item.color }" />
              <span class="text-gray-600">{{ item.label }}</span>
            </div>
            <span class="text-[#111827] font-bold">
              {{ item.value }} 次
            </span>
          </div>
        </div>
      </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 {
  TitleComponent,
  TooltipComponent,
  GridComponent
} from 'echarts/components'
import LTitle from '@/components/LTitle.vue'
import { getValue, FIELD_LABELS } from '../utils/dataParser'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent
])

const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => ({})
  },
  // 维度：id（身份证） / cell（手机号）
  dimension: {
    type: String,
    default: 'id'
  }
})

// 近12个月的前缀
const PREFIX = 'als_m12'

// 关注的产品类型 key（字段中的 id_xxx_allnum）
const TYPE_KEYS = ['pdl', 'caon', 'rel', 'caoff', 'cooff', 'af', 'coon', 'oth']

// 颜色映射，与其他组件保持风格一致
const COLORS = [
  '#2B79EE',
  '#60A5FA',
  '#34D399',
  '#FBBF24',
  '#F97316',
  '#EF4444',
  '#A855F7',
  '#6B7280'
]

// 详细列表（每个产品类型的次数和颜色）
const detailList = computed(() => {
  const v = props.data || {}
  const labels = FIELD_LABELS.bank || {}

  return TYPE_KEYS.map((key, index) => {
    const dimKey = props.dimension === 'cell' ? 'cell' : 'id'
    const field = `${PREFIX}_${dimKey}_${key}_allnum`
    const value = getValue(v[field]) || 0

    return {
      key,
      label: labels[key] || key,
      value,
      color: COLORS[index % COLORS.length]
    }
  })
})

// 产品类型分布柱状图
const chartOption = computed(() => {
  const list = detailList.value

  const categories = list.map(item => item.label)
  const values = list.map(item => item.value)
  const colors = list.map(item => item.color)

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: params => {
        const p = params[0]
        return `${p.name}<br/>申请次数：${p.value} 次`
      }
    },
    grid: {
      left: 0,
      right: 0,
      bottom: 0,
      top: 20,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        fontSize: 10,
        color: '#6b7280',
        rotate: 30
      },
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 11,
        color: '#6b7280',
        formatter: '{value} 次'
      },
      splitLine: {
        lineStyle: {
          color: '#f3f4f6'
        }
      }
    },
    series: [
      {
        name: '申请次数',
        type: 'bar',
        data: values,
        barWidth: '35%',
        barMinHeight: 3,
        itemStyle: {
          color: params => colors[params.dataIndex],
          borderRadius: [4, 4, 0, 0]
        }
      }
    ]
  }
})
</script>

<style lang="scss" scoped>
.card {
  background: #ffffff;
}

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