<template>

</template>

<script setup>
import { createApp, watch, onBeforeUnmount } from "vue";
import { loadModule } from 'vue3-sfc-loader'
import * as echarts from 'echarts'


const props = defineProps({
    chartStr: {
        type: String,
        default: ''
    },
    containerId: {
        type: String,
        default: ''
    }
})



let currentApp = null;
let currentStyle = null;

const processComponentString = (str) => {
    return str.replace(/import.*from.*['"]echarts['"];?\n?/g, '');
};

onBeforeUnmount(() => {
    if (currentApp) {
        currentApp.unmount();
        currentApp = null;
    }
    if (currentStyle) {
        currentStyle.remove();
        currentStyle = null;
    }
})

watch(
    () => props.chartStr,
    async (newVal) => {
        if (newVal) {
            try {
                // 清理之前的实例
                if (currentApp) {
                    currentApp.unmount();
                    currentApp = null;
                }
                const options = {
                    moduleCache: {
                        vue: Vue
                    },
                    getFile(url) {
                        if (url === 'file.vue') {
                            const processedStr = processComponentString(props.chartStr);
                            return Promise.resolve(processedStr)
                        }
                    },
                    addStyle(textContent) {
                        const style = document.createElement('style');
                        style.textContent = textContent;
                        document.head.appendChild(style);
                        return style;
                    },
                    handleModule: async (type, source, path, options) => {
                        if (type === '.vue') {
                            return Vue.defineComponent(source.default);
                        }
                    }
                };
                // 加载组件
                const component = await loadModule('file.vue', options);
                // 创建新实例
                const app = createApp(component).use(echarts);

                app.config.globalProperties.$echarts = echarts;
                app.config.globalProperties.echarts = echarts;

                app.mount(`#${props.containerId}`);
                currentApp = app;
            } catch (error) {
                console.error('创建图表失败:', error);
            }
        }
    },
    { immediate: true }
)
</script>

<style scoped>
#demoChart {
    width: 100%;
    height: 100%;
}
</style>