import EchartsExtens from './libs/echarts-extens.js';
import echartsMap from './libs/echarts-import.js';
import { useTheme } from './libs/echarts-style.js';

class Echarts {
    constructor(echarts) {
        this.echarts = echarts;

        this.loadeds = [];

        this.destroy();

        this.resize();

        // this.exit();
    }

    /**
     * 退出页面时销毁实例（包含刷新）
     */
    exit() {
        window.onbeforeunload = () => {
            this.destroy();
        };
    }

    /**
     * 切换页面销毁实例
     */
    destroy() {
        while (this.loadeds.length) {
            const echarts = this.loadeds.pop();

            echarts.dispose();
        }
    }

    /**
     * 页面尺寸变化重载实例
     */
    resize() {
        let timer = null;

        window.addEventListener('resize', () => {
            clearTimeout(timer);
            timer = setTimeout(() => {
                this.loadeds.forEach((x) => {
                    x.resize();
                });
            }, 700);
        });
    }

    /**
     * 继承option
     */
    extens(FirstOBJ, SecondOBJ) {
        let echartsExtens = new EchartsExtens();

        return echartsExtens.extens(FirstOBJ, SecondOBJ);
    }

    /**
     * 调用指定图表方法
     */
    async dispatch(echartsName, param) {
        let names = Object.keys(echartsMap);

        if (names.indexOf(echartsName) === -1) {
            console.error('提示', `该图表名称${echartsName}不存在`);

            return false;
        }

        const asyncComponent = await echartsMap[echartsName]();

        return asyncComponent.default(param);
    }

    setOption(instance, opt) {
        // instance.clear();

        instance.setOption(opt, true);

        this.loadeds.push(instance);

        return instance;
    }
    /**
     * 渲染图表
     */
    render(dom, opt) {
        let instance = this.echarts.init(dom, null, { locale: 'ZH' });
        instance.clear();

        instance.setOption(opt);

        this.loadeds.push(instance);

        return instance;
    }
}

let $echarts = null;

export let use = (pack) => {
    $echarts = new Echarts(pack);
};

export { $echarts, useTheme };
