import { defineComponent, h, ref, watchEffect, onMounted } from 'vue';
import { type OutputModes, Repl, useStore, useVueImportMap } from './src'
import MonacoEditor from './src/editor/MonacoEditor.vue'
import { useRoute } from 'vue-router';
import CodeMirrorEditor from './src/editor/CodeMirrorEditor.vue'
import { useDataListInit } from '@/views/project/remote/list/components/ProjectItemsList/hooks/useData.hook'

const { list } = useDataListInit()

export default defineComponent({
  name: 'createRemote',
  setup(props) {
    const resultData = ref()
    const route = useRoute();
    if(route.path.indexOf('/remote/edit') != -1){
      // TODO 通过ID获取组件数据
      let id = route.params.id[0]
      console.log('list',list)
      list.value.forEach(item => {
        if(item.id == id){
          resultData.value = item.data
        }
      })
    }
    
    const window = globalThis.window as any
    window.process = { env: {} }

    const query = new URLSearchParams(location.search)
    console.log('location',location.origin,location.search)
    const { importMap: builtinImportMap, vueVersion } = useVueImportMap({
      runtimeDev: import.meta.env.PROD
        ? undefined
        : `${location.origin}/src/views/project/remote/create/src/vue-dev-proxy`,
      serverRenderer: import.meta.env.PROD
        ? undefined
        : `${location.origin}/src/views/project/remote/create/src/vue-server-renderer-dev-proxy`,
    })
    console.log('builtinImportMap',builtinImportMap,vueVersion,ref(query.has('so')),ref((query.get('om') as OutputModes) || 'preview'),location.hash,)
    const store = (window.store = useStore(
      {
        builtinImportMap,
        vueVersion,
        showOutput: ref(query.has('so')),
        outputMode: ref((query.get('om') as OutputModes) || 'preview'),
      },
      resultData.value,
    ))
    console.info(store)

    watchEffect(() => resultData.value = store.serialize())

    const theme = ref<'light' | 'dark'>('light')
    window.theme = theme
    const previewTheme = ref(false)
    window.previewTheme = previewTheme
    return () => h(Repl, {
      store,
      theme: theme.value,
      previewTheme: previewTheme.value,
      editor: MonacoEditor,
      // layout: 'vertical',
      ssr: true,
      sfcOptions: {
        script: {
          // inlineTemplate: false
        },
      },
      // showCompileOutput: false,
      // showImportMap: false
    })
  },
});

