<template>
  <div class="virtual-scroll-chart">
    <a-card :title="title" :bordered="false">
      <template #extra>
        <a-space>
          <a-input-number
            v-model:value="pageSize"
            :min="10"
            :max="1000"
            :step="10"
            size="small"
            addon-before="每页"
            addon-after="条"
            @change="handlePageSizeChange"
          />
          <a-button size="small" @click="refreshData">
            <template #icon><reload-outlined /></template>
            刷新
          </a-button>
        </a-space>
      </template>
      
      <!-- 数据统计信息 -->
      <div class="data-info" v-if="totalCount > 0">
        <a-space>
          <a-tag color="blue">总数据: {{ totalCount.toLocaleString() }}</a-tag>
          <a-tag color="green">当前页: {{ currentPage }}/{{ totalPages }}</a-tag>
          <a-tag color="orange">显示: {{ visibleData.length }}</a-tag>
          <a-tag v-if="isVirtualMode" color="purple">虚拟滚动: 开启</a-tag>
        </a-space>
      </div>
      
      <!-- 图表容器 -->
      <div class="chart-wrapper">
        <e-chart
          :options="chartOptions"
          :height="chartHeight"
          :cache-key="cacheKey"
          :enable-cache="enableCache"
          :cache-ttl="cacheTTL"
          @chart-ready="handleChartReady"
        />
      </div>
      
      <!-- 分页控制 -->
      <div class="pagination-wrapper" v-if="totalPages > 1">
        <a-pagination
          v-model:current="currentPage"
          v-model:page-size="pageSize"
          :total="totalCount"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :show-total="(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
          :page-size-options="['10', '20', '50', '100', '200', '500']"
          @change="handlePageChange"
          @show-size-change="handlePageSizeChange"
        />
      </div>
      
      <!-- 加载状态 -->
      <div class="loading-wrapper" v-if="loading">
        <a-spin size="large" tip="加载中..." />
      </div>
    </a-card>
  </div>
</template>

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

// Props
const props = defineProps({
  title: {
    type: String,
    default: '大数据量图表'
  },
  data: {
    type: Array,
    default: () => []
  },
  chartType: {
    type: String,
    default: 'line',
    validator: (value) => ['line', 'bar', 'scatter'].includes(value)
  },
  chartHeight: {
    type: String,
    default: '400px'
  },
  virtualThreshold: {
    type: Number,
    default: 1000 // 超过1000条数据启用虚拟滚动
  },
  enableCache: {
    type: Boolean,
    default: true
  },
  cacheTTL: {
    type: Number,
    default: 300000 // 5分钟
  }
})

// Emits
const emit = defineEmits(['refresh', 'page-change'])

// 响应式数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(100)
const chartInstance = ref(null)

// 计算属性
const totalCount = computed(() => props.data.length)
const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))
const isVirtualMode = computed(() => totalCount.value > props.virtualThreshold)

// 缓存键
const cacheKey = computed(() => {
  return `virtual_chart_${props.chartType}_${currentPage.value}_${pageSize.value}`
})

// 可见数据（当前页数据）
const visibleData = computed(() => {
  if (!isVirtualMode.value) {
    return props.data
  }
  
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return props.data.slice(startIndex, endIndex)
})

// 图表配置
const chartOptions = computed(() => {
  const baseOptions = {
    title: {
      text: isVirtualMode.value ? `${props.title} (第${currentPage.value}页)` : props.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: visibleData.value.map(item => item.name || item.x)
    },
    yAxis: {
      type: 'value'
    },
    // 性能优化配置
    animation: visibleData.value.length > 200 ? false : true,
    progressive: visibleData.value.length > 500 ? 500 : 0,
    progressiveThreshold: 1000
  }
  
  // 根据图表类型配置series
  if (props.chartType === 'line') {
    baseOptions.series = [{
      name: '数据',
      type: 'line',
      data: visibleData.value.map(item => item.value || item.y),
      smooth: true,
      symbol: visibleData.value.length > 100 ? 'none' : 'circle',
      lineStyle: {
        width: 1
      }
    }]
  } else if (props.chartType === 'bar') {
    baseOptions.series = [{
      name: '数据',
      type: 'bar',
      data: visibleData.value.map(item => item.value || item.y),
      itemStyle: {
        color: '#1890ff'
      }
    }]
  } else if (props.chartType === 'scatter') {
    baseOptions.series = [{
      name: '数据',
      type: 'scatter',
      data: visibleData.value.map(item => [item.x, item.y]),
      symbolSize: 6
    }]
  }
  
  return baseOptions
})

// 处理页面变化
function handlePageChange(page, size) {
  currentPage.value = page
  pageSize.value = size
  emit('page-change', { page, size })
}

// 处理页面大小变化
function handlePageSizeChange(current, size) {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
  emit('page-change', { page: 1, size })
}

// 刷新数据
function refreshData() {
  loading.value = true
  emit('refresh')
  
  // 模拟加载延迟
  setTimeout(() => {
    loading.value = false
    message.success('数据刷新完成')
  }, 500)
}

// 图表就绪回调
function handleChartReady(chart) {
  chartInstance.value = chart
}

// 监听数据变化，自动调整页面
watch(() => props.data, (newData) => {
  if (newData.length === 0) {
    currentPage.value = 1
    return
  }
  
  // 如果当前页超出范围，调整到最后一页
  const maxPage = Math.ceil(newData.length / pageSize.value)
  if (currentPage.value > maxPage) {
    currentPage.value = maxPage
  }
}, { immediate: true })

// 组件挂载时的初始化
onMounted(() => {
  if (totalCount.value > props.virtualThreshold) {
    message.info(`检测到大数据量(${totalCount.value.toLocaleString()}条)，已启用虚拟滚动优化`)
  }
})
</script>

<style scoped>
.virtual-scroll-chart {
  width: 100%;
}

.data-info {
  margin-bottom: 16px;
  padding: 8px 12px;
  background: #fafafa;
  border-radius: 6px;
}

.chart-wrapper {
  position: relative;
  margin-bottom: 16px;
}

.pagination-wrapper {
  text-align: center;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
}

.loading-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
}

:deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.ant-pagination) {
  margin: 0;
}
</style>