<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import WangEditor from 'wangeditor';
import { fetchUpload } from '@/service/api/common';

const editor = ref<WangEditor>();
const domRef = ref<HTMLElement>();

const context = defineModel<string>();
const props = defineProps<{
  height?: number;
  disabled?: boolean;
}>();
const uploadConfig = {
  // 服务器端点
  server: '/smqjh-system/api/v1/files', // 请替换为你的图片上传接口
  // 限制大小
  maxSize: 5 * 1024 * 1024, // 5M
  // 限制类型
  allowedFileTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'],
  // 超时时间
  timeout: 30 * 1000
};
async function renderWangEditor() {
  editor.value = new WangEditor(domRef.value);
  setEditorConfig();
  configureImageUpload();
  editor.value.create();
  await nextTick();
  if (props.disabled) {
    editor.value.disable();
  }
  if (context.value) {
    editor.value.txt.html(context.value);
  }
  editor.value.config.onchange = (newHtml: string) => {
    context.value = newHtml;
    console.log(newHtml, 'newHtml');
  };
}

function setEditorConfig() {
  console.log(editor.value, 'editor.valueeditor.value');

  if (editor.value?.config?.zIndex) {
    editor.value.config.zIndex = 1000;
  }
  if (editor.value) {
    editor.value.config.height = props.height || 800;
  }
  // 启用粘贴文本保持格式
  editor.value!.config.pasteFilterStyle = true;
  editor.value!.config.pasteIgnoreImg = false;
  editor.value!.config.pasteTextHandle = (content: string) => {
    return content;
  };
}
function configureImageUpload() {
  if (!editor.value) return;

  // 配置图片上传参数
  const config = editor.value.config;

  // 设置图片上传配置
  config.uploadImgServer = uploadConfig.server;
  config.uploadImgMaxSize = uploadConfig.maxSize;
  config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
  config.uploadImgTimeout = uploadConfig.timeout;
  config.customUploadImg = async (files: File[], insertFn: (url: string) => void) => {
    try {
      const result = await fetchUpload(files[0]);
      const imageUrl = result.data.url;
      insertFn(imageUrl);
    } catch (error) {
      window.$message?.error(`上传失败${error}`);
    }
  };
}
onMounted(() => {
  renderWangEditor();
});
</script>

<template>
  <div class="h-full w-full">
    <div ref="domRef" class="w-full bg-white dark:bg-dark"></div>
  </div>
</template>

<style scoped>
:deep(.w-e-toolbar) {
  background: inherit !important;
  border-color: #999 !important;
}
:deep(.w-e-text-container) {
  background: inherit;
  border-color: #999 !important;
}
</style>
