<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden;"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadImageApi } from "../../api/contentConfig";

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['update:modelValue', 'image-upload']);

const editorRef = shallowRef();
const valueHtml = ref(props.modelValue);

watch(() => props.modelValue, (newValue) => {
  if (newValue !== valueHtml.value) {
    valueHtml.value = newValue;
  }
});

watch(valueHtml, (newValue) => {
  emit('update:modelValue', newValue);
});

const toolbarConfig = {};
const editorConfig = { 
  placeholder: '请输入内容...',
  MENU_CONF: {}
};

editorConfig.MENU_CONF['uploadImage'] = {
  async customUpload(file, insertFn) {
    try {
      const response = await uploadImageApi(file);
      const imageUrl = 'http://123.249.121.26:8801/images/' + response.data;
      insertFn(imageUrl);
    } catch (error) {
      console.error('Image upload failed:', error);
    }
  }
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

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

onMounted(() => {
  setTimeout(() => {
    valueHtml.value = props.modelValue;
  }, 100);
});
</script>

<style scoped>
.wysiwyg-editor {
  border: 1px solid #ccc;
  z-index: 100;
}
</style>

