<template>
  <div :id="elId" style="height:100%;width:100%" />
</template>

<script>
import * as echarts from 'echarts';
import { debounce, uuid } from "../../utils/index";
// 引入公共样式
import baseOption from "./baseOption"

export default {
    name: 'TestEcharts',
    data() {
        return {
            elId: "",
            vOption: {
                series: [],
            },
        };
    },
    props: {
        optionData: Object,
    },
    computed: {
        // 合并配置对象
        option() {
            return Object.assign({}, baseOption, this.vOption, this.optionData);
        },
    },
    created() {
        this.elId = uuid();
    },
    mounted() {
        // 实例化echarts对象
        this.$nextTick(() => {
            this.initChart();
        });
    },
    beforeDestroy() {
        if (!this.chart) {
            return;
        }
        this.chart.dispose();
        this.chart = null;
    },
    watch: {
        optionData: {
            deep: true,
            handler: function() {
                this.$nextTick(() => {
                    this.initChart();
                });
            },
        },
    },
    methods: {
        // 绘图
        initChart() {
            if(!document.getElementById(this.elId)) return
            this.chart = echarts.init(document.getElementById(this.elId))
            this.chart.showLoading({
                text: 'loading',
                color: 'rgba(84, 112, 198, .95)',
                textColor: '#fff',
                maskColor: 'rgba(255, 255, 255, 0.2)',
                zlevel: 0,
            });

            setTimeout(() => {
                // setOption前隐藏loading事件 
                this.chart.hideLoading();
                this.chart.setOption(this.option);
            }, 500)

            
            const that = this;
            window.addEventListener(
                "resize",
                debounce(() => {    // 引入debounce，防止频繁更改浏览页尺寸出现页面抖动
                    if (that.chart) {
                        that.chart.resize();
                    }
                }, 100)
            );
        },
    },
};
</script>
