<template>
  <div ref="echartsRef"
    :class="className"
    :style="{ height: height, width: width }" />
</template>

<script setup>
import * as echarts from 'echarts'
const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '600px'
  },
  autoResize: {
    type: Boolean,
    default: true
  },
  chartData: {
    type: Object,
    required: true
  }
})
const echartsRef = ref(null)
const chart = shallowRef(null)
let myThousand = false // 是否显示万单位

const setOptions = () => {
  chart.value.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: props.chartData.legend
    },
    toolbox: {
      feature: {
        saveAsImage: {},
        magicType: {
          type: ['stack', 'tiled'] // 切换图表类型
        },
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        // type: 'category',
        // boundaryGap: false,
        data: props.chartData.xAxis
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: props.chartData.series
  }, true)
}

watchEffect(() => {
  if (!chart.value) return
  myThousand = props.chartData.series?.some(o => {
    return o.data.some(num => num >= 10000)
  })
  setOptions()
})

const initChart = () => {
  chart.value = echarts.init(echartsRef.value)
}

const resize = () => {
  chart.value.resize()
}

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onBeforeUnmount(() => {
  if (!chart.value) {
    return
  }
  window.removeEventListener('resize', resize)
  chart.value.dispose()
  chart.value = null
})
</script>