<template>
  <div>
    <QuillEditor ref="myQuillEditor"
                 theme="snow"
                 v-model:content="content"
                 :options="data.editorOption"
                 contentType="html"
                 @update:content="setValue()"
    />
    <!-- 使用自定义图片上传 -->
    <el-upload
      action="/api/files/upload"
      :data="{filePath: filePath}"
      :on-success="handleUploadSuccess"
      name="file"
      :show-file-list="false"
      style="display: none"
      ref="uploadRef"
    >
    </el-upload>
  </div>
</template>

<script setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { reactive, onMounted, ref, toRaw, getCurrentInstance, onUpdated, watch } from 'vue'
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()

const props = defineProps(['value', 'filePath'])
const emit = defineEmits(['updateValue'])
const content = ref('')
const myQuillEditor = ref()
const filePath = ref('')
const data = reactive({
  content: '',
  editorOption: {
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'header': 1 }, { 'header': 2 }],
        ['image'],
        [{ 'direction': 'rtl' }],
        [{ 'color': [] }, { 'background': [] }]
      ]
    },
    placeholder: '请输入内容...'
  }
})

const uploadRef = ref('')

const imgHandler = (state) => {
  if (state) {
    uploadRef.value.$el.querySelector('input').click();
  }
}
// 抛出更改内容，添加安全检查
const setValue = () => {
  if (myQuillEditor.value) {
    try {
      const text = toRaw(myQuillEditor.value).getHTML();
      emit('updateValue', text);
    } catch (e) {
      console.warn('获取HTML内容时出错:', e);
    }
  }
}

function handleUploadSuccess(res, file) {
  // 如果上传成功且编辑器实例存在
  if (res && myQuillEditor.value) {
    try {
      // 获取富文本组件实例
      const quill = toRaw(myQuillEditor.value).getQuill();
      // 获取当前选择
      const selection = quill.getSelection();
      // 安全地获取光标位置，默认为文档末尾
      const length = selection ? selection.index : quill.getLength();
      // 插入图片 res.url为服务器返回的图片地址
      quill.insertEmbed(length, "image", proxy.getFilePrefix + res);
      // 安全地调整光标位置
      try {
        quill.setSelection(Math.min(length + 1, quill.getLength()));
      } catch (e) {
        // 光标位置设置失败不影响功能
        console.warn('设置光标位置时出错:', e);
      }
    } catch (e) {
      console.error('插入图片时出错:', e);
      ElMessage.error("图片插入失败");
    }
  } else {
    ElMessage.error("图片插入失败");
  }
}


onUpdated(() => {
  // 只有当编辑器实例存在且值确实发生变化时才更新内容
  if (myQuillEditor.value && props.value !== undefined) {
    const quill = toRaw(myQuillEditor.value).getQuill();
    const currentHtml = toRaw(myQuillEditor.value).getHTML();

    // 避免不必要的更新
    if ((props.value === '' || props.value === null || props.value === '<p></p>') && currentHtml !== '<p><br></p>') {
      quill.setText('');
    } else if (props.value && props.value !== currentHtml && props.value !== '<p></p>') {
      try {
        toRaw(myQuillEditor.value).setHTML(props.value);
      } catch (e) {
        console.warn('设置HTML内容时出错:', e);
      }
    }
  }
})

// 初始化编辑器
onMounted(() => {
  if (myQuillEditor.value) {
    content.value = props.value || '';
    const quill = toRaw(myQuillEditor.value).getQuill();

    // 添加图片处理程序
    try {
      quill.getModule('toolbar').addHandler('image', imgHandler);
    } catch (e) {
      console.warn('添加工具栏处理程序时出错:', e);
    }

    // 初始设置内容
    if (props.value && props.value !== '<p></p>') {
      try {
        toRaw(myQuillEditor.value).setHTML(props.value);
      } catch (e) {
        console.warn('初始化HTML内容时出错:', e);
      }
    }

    filePath.value = props.filePath;
  }
})
</script>
<style scoped>
</style>
