<template>
  <div class="border-1px border-gray-200">
    <Toolbar class="border-1px border-gray-200" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor :style="{ height: height + 'px' }" :model-value="modelValue" :defaultConfig="editorConfig" :mode="mode"
      @onCreated="handleCreated" @update:model-value="change($event)" />
  </div>
</template>
<script setup>
import { onBeforeUnmount, toRefs, shallowRef } from 'vue'
import { updateFile } from "@/api/uploadFIle.js";

import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { ElMessage } from 'element-plus';

const props = defineProps({ modelValue: { default: '' }, height: { default: 300 } });
const emits = defineEmits(['update:modelValue']);
const { modelValue } = toRefs(props)

const editorRef = shallowRef();
const toolbarConfig = {
  excludeKeys: ['emotion', 'group-video', 'fullScreen']
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        const res = await updateFile(file.name, file, sessionStorage.getItem('corpId'));
        if (res && res.download_url) {
          insertFn(res.download_url, file.name || '', res.download_url)
        } else {
          ElMessage.error('图片上传失败')
        }
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => editorRef.value && editorRef.value.destroy ? editorRef.value.destroy() : null)

const handleCreated = async (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  // await nextTick();
  // const toolbar = DomEditor.getToolbar(editor)

  // const curToolbarConfig = toolbar.getConfig()
  // console.log(curToolbarConfig.toolbarKeys)
}

function change(value) {
  emits('update:modelValue', value)
}

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