<template>
    <div v-resize="_onresize" style="width: 100%;height:100%">
        <div></div>
    </div>
</template>

<script>
let echartsUrl = "https://www.niceloo.com/zt4ird/@qdyfb/common/js-plugin/echarts/4.2.1/echarts.min.js";
import * as ResUtil from "../../../util/global/resLoader"
import resize from "../../../service/directives/resize";
import EchartsOptionTool from "./EchartsOptionTool";

let loadEchartsJsPromise;

async function loadEchartsJs() {
    if (window.echarts) {
        return window.echarts;
    }
    await (loadEchartsJsPromise = loadEchartsJsPromise || ResUtil.loadJs(echartsUrl));
    return loadEchartsJs();
}

export default {
    name: "index",
    EchartsOptionTool,
    directives: {
        resize
    },
    data() {
        return {
            echartsInstance: null,
        }
    },
    props: {
        option: {
            type: Object,
        },
    },
    watch: {
        option: {
            immediate: true,
            handler(newV, oldV) {
                if (!newV || newV === oldV) return;
                this.setOption(newV);
            }
        }
    },
    async mounted() {
    },
    async beforeDestroy() {
        let echartsInstance = await this.getEchartsInstance();
        echartsInstance.dispose();
    },
    methods: {
        ready() {
            return loadEchartsJs();
        },
        async _onresize() {
            let echartsInstance = await this.getEchartsInstance();
            echartsInstance.resize(await this.getSize())
        },
        async getSize() {
            let el = await this._getChartElement();
            let eleP = el.parentElement;
            return {
                width: eleP.clientWidth,
                height: eleP.clientHeight,
            }
        },
        /**
         * 设置配置
         */
        async setOption(option) {
            let echartsInstance = await this.getEchartsInstance();
            echartsInstance.hideLoading();
            echartsInstance.setOption(option);
        },
        /**
         * 获取图表实例
         */
        async getEchartsInstance() {
            await this.ready();
            if (!this.echartsInstance) {
                let el = await this._getChartElement();
                this.echartsInstance = echarts.init(el, null, await this.getSize());
                this.echartsInstance.showLoading();
            }
            return this.echartsInstance;
        },
        //获取echart实例bind的dom元素
        async _getChartElement() {
            if (this.$el) {
                return this.$el.firstChild;
            } else {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve(this._getChartElement())
                    }, 100)
                })
            }
        }
    }
}
</script>

<style scoped>

</style>
