<template>
  <component :is="remote" v-if="remote" @childClick="childClick" :optionParam="optionParam" />
</template>

<script setup lang="ts">
import { loadModule } from 'vue3-sfc-loader/dist/vue3-sfc-loader'
import { ref, onMounted, getCurrentInstance, defineAsyncComponent } from 'vue'
import * as Vue from 'vue'
import { PropType } from 'vue'
import { option } from './config'
import { CreateComponentType } from '@/packages/index.d'

let remote = ref()
let url = 'http://localhost:3000/getVue3Str'

onMounted(() => {
  load(url)
})
const load = async url => {
  let res = await fetch(url).then(res => res.json())

  const options = {
    moduleCache: {
      vue: Vue
    },
    async getFile() {
      return res.fileStr
    },
    addStyle(textContent) {
      const style = Object.assign(document.createElement('style'), { textContent })
      const ref = document.head.getElementsByTagName('style')[0] || null
      document.head.insertBefore(style, ref)
    }
  }

  // 加载远程组件
  remote.value = defineAsyncComponent(() => loadModule(res.fileName || 'loader.vue', options))
}
const childClick = newVal => {
  console.log('子组件点击事件', newVal)
}

const props = defineProps({
  optionData: {
    type: Object as PropType<typeof option>,
    required: true
  },
  chartConfig: {
    type: Object as PropType<CreateComponentType>,
    required: true
  }
})
console.log('props', props)
const optionParam = ref(props.chartConfig.option ? props.chartConfig.option : option)
</script>

<style lang="scss" scoped></style>
