<template>
  <div class="tableheader-popper-editdialog">
    <el-dialog
      :visible.sync="dialogVisible"
      title="修改字段说明"
      width="408px"
      custom-class="tableheader-popper-editdialog"
      append-to-body
      @closed="handleClosed"
    >
      <div class="tableheader-popper-editbox">
        <el-form
          :model="popperData"
          label-width="80px"
        >
          <el-form-item label="说明">

            <quill-editor
              ref="myQuillEditor"
              v-model="popperData.content"
              :options="editorOption"

              :disabled="quill_disabled"
              @ready="onEditorReady($event)"
              @change="onEditorChange($event)"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="截图">
            <el-upload
              ref="Upload"
              list-type="picture-card"
              :http-request="httpRequest"
              action="#"
              :file-list="fileList"
              :on-success="success"
              :before-remove="beforeRemove"
              :before-upload="beforeUpload"
            >

              <!-- <el-image
                v-for="
              img
              in
              fileList"
              :key="img"
              :src="img"
              style="width: 100px; height: 100px"
            ></el-image> -->
              <i class="el-icon-add"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          v-if="popperData.id"
          type="text"
          @click="delePopper"
        >清除提示</el-button>
        <div class="action-buttons">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            :disabled="uploadLoading"
            :loading="saveLoading"
            @click="handleSave"
          >确 定</el-button>
        </div>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import './style/index.scss'
