import { merge } from 'lodash-es'
import { loadEchartsLibs } from '/@/components/Echarts/src/tools'
import * as EchartsHelper from './inject'

// 全局注入工具函数
window.EchartsHelper = EchartsHelper

export default {
    data() {
        return {
            option: {},
        }
    },
    methods: {
        loadLibs: loadEchartsLibs,
        init() {
            // 如果已经初始化过了，就直接更新配置项
            if (this.chart && this.chart.setOption) {
                this.chart.setOption(this.option)
                return
            }

            // 初始化组件
            const chart = window.echarts.init(document.getElementById(this.option.id))
            // 设置图表配置项
            chart.setOption(this.option)
            this.chart = chart
        },
        changeOption(option) {
            if (!option?.id) {
                return
            }

            this.option = merge(this.option, option)
            if (typeof window.echarts === 'object' && typeof window.echarts.init === 'function') {
                this.init()
            } else {
                this.loadLibs().then(() => {
                    this.init()
                })
            }
        },
    },
}
