<template>
    <div class="chart-container">
      <h3>活跃用户 Top10 借用次数分布</h3>
  
      <div v-if="hasData">
        <v-chart :option="chartOption" autoresize style="height: 400px;" />
      </div>
      <div v-else class="empty-tip">暂无数据</div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import VChart from 'vue-echarts'
  import { use } from 'echarts/core'
  import {
    CanvasRenderer
  } from 'echarts/renderers'
  import {
    PieChart
  } from 'echarts/charts'
  import {
    TitleComponent,
    TooltipComponent,
    LegendComponent
  } from 'echarts/components'
  import * as api from '../api'
  
  use([
    CanvasRenderer,
    PieChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent
  ])
  
  interface ActiveUser {
    user_id: number
    user_name: string
    user_code: string
    borrow_count: number
    total_quantity: number
  }
  
  const rawData = ref<ActiveUser[]>([])
  
  const fetchData = async () => {
    const res = await api.GetActiveUsers()
    if (res.code === 2000) {
      rawData.value = res.data.active_users
    } else {
      rawData.value = []
    }
  }
  
  onMounted(fetchData)
  
  const hasData = computed(() => rawData.value.length > 0)
  
  const chartOption = computed(() => {
    const pieData = rawData.value.map(user => ({
      name: user.user_name,
      value: user.borrow_count
    }))
  
    return {
      title: {
        text: '借用次数分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}次 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: pieData.map(item => item.name)
      },
      series: [
        {
          name: '借用次数',
          type: 'pie',
          radius: '60%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  })
  </script>
  
  <style scoped>
  .chart-container {
    width: 100%;
    margin: 0 auto;
  }
  .empty-tip {
    text-align: center;
    color: #999;
    padding: 20px;
  }
  </style>
  