<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc; width: 410px;" :editor="editorRef" :defaultConfig="toolbarConfig"
             :mode="mode" />
    <Editor style="height: 500px; overflow-y: hidden; width: 410px;" v-model="valueHtml" :defaultConfig="editorConfig"
            :mode="mode" @onChange="handleChange" @onCreated="handleCreated" />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, defineEmits } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import myAxios from "@/api/myAxios";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')
const emit = defineEmits(['richTextContent'])   //子组件向父组件传值
const props = defineProps({
  context: String,
  disableRich: Boolean
})

onMounted(() => {
  setTimeout(() => {
    if(props.context !== undefined) {
      valueHtml.value = props.context   //访问父组件的值，回显
    }
  }, 1500)
})

const toolbarConfig = {
  excludeKeys: [   //去掉富文本部分功能
      "group-video","uploadVideo","insertVideo","todo","codeBlock","insertImage","code"
  ]
}

const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}

editorConfig.readOnly = props.disableRich   //控制富文本是否启用
editorConfig.autoFocus = false   //默认不对焦
editorConfig.MENU_CONF['uploadImage'] = {
  allowedFileTypes: ['image/*'],   //限定只能上传图片格式
  maxFileSize: 1024 * 1024 * 10,   //最大图片10M
  async customUpload(file, insertFn) {
    const res = await myAxios({
      url: '/file/uploadFile',
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      data: {
        biz: "test",
        file: file
      }
    })
    // console.log('图片上传返回值--->',res.data)
    const downloadUrl = 'https://www.carboner.cn:8888/api/file/downloadFile?objectKey=';
    insertFn(downloadUrl + res.data.data, res.alt, res.href)
  }
}

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

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

const handleChange = (editor) => {   //当选项改变时触发emit传值
  emit('richTextContent', valueHtml.value)
}
</script>

<style scoped>
</style>