<template>
  <!-- 简单版的图文编辑器 可以上传 截图上传图片 能实现简单的图文编辑功能 -->
  <div class="text-editor">
    <div
      class="text-editor__title"
      @click.stop="handlePreview"
    >
      <el-image
        class="text-editor__preview-icon"
        :src="previewIcon"
      > </el-image>
      <p class="text-editor__preview-text">查看大图</p>
      <span
        v-if="isUploading"
        class="text-editor__upload-status text-editor__upload-status--loading"
      >
        <i class="el-icon-loading"></i>
        上传中
      </span>
      <span
        v-if="uploadSuccess"
        class="text-editor__upload-status text-editor__upload-status--success"
      >
        <i class="el-icon-check"></i>
        上传成功
      </span>
    </div>
    <!-- 只展示不编辑 -->
    <div
      v-if="!contenteditable"
      :id="domid"
      class="text-editor__content text-editor__content--readonly"
      v-html="sanitizedRemark"
    ></div>
    <!-- 可以编辑 -->
    <div
      v-else
      :id="domid"
      class="text-editor__content"
      :class="{'text-editor__content--active': contenteditable}"
      :contenteditable="contenteditable"
      @blur="handleContentChange"
      @input="handleContentChange"
    ></div>
    <!-- 查看大图 -->
    <el-dialog
      title="查看大图"
      append-to-body
      center
      :visible.sync="showPreviewDialog"
      class="text-editor__preview-dialog"
    >
      <div
        class="text-editor__preview-content"
        v-html="sanitizedRemark"
      ></div>
    </el-dialog>
  </div>
</template>
<script>
import { base64toFile } from '@/utils/index'
import DOMPurify from 'dompurify'
import ossUpload from '../utils/ossUpload'
import { getSystem } from '../utils/tools'
export default {
  name: 'BiTextEditor',
  props: {
    remark: {
      type: String,
      default: ''
    },
    contenteditable: {
      type: Boolean,
      default: false
    },
    domid: {
      type: String,
      required: true
    },
    uploadConfig: {
      type: Object,
      default: () => ({
        dir: `/${getSystem()}/`
      })
    },
    upload: {
      type: Function,
      default: null
    }
  },

  data() {
    return {
      srcList: [],
      editorContent: null,
      showPreviewDialog: false,
      previewIcon: 'https://wanxiaomeng-1255977238.cos.ap-shanghai.myqcloud.com/mxy/web/eye.png',
      isUploading: false,
      uploadSuccess: false,
      uploadStatusTimer: null
    }
  },

  computed: {
    sanitizedRemark() {
      return this.remark ? DOMPurify.sanitize(this.remark) : ''
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.editorContent = document.getElementById(`${this.domid}`)
      if (this.remark && this.remark.length > 0 && this.contenteditable && this.editorContent) {
        this.editorContent.innerHTML = this.sanitizedRemark
      }
    })
  },

  beforeDestroy() {
    if (this.uploadStatusTimer) {
      clearTimeout(this.uploadStatusTimer)
    }
  },

  methods: {
    handlePreview() {
      if (!this.remark || this.remark.trim().length === 0) {
        this.$message.warning('内容为空')
        return
      }
      this.showPreviewDialog = true
    },

    async handleContentChange() {
      if (!this.editorContent) return
      const imgElements = this.editorContent.querySelectorAll('img')
      const imgList = Array.from(imgElements).filter((img) => img.src.includes('data:image'))
      if (imgList.length > 0) {
        this.isUploading = true
        this.uploadSuccess = false
        await this.processImages(imgList)
        this.isUploading = false
        this.uploadSuccess = true
        this.resetUploadStatus()
      }
      this.emitContentChange()
    },

    async processImages(imgList) {
      for (const img of imgList) {
        if (!img.src.includes('http:')) {
          const file = base64toFile(img.src)
          try {
            const result = await (this.upload || ossUpload)(file, this.uploadConfig)
            if (result && result.data) {
              img.src = result.data
            }
          } catch (error) {
            console.error('图片上传失败:', error)
            this.$message.error('图片上传失败')
            this.isUploading = false
          }
        }
      }
    },
    resetUploadStatus() {
      if (this.uploadStatusTimer) {
        clearTimeout(this.uploadStatusTimer)
      }
      this.uploadStatusTimer = setTimeout(() => {
        this.uploadSuccess = false
      }, 3000)
    },
    emitContentChange() {
      const content = this.editorContent.innerHTML
      this.$emit('resultReamrk', content)
      this.$emit('update:remark', content)
    }
  }
}
</script>
<style lang="scss" scoped>
.text-editor {
  &__title {
    display: flex;
    align-items: center;
    width: 100%;
    cursor: pointer;
  }

  &__preview-icon {
    width: 20px;
    height: 20px;
    margin-right: 5px;
  }

  &__preview-text {
    color: #00bf8a;
    margin-right: 10px;
  }

  &__upload-status {
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-left: 10px;

    i {
      margin-right: 5px;
    }

    &--loading {
      color: #e6a23c;
      font-weight: bold;
    }

    &--success {
      color: #00bf8a;
      font-weight: bold;
    }
  }

  &__content {
    width: 100%;
    height: 150px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
    overflow: auto;
    line-height: 20px;
    outline: #c0c4cc;

    &--readonly {
      background: #f5f7fa;
      color: #c0c4cc;
    }

    &--active {
      background: #fff;
      color: #333;
    }

    :deep(img) {
      max-width: 80px;
      max-width: 80px;
      margin: 10px 10px 0 0;
    }
  }

  &__preview-dialog {
    :deep(.el-dialog__body) {
      padding: 20px 30px;
    }
  }

  &__preview-content {
    width: 100%;
    line-height: 1.5;
    overflow: auto;

    img {
      display: block;
      max-width: 100%;
      margin-bottom: 20px;
    }
  }
}
</style>
