<template>
  <div style="border: 1px solid #ccc; z-index: 100">
    <!-- 工具栏 -->
    <Toolbar :editor="editorRef" :mode="mode" style="border-bottom: 1px solid #ccc" />
    <!-- 编辑器 -->
    <Editor :model-value="modelValue" :style="style" :disabled="disabled" :default-config="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="handleChange" />
  </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css";
import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IDomEditor, IEditorConfig } from "@wangeditor/editor";
import app from "@/constants/app";
import baseService from "@/service/baseService";

const props = defineProps({
  modelValue: {
    type: String,
    required: true
  },
  mode: {
    type: String,
    default: "default" // 可选值：[default | simple]
  },
  placeholder: {
    type: String,
    default: ""
  },
  style: {
    type: String,
    default: "height: 300px;"
  },
  disabled: {
    type: Boolean,
    default: false
  }
});

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

type InsertFnType = (url: string, alt: string, href: string) => void;

// 编辑器配置（使用 customUpload 替代静态 token URL，每次上传时动态获取 token）
const editorConfig: Partial<IEditorConfig> = {
  placeholder: props.placeholder,
  readOnly: props.disabled,
  MENU_CONF: {
    uploadImage: {
      async customUpload(file: File, insertFn: InsertFnType) {
        const formData = new FormData();
        formData.append("file", file);
        try {
          const res: any = await baseService.upload("/sys/oss/upload", formData);
          if (res.code === 0 && res.data?.src) {
            insertFn(res.data.src, "", "");
          }
        } catch (e) {
          console.error("图片上传失败", e);
        }
      }
    }
  }
};

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

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor;
};

// 编辑器change事件触发
const emit = defineEmits(["update:modelValue"]);
const handleChange = (editor: IDomEditor) => {
  emit("update:modelValue", editor.getHtml());
};
</script>
