<template>
  <div>
    <div ref='editor1' class="myedit"></div>
  </div>
</template>

<script>
import E from 'wangeditor'
export default {
  name: 'editoritem',
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadWang",
      editor: null,
      selectedImageCount: 0, // 记录选择的图片数量
      uploadedImageCount: 0  // 记录已上传的图片数量
    }
  },
  beforeDestroy() {
    if (this.editor != null) {
      this.editor.destroy()
      this.editor = null
    }
  },
  methods: {
    initEditor() {
      const that = this;
      if (this.editor == null) {
        this.editor = new E(that.$refs.editor1)
        this.editor.config.uploadImgServer = this.uploadUrl;
        this.editor.config.uploadImgMaxSize = 6 * 1024 * 1024 // 2M
        this.editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
        this.editor.config.uploadFileName = 'fileName'
        this.editor.config.zIndex = 1

        // 关键配置：允许多选，串行上传
        this.editor.config.uploadImgMultiple = true;
        this.editor.config.uploadImgMaxLength = 5;
        this.editor.config.uploadImgConcurrent = 1;

        this.editor.config.customUploadImg = function (files, insertImgFn) {
          // 获取选择的图片数量
          that.selectedImageCount = files.length;
          that.uploadedImageCount = 0;
          console.log(`已选择 ${that.selectedImageCount} 张图片，准备开始上传`);

          that.$emit('image-selected', that.selectedImageCount);

          const uploadNext = (index) => {
            if (index >= files.length) {
              console.log(`所有 ${files.length} 张图片上传处理完毕`);
              that.$emit('all-images-uploaded', that.uploadedImageCount);
              return;
            }

            const formData = new FormData();
            formData.append(that.editor.config.uploadFileName, files[index]);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', that.uploadUrl);

            xhr.onload = function () {
              if (xhr.status >= 200 && xhr.status < 300) {
                const result = JSON.parse(xhr.responseText);
                if (result.errno === 0 && result.data && result.data[0] && result.data[0].url) {
                  insertImgFn(result.data[0].url);
                  that.uploadedImageCount++;
                  that.$emit('image-uploaded', that.uploadedImageCount, that.selectedImageCount);
                } else {
                  console.error(`第 ${index+1} 张图片上传失败:`, result);
                  that.$emit('image-upload-error', index+1);
                }
              } else {
                console.error(`第 ${index+1} 张图片上传请求失败:`, xhr.statusText);
                that.$emit('image-upload-error', index+1);
              }
              uploadNext(index + 1);
            };

            xhr.onerror = function () {
              console.error(`第 ${index+1} 张图片上传出错`);
              that.$emit('image-upload-error', index+1);
              uploadNext(index + 1);
            };

            // 发送请求
            xhr.send(formData);
          };

          // 开始上传第一张
          uploadNext(0);
        };

        this.editor.config.menus = [
          'head', 'bold', 'fontSize', 'fontName', 'italic', 'underline',
          'strikeThrough', 'indent', 'lineHeight', 'foreColor', 'backColor',
          'link', 'list', 'todo', 'justify', 'quote', 'emoticon', 'image',
          'table', 'code', 'splitLine', 'undo', 'redo'
        ]

        this.editor.config.onchange = function (newHtml) {
          that.$emit("on-text-change", newHtml);
        }

        this.editor.config.pasteFilterStyle = false
        this.editor.config.onchangeTimeout = 500

        this.editor.create()
      }
      this.editor.txt.html("");
    },

    setText(text) {
      if (this.editor == null) {
        this.initEditor()
      }
      this.editor.txt.html(text || "");
    },

    getSelectedImageCount() {
      return this.selectedImageCount;
    },

    getUploadedImageCount() {
      return this.uploadedImageCount;
    }
  }
}
</script>

<style scoped>
.myedit {
  min-height: 300px;
  z-index: 1 !important;
}
.w-e-toolbar, .w-e-text-container {
  z-index: 1 !important;
}
</style>
