import { defineComponent, nextTick, onMounted, reactive, ref, defineExpose } from 'vue'

import { basicSetup } from 'codemirror'
import { EditorView } from '@codemirror/view'
import { EditorState, StateEffect } from '@codemirror/state'
import { javascript } from '@codemirror/lang-javascript'
import { useId } from '@/hooks'
// '{"paramName":"page","paramType":"int","paramDesc":"分页页码","require":true}'
export const CodeMirrorTsx = defineComponent({
  name: 'code-mirror-tsx',
  props: {
    bodyType: {
      type: String,
      default: 'javascript' //  javascript json
    },
    bodyJson: {
      type: String,
      default: ''
    }
  },
  setup (props, ctx) {
    const id = useId()

    const state = reactive({})

    const editorRef = ref()

    const view = ref<EditorView>()

    const transDoc = () => {
      console.log(' props.bodyType:', props.bodyType)

      return props.bodyType === 'javascript' ? props.bodyJson : JSON.stringify(JSON.parse(props.bodyJson), null, '\t')
    }

    const createView = () => {
      const editorState = EditorState.create({
        doc: transDoc(),
        extensions: [basicSetup, javascript()]
      })
      // transDoc(),
      view.value = new EditorView({
        state: editorState,
        parent: document.getElementById(`editorRef-${id}`)!
      })

      setTimeout(() => {
        console.dir(document.getElementById(`editorRef-${id}`))

        // console.log(document.getElementById(`editorRef-${id}`)!.getValue())
      }, 10000)
    }

    onMounted(() => {
      nextTick(() => {
        setTimeout(() => {
          createView()
        }, 1000)
      })
    })

    return () => (
      <div ref="editorRef" id={`editorRef-${id}`}></div>
    )
  }
})
