<template>
  <div class="data-statistics-chart">
    <a-card :title="title" :loading="loading">
      <template #extra>
        <a-space>
          <a-select
            v-model:value="selectedPeriod"
            style="width: 120px"
            @change="handlePeriodChange"
          >
            <a-select-option value="7d">近7天</a-select-option>
            <a-select-option value="30d">近30天</a-select-option>
            <a-select-option value="90d">近90天</a-select-option>
            <a-select-option value="365d">近一年</a-select-option>
          </a-select>
          <a-button @click="handleRefresh" :loading="loading">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
        </a-space>
      </template>
      
      <div ref="chartContainer" :style="{ height: chartHeight + 'px' }"></div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
import * as echarts from 'echarts'
import { message } from 'ant-design-vue'

interface ChartData {
  date: string
  value: number
  [key: string]: any
}

interface Props {
  title: string
  chartType: 'line' | 'bar' | 'pie' | 'area'
  dataSource: string // API接口地址
  chartHeight?: number
  xAxisKey?: string
  yAxisKey?: string
  seriesConfig?: any[]
}

const props = withDefaults(defineProps<Props>(), {
  chartHeight: 300,
  xAxisKey: 'date',
  yAxisKey: 'value',
  seriesConfig: () => []
})

const emit = defineEmits<{
  dataLoaded: [data: ChartData[]]
  error: [error: Error]
}>()

const loading = ref(false)
const selectedPeriod = ref('30d')
const chartContainer = ref<HTMLDivElement>()
let chartInstance: echarts.ECharts | null = null
const chartData = ref<ChartData[]>([])

/**
 * 初始化图表
 */
const initChart = () => {
  if (!chartContainer.value) return
  
  chartInstance = echarts.init(chartContainer.value)
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

/**
 * 更新图表配置
 */
const updateChart = () => {
  if (!chartInstance || !chartData.value.length) return
  
  const option = generateChartOption()
  chartInstance.setOption(option, true)
}

/**
 * 生成图表配置
 */
const generateChartOption = () => {
  const baseOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: props.seriesConfig.map(s => s.name) || ['数据']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {
          title: '保存为图片'
        },
        dataZoom: {
          title: {
            zoom: '区域缩放',
            back: '区域缩放还原'
          }
        }
      }
    }
  }

  // 根据图表类型生成不同配置
  switch (props.chartType) {
    case 'line':
    case 'area':
      return {
        ...baseOption,
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: chartData.value.map(item => item[props.xAxisKey])
        },
        yAxis: {
          type: 'value'
        },
        series: props.seriesConfig.length > 0 
          ? props.seriesConfig.map(config => ({
              ...config,
              type: 'line',
              smooth: true,
              areaStyle: props.chartType === 'area' ? {} : undefined,
              data: chartData.value.map(item => item[config.dataKey || props.yAxisKey])
            }))
          : [{
              name: '数据',
              type: 'line',
              smooth: true,
              areaStyle: props.chartType === 'area' ? {} : undefined,
              data: chartData.value.map(item => item[props.yAxisKey])
            }]
      }
    
    case 'bar':
      return {
        ...baseOption,
        xAxis: {
          type: 'category',
          data: chartData.value.map(item => item[props.xAxisKey])
        },
        yAxis: {
          type: 'value'
        },
        series: props.seriesConfig.length > 0 
          ? props.seriesConfig.map(config => ({
              ...config,
              type: 'bar',
              data: chartData.value.map(item => item[config.dataKey || props.yAxisKey])
            }))
          : [{
              name: '数据',
              type: 'bar',
              data: chartData.value.map(item => item[props.yAxisKey])
            }]
      }
    
    case 'pie':
      return {
        ...baseOption,
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: props.title,
          type: 'pie',
          radius: '50%',
          data: chartData.value.map(item => ({
            name: item[props.xAxisKey],
            value: item[props.yAxisKey]
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
    
    default:
      return baseOption
  }
}

/**
 * 加载图表数据
 */
const loadData = async () => {
  if (!props.dataSource) return
  
  loading.value = true
  
  try {
    // 这里应该调用实际的API接口
    // const response = await fetch(`${props.dataSource}?period=${selectedPeriod.value}`)
    // const result = await response.json()
    
    // 模拟数据加载
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 生成模拟数据
    const mockData = generateMockData()
    chartData.value = mockData
    
    emit('dataLoaded', mockData)
    
    // 更新图表
    nextTick(() => {
      updateChart()
    })
  } catch (error) {
    console.error('加载图表数据失败:', error)
    message.error('加载图表数据失败')
    emit('error', error as Error)
  } finally {
    loading.value = false
  }
}

/**
 * 生成模拟数据
 */
const generateMockData = (): ChartData[] => {
  const days = selectedPeriod.value === '7d' ? 7 : 
               selectedPeriod.value === '30d' ? 30 :
               selectedPeriod.value === '90d' ? 90 : 365
  
  const data: ChartData[] = []
  const now = new Date()
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(now)
    date.setDate(date.getDate() - i)
    
    data.push({
      date: date.toISOString().split('T')[0],
      value: Math.floor(Math.random() * 100) + 50,
      users: Math.floor(Math.random() * 50) + 20,
      orders: Math.floor(Math.random() * 30) + 10,
      revenue: Math.floor(Math.random() * 5000) + 1000
    })
  }
  
  return data
}

/**
 * 处理时间周期变化
 */
const handlePeriodChange = () => {
  loadData()
}

/**
 * 刷新数据
 */
const handleRefresh = () => {
  loadData()
}

/**
 * 处理窗口大小变化
 */
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

/**
 * 监听数据变化
 */
watch(() => props.dataSource, () => {
  loadData()
}, { immediate: false })

/**
 * 组件挂载
 */
onMounted(() => {
  nextTick(() => {
    initChart()
    loadData()
  })
})

/**
 * 组件卸载
 */
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})

// 暴露方法给父组件
defineExpose({
  refresh: handleRefresh,
  updateData: (data: ChartData[]) => {
    chartData.value = data
    updateChart()
  }
})
</script>

<style scoped>
.data-statistics-chart {
  width: 100%;
}

.data-statistics-chart :deep(.ant-card-body) {
  padding: 16px;
}
</style>