<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue"
import * as echarts from "echarts"
import "echarts-wordcloud"

const props = defineProps({
  /** 与 ECharts 官方 option 一致，由父组件传入 */
  option: {
    type: Object,
    required: true
  }
})

const chartRef = ref(null)
let chartInstance = null
let resizeObserver = null
let resizeTimer = null
let lastSize = { w: 0, h: 0 }

const DEFAULT_ANIMATION = {
  animation: true,
  animationDuration: 1000,
  animationEasing: 'cubicOut',
  animationDurationUpdate: 600,
  animationEasingUpdate: 'cubicOut'
}

/** 合并默认动画；各页/系列可显式 animation: false 覆盖 */
function withAnimation(opt) {
  if (!opt || opt.animation === false) {
    return opt
  }
  return { ...DEFAULT_ANIMATION, ...opt }
}

/** 写入配置并强制整表替换，避免从「暂无数据」切到真实图表时残留 title */
function applyOption(opt) {
  if (!chartInstance || !opt) {
    return
  }
  chartInstance.setOption(withAnimation(opt), { notMerge: true })
}

/** 在挂载点创建实例并塞入配置 */
function initChart() {
  if (!chartRef.value) {
    return
  }
  if (chartInstance) {
    chartInstance.dispose()
  }
  lastSize = { w: 0, h: 0 }
  chartInstance = echarts.init(chartRef.value)
  applyOption(props.option)
  scheduleResize()
}

/** 仅容器尺寸变化时 resize；避免 setOption 后立即 resize 打断入场动画 */
function resizeIfChanged() {
  const el = chartRef.value
  if (!chartInstance || !el) {
    return
  }
  const w = el.clientWidth
  const h = el.clientHeight
  if (w <= 0 || h <= 0) {
    return
  }
  if (w === lastSize.w && h === lastSize.h) {
    return
  }
  lastSize = { w, h }
  chartInstance.resize()
}

function scheduleResize() {
  if (resizeTimer) {
    clearTimeout(resizeTimer)
  }
  resizeTimer = window.setTimeout(() => {
    resizeTimer = null
    resizeIfChanged()
  }, 80)
}

onMounted(() => {
  initChart()
  resizeObserver = new ResizeObserver(() => scheduleResize())
  if (chartRef.value) {
    resizeObserver.observe(chartRef.value)
  }
})

watch(
  () => props.option,
  (opt) => {
    applyOption(opt)
  },
  { deep: true }
)

onUnmounted(() => {
  if (resizeTimer) {
    clearTimeout(resizeTimer)
    resizeTimer = null
  }
  resizeObserver?.disconnect()
  resizeObserver = null
  chartInstance?.dispose()
  chartInstance = null
})
</script>

<template>
  <div ref="chartRef" class="screen-chart" />
</template>

<style scoped>
.screen-chart {
  width: 100%;
  height: 100%;
  min-height: 0;
}
</style>
