<template>
  <div ref="aceRef" style="width: 100%; height:  350px;"></div>
</template>

<script lang="ts" setup>
import { onMounted, watch, ref } from 'vue'
// Ace 是一个用 JavaScript 编写的代码编辑器 仅生成文件
import ace, { Ace } from 'ace-builds'

interface State {
  aceRef?: HTMLElement
  codeEditor?: Ace.Editor
}
const aceRef: any = ref<State>()
const codeEditor: any = ref<State>()

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'javascript'
  },
  theme: {
    tyle: String,
    default: 'github'
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:value'])

onMounted(() => {
  codeEditor.value = ace.edit(aceRef.value!, {
    mode: `ace/mode/${props.language}`,
    theme: `ace/theme/${props.theme}`,
    value: props.value,
    readOnly: props.readonly,
    fontSize: 12,
    tabSize: 2
  })

  codeEditor.value.on('change', () =>
    emits('update:value', codeEditor.value?.getValue())
  )
})

watch(
  () => props.value,
  val => {
    if (codeEditor.value) {
      const currentPosition = codeEditor.value?.selection.getCursor()
      codeEditor.value.setValue(val)
      codeEditor.value.clearSelection()
      codeEditor.value.gotoLine(
        currentPosition.row + 1,
        currentPosition.column,
        true
      )
    }
  }
)
</script>
