<template>
  <section class="chart-block-preview">
    <header v-if="block?.display?.showTitle !== false" class="preview-header">
      <strong>{{ block?.name || definition?.name || '图表' }}</strong>
      <small>样例数据</small>
    </header>

    <div v-if="definition?.chartType === 'metric'" class="metric-preview">
      <strong>{{ sample.summary.value.toLocaleString() }}</strong>
      <span>共 {{ sample.summary.count }} 条</span>
    </div>
    <div v-else-if="errorMessage" class="preview-error">
      <span>{{ errorMessage }}</span>
      <el-button size="small" @click.stop="retry">重试</el-button>
    </div>
    <div v-else ref="chartElement" class="chart-preview-canvas"></div>
  </section>
</template>

<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { buildChartOption, sampleChartData } from './chartBlock.js'

const props = defineProps({
  definition: { type: Object, default: null },
  block: { type: Object, default: null }
})

const chartElement = ref(null)
const errorMessage = ref('')
const sample = computed(() => sampleChartData(props.definition))
const option = computed(() => buildChartOption(props.definition, props.block, sample.value))
let chart = null

onMounted(() => {
  renderChart()
  window.addEventListener('resize', resizeChart)
})

watch(option, renderChart, { deep: true })

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  disposeChart()
})

async function renderChart() {
  if (props.definition?.chartType === 'metric') return
  await nextTick()
  if (!chartElement.value) return
  try {
    errorMessage.value = ''
    if (!chart) {
      chart = echarts.init(chartElement.value)
    }
    chart.setOption(option.value, true)
    chart.resize()
  } catch (error) {
    errorMessage.value = error?.message || '图表预览失败'
    disposeChart()
  }
}

function resizeChart() {
  chart?.resize()
}

function disposeChart() {
  if (!chart) return
  chart.dispose()
  chart = null
}

function retry() {
  renderChart()
}
</script>

<style scoped lang="scss">
.chart-block-preview {
  display: grid;
  gap: 8px;
  min-height: 180px;
}

.preview-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.preview-header small,
.metric-preview span {
  color: #98a2b3;
  font-size: 12px;
}

.chart-preview-canvas {
  width: 100%;
  min-height: 150px;
}

.metric-preview {
  display: grid;
  align-content: center;
  gap: 6px;
  min-height: 130px;
}

.metric-preview strong {
  color: #172033;
  font-size: 30px;
}

.preview-error {
  display: grid;
  place-items: center;
  align-content: center;
  gap: 10px;
  min-height: 130px;
  color: #f56c6c;
}
</style>
