<template>
  <div class="white" ref="content">
    <div ref="chart"></div>
  </div>
</template>

<script>
import { isIE } from '@/utils'

import elementResizeDetector from 'element-resize-detector'
export default {
  name: 'initChart',
  data () {
    return {
      chart: null,
      resizeObserver: null
    }
  },
  beforeDestroy () {
    this.cleanup()
  },
  mounted () {
    this.setupResizeObserver()
  },
  methods: {
    setupResizeObserver () {
      if (!this.$refs.content) return

      if (isIE()) {
        this.resizeDetector = elementResizeDetector()
        this.resizeDetector.listenTo(this.$refs.content, () => {
          if (this.chart) {
            this.onResize()
          }
        })
        return
      }
      this.resizeObserver = new ResizeObserver(entries => {
        window.requestAnimationFrame(() => {
          if (!Array.isArray(entries) || !entries.length) return
          // 处理尺寸变化的代码
          if (this.chart) {
            this.onResize()
          }
        })
      })
      this.resizeObserver.observe(this.$refs.content)
    },
    cleanup () {
      window.removeEventListener('resize', this.onResize)
      if (isIE() && this.resizeDetector) {
        this.resizeDetector.removeListener(
          this.$refs.content,
          this.handleResize
        )
      }
      if (this.resizeObserver) {
        this.resizeObserver.disconnect() // 停止监听
        this.resizeObserver = null
      }
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
    },
    init () {
      this.chart = this.$echarts.init(this.$refs.chart, null, { renderer: 'svg' })
      this.setRect()
      window.addEventListener('resize', this.onResize)
      return this.chart
    },
    setRect () {
      const { height, width } = this.$refs.content.getBoundingClientRect()
      console.log(height, width)
      this.$refs.chart.style.width = this.$refs.content.offsetWidth + 'px'
      this.$refs.chart.style.height = this.$refs.content.offsetHeight + 'px'
    },
    onResize () {
      this.$nextTick(() => {
        if (!this.$refs.chart || !this.chart) return
        this.setRect()
        this.chart.resize()
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
