<script setup>
import { useTheme } from 'vuetify'
import { computed, ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import MoreBtn from '@/components/MoreBtn.vue'

const vuetifyTheme = useTheme()

// 图表实例引用
const chartRef = ref(null)
let chartInstance = null

// 数据
const seriesData = [
  37,
  57,
  45,
  75,
  57,
  40,
  65,
]

const options = computed(() => {
  const currentTheme = vuetifyTheme.current.value.colors
  const variableTheme = vuetifyTheme.current.value.variables
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        show: false
      },
      axisLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLabel: {
        formatter: value => `${value > 999 ? `${(value / 1000).toFixed(0)}` : value}k`
      }
    },
    series: [{
      type: 'bar',
      barWidth: '40%',
      data: seriesData,
      itemStyle: {
        borderRadius: [6, 6, 0, 0],
        color: function(params) {
          // 第四个柱子使用主色调，其他使用灰色
          return params.dataIndex === 3 ? 
            currentTheme.primary : 
            currentTheme['track-bg']
        }
      }
    }]
  }
})

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    chartInstance.setOption(options.value)
  }
}

// 更新图表
const updateChart = () => {
  if (chartInstance) {
    chartInstance.setOption(options.value, true)
  }
}

// 监听主题变化
const watchTheme = () => {
  return vuetifyTheme.current.value
}

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 生命周期钩子
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

const moreList = [
  {
    title: 'Share',
    value: 'Share',
  },
  {
    title: 'Refresh',
    value: 'Refresh',
  },
  {
    title: 'Update',
    value: 'Update',
  },
]
</script>

<template>
  <v-card>
    <VCardItem>
      <VCardTitle>Weekly Overview</VCardTitle>

      <template #append>
        <div class="me-n3">
          <MoreBtn :menu-list="moreList" />
        </div>
      </template>
    </VCardItem>

    <v-card-text>
      <!-- ECharts 容器 -->
      <div 
        ref="chartRef" 
        style="width: 100%; height: 200px;"
      ></div>

      <v-btn block color="primary" class="mt-2">
        Details
      </v-btn>
    </v-card-text>
  </v-card>
</template>