<template>
  <div :id="editorId" class="editorContainer"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed, toRaw } from 'vue'
import * as monaco from 'monaco-editor'

const props = defineProps({
  value: String,
  language: String,
})

const emit = defineEmits(['change'])
const editor = ref(null)
const editorId = computed(() => `editor_${Math.random().toString(36).slice(2, 11)}`)

const getEditorValue = () => toRaw(editor.value)?.getValue() || ''

let resizeObserver = null

onMounted(() => {
  const el = document.getElementById(editorId.value)

  if (!el) {
    // console.warn('[MonacoEdit]找不到容器元素')
    return
  }

  const initEditor = () => {
    if (editor.value || el.clientWidth === 0 || el.clientHeight === 0) return

    // console.log('[MonacoEdit]尺寸可用，初始化编辑器')

    monaco.editor.defineTheme('custom-light', {
      base: 'vs',
      inherit: true,
      rules: [],
      colors: {
        'editorGutter.background': '#EEEEEE',
      },
    })

    editor.value = monaco.editor.create(el, {
      value: props.value || '',
      language: props.language || 'python',
      minimap: { enabled: true },
      colorDecorators: true,
      readOnly: false,
      theme: 'custom-light',
      automaticLayout: true,
    })

    editor.value.onDidChangeModelContent(() => {
      emit('change', getEditorValue())
    })

    // console.log('[MonacoEdit]初始化完成')
  }

  // 使用 ResizeObserver 监听尺寸变化
  resizeObserver = new ResizeObserver(() => {
    if (el.clientWidth > 0 && el.clientHeight > 0 && !editor.value) {
      initEditor()
    }
  })

  resizeObserver.observe(el)
})

onUnmounted(() => {
  if (editor.value) {
    editor.value.dispose()
    editor.value = null
  }

  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
})
</script>

<style>
.editorContainer {
  height: 400px !important;
}
</style>