<template>
  <!-- 微信小程序使用 ec-canvas -->
  <view v-if="isMp" class="chart-wrapper">
    <uni-ec-canvas id="line-chart" :style="{ width, height }" canvas-id="multi-charts-line" :ec="ec" ref="canvas" />
  </view>

  <!-- H5 / App 使用普通 div 方式挂载 echarts -->
  <div v-else ref="canvasDom" class="chart-wrapper" :style="{ width, height }" />
</template>

<script>
import uniEcCanvas from '@/echarts/uni-ec-canvas/uni-ec-canvas.vue'

export default {
  name: 'EcChart',
  components: {
    uniEcCanvas
  },
  props: {
    chartOption: Object,
    width: { type: String, default: '100%' },
    height: { type: String, default: '300px' }
  },
  data() {
    return {
      ec: {
        lazyLoad: true
      },
      isMp: false
    }
  },
  mounted() {
    this.isMp = process.env.UNI_PLATFORM === 'mp-weixin'

     this.$nextTick(() => {
	  setTimeout(() => {
		if (this.isMp) {
		  this.$refs.canvas.init(this.initChartMp)
		} else {
		  this.initChartWeb()
		}
	  }, 100)
	})
  },
 beforeDestroy() {
   // 只在非小程序端调用 dispose
   if (!this.isMp && this.chart && typeof this.chart.dispose === 'function') {
     this.chart.dispose()
     this.chart = null
   }
 },
  methods: {
    async initChartWeb() {
      const echarts = await import('echarts') // npm 安装的 echarts
      this.chart = echarts.init(this.$refs.canvasDom)
      this.chart.setOption(this.chartOption)
      window.addEventListener('resize', () => {
        this.chart && this.chart.resize()
      })
    },

    // 小程序端初始化 chart 实例
    initChartMp(canvas, width, height, dpr) {
      const echarts = require('@/echarts/uni-ec-canvas/echarts.min.js')
      const chart = echarts.init(canvas, null, {
              width,
              height,
              devicePixelRatio: dpr
            })
      canvas.setChart(chart)
      chart.setOption(this.chartOption)
      this.chart = chart
      return chart
    }
  }
}
</script>

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