<template>
  <div class="monitor-chart">
    <div class="chart-header">
      <h3>{{ title }}</h3>
      <div class="chart-controls">
        <a-select
          v-model="selectedPeriod"
          style="width: 120px"
          @change="handlePeriodChange"
        >
          <a-select-option value="day">今日</a-select-option>
          <a-select-option value="week">本周</a-select-option>
          <a-select-option value="month">本月</a-select-option>
        </a-select>
        <a-button type="text" @click="refreshData">
          <template #icon><reload-outlined /></template>
        </a-button>
      </div>
    </div>
    
    <div class="chart-content">
      <e-chart 
        :options="chartOptions" 
        :height="height" 
        :cache-key="cacheKey"
        :enable-cache="enableCache"
        :cache-ttl="cacheTTL"
        @chart-ready="handleChartReady" 
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
import EChart from './EChart.vue'

// 定义组件属性
const props = defineProps({
  // 图表标题
  title: {
    type: String,
    default: '监控图表'
  },
  // 图表类型
  type: {
    type: String,
    default: 'line',
    validator: (value) => ['line', 'bar', 'pie'].includes(value)
  },
  // 图表数据
  data: {
    type: Object,
    default: () => ({
      xAxis: [],
      series: []
    })
  },
  // 图表高度
  height: {
    type: String,
    default: '300px'
  },
  // 自动刷新间隔（毫秒），0表示不自动刷新
  refreshInterval: {
    type: Number,
    default: 0
  },
  // 缓存键
  cacheKey: {
    type: String,
    default: null
  },
  // 启用缓存
  enableCache: {
    type: Boolean,
    default: true
  },
  // 缓存过期时间（毫秒）
  cacheTTL: {
    type: Number,
    default: 5 * 60 * 1000 // 5分钟
  }
})

// 定义事件
const emit = defineEmits(['refresh', 'period-change'])

// 选中的时间周期
const selectedPeriod = ref('day')

// 图表实例
let chartInstance = null

// 自动刷新定时器
let refreshTimer = null

// 处理图表就绪事件
function handleChartReady(chart) {
  chartInstance = chart
}

// 处理时间周期变化
function handlePeriodChange(period) {
  emit('period-change', period)
}

// 刷新数据
function refreshData() {
  emit('refresh', selectedPeriod.value)
}

// 图表选项
const chartOptions = computed(() => {
  if (props.type === 'line' || props.type === 'bar') {
    return {
      title: {
        text: props.title,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: props.data.series?.map(item => item.name) || [],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: props.type === 'bar',
        data: props.data.xAxis || []
      },
      yAxis: {
        type: 'value'
      },
      series: (props.data.series || []).map(item => ({
        name: item.name,
        type: props.type,
        data: item.data,
        smooth: props.type === 'line',
        itemStyle: item.itemStyle,
        lineStyle: item.lineStyle,
        areaStyle: props.type === 'line' ? item.areaStyle : undefined
      }))
    }
  } else if (props.type === 'pie') {
    return {
      title: {
        text: props.title,
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'horizontal',
        bottom: 0
      },
      series: [
        {
          name: props.title,
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: props.data || []
        }
      ]
    }
  }
  
  return {}
})

// 设置自动刷新
function setupAutoRefresh() {
  clearInterval(refreshTimer)
  
  if (props.refreshInterval > 0) {
    refreshTimer = setInterval(() => {
      refreshData()
    }, props.refreshInterval)
  }
}

// 监听刷新间隔变化
watch(() => props.refreshInterval, () => {
  setupAutoRefresh()
})

// 组件挂载时设置自动刷新
onMounted(() => {
  setupAutoRefresh()
})

// 组件卸载时清理定时器
onMounted(() => {
  clearInterval(refreshTimer)
})
</script>

<style scoped>
.monitor-chart {
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  height: 48px;
  border-bottom: 1px solid #f0f0f0;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-content {
  padding: 16px;
}
</style>