<template>
  <div class="width-100 sf-mt-lg relative">
    <span v-if="config?.title">{{ config.title }}</span>
    <div class="mgb20" ref="editor" :style="config?.style"></div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  defineProps,
  watch,
  onBeforeUnmount,
  getCurrentInstance,
} from "vue";
import WangEditor from "wangeditor";
import { useMessage } from "naive-ui";
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;

const message = useMessage();
const props = defineProps({
  val: String,
  title: String,
  config: Object,
  disable: Boolean,
});

const state = reactive({
  html: "",
});

watch(
  () => props.disable,
  (newVal) => {
    if (instance) {
      newVal ? instance.disable() : instance.enable();
    }
  }
);
watch(
  () => props.val,
  () => {
    if (state.html !== props.val) {
      instance.txt.html(props.val);
    }
  }
);
const emit = defineEmits(["getEditorVal"]);
const editor = ref(null);
let instance;

onMounted(() => {
  instance = new WangEditor(editor.value);
  instance.config.zIndex = 1;
  instance.config.uploadImgShowBase64 = false; // 关闭 base64 上传
  instance.config.onchange = function (newHtml) {
    state.html = newHtml;
    emit("getEditorVal", { val: state.html });
  };
  instance.config.onchangeTimeout = 500;
  instance.config.placeholder = "可以在编辑器直接贴图";
  //  instance.config.uploadImgServer = "http://114.218.158.24:9020/upload/img";
  instance.config.uploadFileName = "file";
  instance.config.uploadImgTimeout = 10 * 60 * 1000;
  // 自定义图片上传方法
  instance.config.customUploadImg = function (resultFiles, insertImgFn) {
    const formData = new FormData();
    formData.append("file", resultFiles[0]);
    formData.append("source", "bug");
    formData.append("mask", "");
    formData.append("type", resultFiles[0].type);
    $request.HTTP.components.uploadFormData("upload/img", formData).then(
      (res) => {
        if (res.status === 0) {
          insertImgFn(res.data.ori_url);
        } else {
          console.error("上传失败:", res.msg);
        }
      },
      (err) => {
        console.error("上传失败:", err.message);
      }
    );
  };
  instance.create();
  instance.txt.html(props.val);
  if (props.disable) {
    instance.disable();
  }
});

onBeforeUnmount(() => {
  instance?.destroy();
  instance = null;
});
</script>

<style>
.wangeditor-save {
  position: absolute;
  right: 10%;
  top: 80%;
  z-index: 3;
}
</style>