import { quillEditor } from 'vue-quill-editor'
import ossUpload from '../../utils/ossUpload'
import { Message } from 'bi-eleme'
export default {
  name: 'BiTableHeaderPopperEdit',
  components: {
    quillEditor
  },
  data() {
    return {
      quill_disabled: false,
      dialogVisible: false,
      saveLoading: false,
      uploadLoading: false,
      popperData: {
        label: '',
        prop: '',
        content: '',
        imgs: []
      },
      fileList: [],
      lastFileData: {},
      lastFile: {
        uid: '',
        url: ''
      },
      editorOption: {
        placeholder: '在这里输入....',
        // formats: ['link', 'header'],
        modules: {
          toolbar: [['bold', 'italic', 'underline', 'link', { align: [] }, { color: [] }, 'clean']]
          // 完全移除 clipboard 配置，避免初始化问题
        }
      }
    }
  },
  inject: ['biTable'],
  computed: {
    editor() {
      return this.$refs.myQuillEditor && this.$refs.myQuillEditor.quill
    }
  },
  mounted() {
    // 确保组件完全挂载后再进行初始化
    this.$nextTick(() => {
      this.$nextTick(() => {
        // 延迟初始化，确保所有依赖都已加载
        this.initializeEditor()
      })
    })
  },
  methods: {
    initializeEditor() {
      // 安全地初始化编辑器
      try {
        if (this.$refs.myQuillEditor && this.$refs.myQuillEditor.quill) {
          const quill = this.$refs.myQuillEditor.quill

          
          // 确保 quill 实例完全初始化
          if (typeof quill.getText === 'function') {
            console.log('Editor initialized successfully')

            // 尝试添加 clipboard matcher 作为备用方案
            this.$nextTick(() => {
              this.quill_disabled = true
              this.addClipboardMatcher(quill)
            })
          }
        }
      } catch (error) {
        console.warn('Editor initialization failed:', error)
      }
    },

    addClipboardMatcher(quill) {
      // 安全地添加 clipboard matcher
      if (quill && quill.clipboard && typeof quill.clipboard.addMatcher === 'function') {
        try {
          quill.clipboard.addMatcher(Node.ELEMENT_NODE, this.desMatcher)
          console.log('Clipboard matcher added successfully')
        } catch (error) {
          console.warn('Failed to add clipboard matcher:', error)
        }
      }
    },
    show(prop) {
      const popperData = this.biTable.headerPopper.findPopperData(prop) || {
        label: '',
        prop: prop,
        content: '',
        imgs: []
      }
      this.$set(this, 'popperData', Object.assign({}, popperData))
      this.dialogVisible = true
      
      this.$nextTick(() => {
        this.fileList = popperData.imgs.map((item) => {
          return {
            name: item,
            url: item
          }
        })

        // 确保编辑器正确初始化
        this.$nextTick(() => {
          if (this.$refs.myQuillEditor && this.$refs.myQuillEditor.quill) {
            // 编辑器已经准备好
            
          }
        })
      })
    },
    onEditorReady(quill) {
      // 安全地初始化编辑器并添加 clipboard matcher
      if (quill) {
        console.log('Quill editor ready')

        // 延迟添加 clipboard matcher，确保 quill 实例完全初始化
        this.$nextTick(() => {
          if (quill.clipboard && typeof quill.clipboard.addMatcher === 'function') {
            try {
              quill.clipboard.addMatcher(Node.ELEMENT_NODE, this.desMatcher)
              console.log('Clipboard matcher added successfully')
            } catch (error) {
              console.warn('Failed to add clipboard matcher:', error)
            }
          } else {
            console.warn('Clipboard API not available')
          }
        })
      }
    },
    onEditorChange({ quill, html, text }) {
      this.popperData.content = html
    },
    desMatcher(node, Delta) {
      const ops = []
      if (Delta && Delta.ops && Array.isArray(Delta.ops)) {
        Delta.ops.forEach((op) => {
          if (op.insert && typeof op.insert === 'string') {
            // 如果粘贴了图片，这里会是一个对象，如果是字符串则可以添加
            const obj = {
              insert: op.insert
            }
            if (op.attributes) {
              obj.attributes = op.attributes
            }
            ops.push(obj)
          } else if (op.insert && op.insert.image) {
            // 给出提醒
            console.log('图片不可粘贴，请使用图片上传按钮哦！')
            // 不添加图片操作，只保留文本
          } else if (op.insert && typeof op.insert === 'object') {
            // 处理其他类型的插入内容（如表格、列表等）
            // 可以根据需要决定是否保留
            console.log('检测到复杂内容粘贴，已过滤')
          }
        })
        Delta.ops = ops
      }
      return Delta
    },
    handleSave() {
      this.saveLoading = true
      this.popperData.imgs = this.fileList.map((item) => item.url)
      this.biTable.headerPopper.savePopperData(this.popperData).then(() => {
        this.saveLoading = false
        this.dialogVisible = false
      })
    },
    async httpRequest(params) {
      const uploadConfig = {
        dir: '/'
      }
      try {
        const progressCallback = (p) => {
          this.uploadLoading = true
          if (p * 100 === 100) {
            this.uploadLoading = false
            Message({
              message: '上传成功',
              type: 'success'
            })
          }
        }
        Message({
          message: '上传中',
          type: 'info'
        })
        const result = await ossUpload(params.file, uploadConfig, progressCallback)
        if (result.status_code === 1) {
          this.lastFile.url = result.data
        }

        // this.formData.download_url = result.data
      } catch (error) {
        // this.$message.error(error.msg || error)
      }
    },
    beforeUpload(file) {
      this.$set(this, 'lastFileData', file)
      this.lastFile.uid = ''
      this.lastFile.url = ''
      if (file && file.uid) {
        this.lastFileData.percentage = 0
        this.lastFileData.status = 'uploading'

        this.lastFile.uid = file.uid
      }
      return true
    },
    beforeRemove(file, fileList) {
      this.fileList = fileList.filter((item) => item.uid !== file.uid)
      return true
    },
    success(response, file, fileList) {
      const successFile = fileList.find((item) => item.uid === this.lastFile.uid)
      if (successFile) {
        successFile.url = this.lastFile.url
      }
      this.fileList = fileList
    },
    handleClosed() {
      this.fileList = []
      this.saveLoading = false
    },
    delePopper() {
      this.biTable.headerPopper.delPopperItem(this.popperData.id).then((res) => {
        if (res.status_code === 1) {
          Message({
            message: '清除成功',
            type: 'success'
          })
        }
        this.biTable.headerPopper.getPopperList()
        this.dialogVisible = false
        this.uploadLoading = false
      })
    }
  }
}
</script>

<style>
</style>