<!--
 * @Author: zk
 * @Date: 2021-09-16 16:24:53
 * @LastEditTime: 2021-11-02 15:45:53
 * @LastEditors: Please set LastEditors
 * @Description: 折线图
 * @FilePath: \vue-admin-template-master\src\layout\components\Echarts\commonChartsLine.vue
-->
<template>
  <div class="ChartsLine" :id="id"></div>
</template>

<script>
// 折线图初始数据
import ChartsLine from './commonChartsLine'
export default {
  name: 'ChartsLine',
  props: {
    // 折线图生成所需id
    id: {
      type: String,
      default: ''
    },
    // 折线图额外的数据
    option: {
      type: Object,
      default: () => { }
    }
  },
  mixins: [ChartsLine],
  data () {
    return {
      myChart: null, //折线图实例
      desc: 300 // 防抖时间
    }
  },
  mounted () {
    // 生成图形
    this.initEcharts()
    // 监听页面缩放 防止dom重复渲染
    window.addEventListener('resize', _.debounce(this.handle, this.desc))
  },
  beforeDestroy () {
    // 销毁实例和移除监听
    if (this.myChart) {
      this.myChart.dispose()
      window.removeEventListener('resize', this.handle)
      this.myChart = null
    }
  },
  watch: {
    // 监听数据变化 重绘图形
    option: {
      handler (obj) {
        // 初始数据和额外的配置数据耦合
        const objData = _.cloneDeep(this.options)
        _.merge(objData, obj)
        // 生成柱状图
        this.myChart.setOption(objData)
      },
      deep: true
    }
  },
  methods: {
    /**
     * @description: 图形缩放
     * @param {*}
     * @return {*}
     */
    handle () {
      if (this.myChart) {
        this.myChart.resize()
      }
    },
    /**
     * @description: 初始化echarts
     * @param {*}
     * @return {*}
     */
    initEcharts () {
      // 初始数据和额外的配置数据耦合
      const objData = _.cloneDeep(this.options)
      _.merge(objData, this.option)
      // dom
      const chartDom = document.getElementById(this.id)
      // 初始化
      this.myChart = this.$echarts.init(chartDom)
      // 生成柱状图
      this.myChart.setOption(objData)
      // 事件
      this.myChart.on('click', params => {
        this.$emit('getChartData', params)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ChartsLine {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
</style>