import { ref } from 'vue'
import * as echarts from 'echarts'
import { guid } from '@/utils/util'

export function useEchart() {
  let chart = null
  let chartVal = ref(null)
  let id = ref(guid())
  const initChart = () => {
    const dom = document.getElementById(id.value)
    chart = echarts.init(dom)
  }
  const setOption = (params, update = false) => {
	initChart()
    chart.setOption(params, update)
    return chart;
  }
  const clearOption = () => {
	   // 将series设置为空数组，可以清空图表内容
    chart.setOption({
		series:[]
	})
  }
  const dispose = () => {
    chart.dispose()
    chart = null
  }
  const resize = () => {
    if (chart) chart.resize()
  }
  onMounted(() => {
    initChart()
    // 监听窗口大小变化
    window.addEventListener('resize', resize)
  })

  return { id, chart, setOption, dispose, initChart,chartVal,clearOption }
}
