<template>
  <div class="card application-count-section">
    <div class="rounded-lg border border-gray-200 pb-2 mb-4">
      <div class="mt-4">
        <!-- 申请次数时间分布图表 -->
        <div class="mb-6">
          <LTitle title="申请次数时间分布" />
          <div class="h-64">
            <v-chart class="chart-container" :option="chartOption" autoresize />
          </div>
        </div>

        <!-- 特殊时段申请次数（周末/夜间），去掉 Tab，直接展示一张柱状图 -->
        <div class="mb-2">
          <LTitle title="特殊时段申请次数（周末 / 夜间）" />
          <div class="h-64">
            <v-chart class="chart-container" :option="specialChartOption" autoresize />
          </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,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import LTitle from '@/components/LTitle.vue'
import { getApplicationCounts, getSpecialPeriodCounts, PERIOD_MAP } from '../utils/dataParser'

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

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

const periodKeys = ['d7', 'd15', 'm1', 'm3', 'm6', 'm12']
const labels = periodKeys.map(key => PERIOD_MAP[key].label)

// 总申请次数图表配置
const chartOption = computed(() => {
  const data = periodKeys.map(key => {
    const counts = getApplicationCounts(props.data, key, props.dimension)
    return counts.total
  })

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        let result = params[0].name + '<br/>'
        params.forEach(item => {
          result += `${item.seriesName}: ${item.value} 次<br/>`
        })
        return result
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: 0,
      top: 20,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: labels,
      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: '#2B79EE',
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: '#1e5bb8'
          }
        }
      }
    ]
  }
})

// 特殊时段（周末 / 夜间）图表配置
const specialChartOption = computed(() => {
  const weekendData = periodKeys.map(key => {
    const s = getSpecialPeriodCounts(props.data, key, props.dimension)
    return s.weekend || 0
  })
  const nightData = periodKeys.map(key => {
    const s = getSpecialPeriodCounts(props.data, key, props.dimension)
    return s.night || 0
  })

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        let result = params[0].name + '<br/>'
        params.forEach(item => {
          result += `${item.seriesName}: ${item.value} 次<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['周末申请次数', '夜间申请次数'],
      top: '5%',
      textStyle: {
        fontSize: 12
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: 0,
      top: 30,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: labels,
      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: weekendData,
        barWidth: '25%',
        barMinHeight: 3,
        itemStyle: {
          color: '#2B79EE',
          borderRadius: [4, 4, 0, 0]
        }
      },
      {
        name: '夜间申请次数',
        type: 'bar',
        data: nightData,
        barWidth: '25%',
        barMinHeight: 3,
        itemStyle: {
          color: '#F97316',
          borderRadius: [4, 4, 0, 0]
        }
      }
    ]
  }
})
</script>

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

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