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

<script>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { getToken } from "@/utils/auth";
import { onBeforeUnmount, ref, shallowRef, onMounted, toRefs } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const baseUrl = import.meta.env.VITE_APP_BASE_API;
export default {
  components: { Editor, Toolbar },
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    minHeight: {
      type: [String, Number],
      default: 300,
    },
    height: {
      type: [String, Number],
      default: 300,
    },
    width: {
      type: [String, Number],
      default: 820,
    },
    mode: {
      type: String,
      default: "default", // or 'simple'
    },
  },
  setup(props, context) {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref("");
    watch(
      () => props.modelValue,
      (val) => {
        valueHtml.value = val;
      },
      { immediate: true }
    );
    const { height } = toRefs(props);
    const toolbarConfig = {
      excludeKeys: [],
    };
    const editorConfig = {
      placeholder: "请输入内容...",
      MENU_CONF: {
        uploadImage: {
          server: `${baseUrl}/common/upload`,
          // 自定义增加 http  header
          fieldName: "file",
          headers: {
            Authorization: `Bearer ${getToken()}`,
          },
          customInsert(res, insertFn) {
            // res 即服务端的返回结果
            console.log(res);
            // 从 res 中找到 url alt href ，然后插图图片
            insertFn(res.url, null, null);
          },
        },
      },
    };

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

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };
    const handleChange = (editor) => {
      context.emit("update:modelValue", editor.getHtml());
    };
    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      height,
      handleCreated,
      handleChange,
    };
  },
};
</script>
