<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useUserStore } from '@/stores/user'
import { ACCESS_TOKEN } from '@/utils/constants'

defineOptions({
  name: 'ElEditor'
})

interface Props {
  modelValue: string
  mode?: string
  height?: string
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'simple',
  height: '400px'
})
const emits = defineEmits(['update:modelValue', 'change'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = computed({
  get: () => props.modelValue,
  set: value => emits('update:modelValue', value)
})

const userStore = useUserStore()
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: `${import.meta.env.VITE_BASE_API}/file/upload`,
      headers: { [ACCESS_TOKEN]: userStore.token },
      fieldName: 'file',
      // 自定义插入图片
      customInsert(res: any, insertFn: Function) {
        const file = res?.data
        insertFn(import.meta.env.VITE_BASE_PATH + file)
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const handleChange = (editor: any) => {
  emits('change', editor.getHtml())
}
</script>

<template>
  <div style="border: 1px solid var(--el-border-color)" class="w-full">
    <Toolbar
      style="border-bottom: 1px solid var(--el-border-color)"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="overflow-y: hidden"
      :style="{ height: height }"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<style lang="scss" scoped></style>
