<template>
  <umo-editor
    ref="editorRef"
    v-bind="options"
    @changed="onChanged"
    @created="onCreated"
    @file-upload="onFileUpload"
  />
</template>

<script setup>
import { ref, watch } from 'vue'
import { UmoEditor } from '@umoteam/editor'
import { uploadFile } from '@/api/file'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue'])

const content = ref(props.modelValue)
const editorRef = ref(null)
const isCreated = ref(false)

const options = {
  height: '100%',
}

const onFileUpload = async (file) => {
  const formData = new FormData()
  formData.append('file', file)
  const res = await uploadFile(formData)
  return {
    id: res.data.id,
    url: res.data.url,
  }
}

const onCreated = () => {
  isCreated.value = true
  if (content.value) {
    editorRef.value.setContent(content.value)
  }
}

const onChanged = ({ editor }) => {
  const html = editor.getHTML()
  content.value = html
  emit('update:modelValue', html)
}

watch(
  () => props.modelValue,
  (val) => {
    if (val !== content.value && isCreated.value && editorRef.value) {
      editorRef.value.setContent(val)
    }
  }
)
</script>