import type { EChartsOption } from 'echarts'
import { tryOnMounted } from '@vueuse/core'
import { isProdMode } from '@/utils/env'

// 组件名称
export const name = 'Echarts'

export interface EchartsInstance {
    setOption: (option: Partial<EChartsOption>) => Promise<void>
}

/**
 * 注册 Echarts 实例
 * @param option Echarts 配置项
 */
export function useEcharts<T extends EchartsInstance, P extends EChartsOption>(
    option?: P,
): [(instance: T) => void, EchartsInstance] {
    const instanceRef = ref<T>()

    function register(instance: T) {
        if (isProdMode()) {
            if (instance === unref(instanceRef)) {
                return
            }

            onUnmounted(() => {
                instanceRef.value = null
            })
        }

        instanceRef.value = instance
        option && instance?.setOption(option)
    }

    function getInstance() {
        const instance = unref(instanceRef)
        if (!instance) {
            console.warn('Echarts instance is undefined!')
        }
        return instance as T
    }

    return [
        register,
        {
            setOption: (option: Partial<P>): Promise<void> => {
                return new Promise((resolve) => {
                    tryOnMounted(() => {
                        getInstance()?.setOption(option)
                        resolve()
                    })
                })
            },
        },
    ]
}
