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

<script>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  onBeforeUnmount,
  onMounted,
  ref,
  shallowRef,
  toRefs,
  watch,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import request from "@/utils/request";
import { getToken } from "@/utils/auth";

export default {
  components: { Editor, Toolbar },
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    minHeight: {
      type: String,
      default: "150px",
    },
    height: {
      type: String,
      default: "320px",
    },
    width: {
      type: String,
      default: "100%",
    },
    focus: {
      type: Boolean,
      default: false,
    },
    mode: {
      type: String,
      default: "default",
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    // disabled:{
    //   type:B
    // }
  },
  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 = {
      // toolbarKeys: [
      //   "bold",
      //   "underline",
      //   "italic",
      //   "through",
      //   "color",
      //   "bgColor",
      //   "fontSize",
      //   "fontFamily",
      //   "lineHeight",
      //   "uploadImage",
      //   // "emotion",
      //   // "redo",
      //   // "undo",
      // ],
    };
    const editorConfig = {
      placeholder: "请输入内容...",
      autoFocus: props.focus,
      // maxLength: 140,
      readOnly: props.readOnly,
      MENU_CONF: {
        uploadImage: {
          async customUpload(file, insertFn) {
            const fd = new FormData();
            fd.append("file", file);
            const resp = await request({
              url: "/common/upload",
              method: "post",
              data: fd,
              headers: {
                Authorization: "Bearer " + getToken(),
              },
            });

            insertFn(resp.url, "", resp.url);
          },
        },
      },
    };
    onMounted(() => {
      // console.log(editorRef.value.getConfig());
    });
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;

      if (editor == null) return;
      editor.destroy();
    });

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

    const handleChange = (editor) => {
      if (editor.isEmpty()) {
        context.emit("update:modelValue", "");
      } else {
        context.emit("update:modelValue", editor.getHtml());
      }
    };
    const emitBlur = () => {
      context.emit("blur", editorRef.value);
      // editorRef.value.emit("blur");
    };
    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      height,
      handleCreated,
      handleChange,
      emitBlur,
    };
  },
};
</script>
<style lang="scss" scoped>
.disabled {
  background-color: #f5f7fa;
  cursor: not-allowed;

  :deep(.w-e-text-container) {
    background-color: inherit;
    // color: green;
    opacity: 0.5;
  }

  :deep(.w-e-toolbar) {
    user-select: none;
    pointer-events: none;
    background-color: inherit;
  }
}
</style>
