<template>
  <div>
    <el-upload
      style="width: 70%"
      :http-request="customUpload"
      action="#"
      multiple
      :file-list="fileList"
      :auto-upload="true"
      :show-file-list="false"
      :on-change="handleChange"
      :on-exceed="handleExceed"
      accept="*"
      :before-upload="beforeUpload"
      :directory="true"
    >
      <el-row>
        <el-col :span="1.5">
          <el-button icon="el-icon-upload2" :disabled="disabled" size="small" type="primary">上传文件</el-button>
        </el-col>
      </el-row>
    </el-upload>

    <el-drawer
      style="z-index: 4001 !important;"
      title="上传进度"
      :modal="false"
      :visible.sync="drawer"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :wrapper-closable="false"
    >
      <!-- 显示所有文件的上传进度 -->
      <div v-for="([filename, progress], index) in Object.entries(uploadProgress)" :key="index"
           style="padding-left: 20px;padding-right: 20px"
      >
        <div
          style="display: flex;flex-direction: row;align-items: center;justify-content: flex-start;margin-bottom: 10px"
        >
          <i v-if="progress ===100 && !uploadFailed[filename]" style="color: #13ce66;font-size: 18px"
             class="el-icon-success"
          ></i>
          <i v-if="progress !==100 && !uploadFailed[filename]" style="font-size: 18px;color: rgba(110,106,106,0.3)"
             class="el-icon-upload"
          ></i>
          <i v-if="uploadFailed[filename]" style="font-size: 18px;color: red" class="el-icon-warning"></i>
          <span style="margin-left: 2%;font-size: 18px">{{ filename }}</span>
        </div>
        <el-progress :color="progress === 100 ? '#13ce66' : '#6E6A6A4C'" :percentage="progress"></el-progress>
        <span v-if="uploadFailed[filename]" style="font-size: 12px;color: red">文件上传失败</span>
        <el-divider></el-divider>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { uploadFiles } from '@/api/dataCenter/basicFile'

export default {
  props: {
    parentId: {
      type: String,
      required: true
    },
    fileUrl: {
      type: String,
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    getList: {
      type: Function
    }
  },
  data() {
    return {
      fileList: [], // 文件列表
      chunkSize: 1024 * 1024 * 20, // 每个分片的大小（2MB）
      drawer: false,
      uploadProgress: {}, // 存储每个文件的上传进度
      uploadFailed: {}, // 存储上传失败的文件
      queue: [], // 文件上传队列
      maxConcurrentUploads: 5, // 最大并发上传数
      uploadsNum: {}
    }
  },
  beforeMount() {
    this.resetComponent()
  },
  mounted() {
    this.resetComponent() // 在组件挂载完成后调用
  },
  methods: {
    handleClose(done) {
      this.$modal
        .confirm('您确认要关闭吗？关闭后，未完成上传的文件将停止上传。')
        .then(() => {
          this.queue = [] // 清空队列
          done()
        })
        .then(() => {
          this.resetComponent()
          this.getList && this.getList() // 重新加载文件列表
        })
        .catch(() => {
        })
    },
    // 重置组件状态
    resetComponent() {
      this.fileList = []
      this.uploadProgress = {}
      this.uploadFailed = {}
      this.queue = []
      this.uploadsNum = {}
    },
    // 自定义上传请求
    customUpload(uploadFile) {
      this.drawer = true
      const file = uploadFile.file
      this.$set(this.uploadProgress, file.name, 0) // 更新文件上传进度
      // 将文件添加到队列
      this.queue.push(file)
      this.startNextUpload()
    },

    // 处理文件夹上传
    handleChange(file, fileList) {
      // 监听文件夹上传，遍历文件夹中的文件
      if (file && file.webkitRelativePath) {
        const folderPath = file.webkitRelativePath.split('/')[0] // 文件夹路径
        const filesInFolder = fileList.filter(f => f.webkitRelativePath.startsWith(folderPath))
      }
    },

    // 分片上传
    uploadChunks(file) {
      if (!this.drawer) return // 检查是否需要继续上传
      this.$set(this.uploadsNum, file.name, 0)
      const totalChunks = Math.ceil(file.size / this.chunkSize)
      let currentChunk = 0
      const uploadNextChunk = () => {
        if (!this.drawer) return // 检查是否需要继续上传
        const start = currentChunk * this.chunkSize
        const end = Math.min(file.size, start + this.chunkSize)
        const chunk = file.slice(start, end)
        const formData = new FormData()
        formData.append('file', chunk)
        formData.append('filename', file.name)
        formData.append('chunk', currentChunk + 1)
        formData.append('totalChunks', totalChunks)
        formData.append('parentId', this.parentId)
        formData.append('fileUrl', this.fileUrl)

        uploadFiles(formData)
          .then(res => {
            currentChunk++
            const progress = Math.floor((currentChunk / totalChunks) * 100)
            this.$set(this.uploadsNum, file.name, progress)
            this.$set(this.uploadProgress, file.name, progress)
            if (currentChunk < totalChunks) {
              uploadNextChunk()
            } else {
              console.log(res)
              console.log(this.$parent)
              // 通过 $emit 触发父组件方法
              this.$emit('file-uploaded', res.data);
              console.log(res)
              this.startNextUpload()
              this.checkAllUploadsComplete()
            }
          })
          .catch(reason => {
            console.log(reason)
            this.$set(this.uploadFailed, file.name, true)
            this.startNextUpload()
          })
      }

      uploadNextChunk()
    },
    checkAllUploadsComplete() {
      const allComplete = Object.values(this.uploadProgress).every(progress => progress === 100)
      if (allComplete) {
        this.$message.success('所有文件上传完成！')
        this.drawer = false // 自动关闭弹窗
        this.getList && this.getList() // 重新加载列表
        this.resetComponent()
      }
    },
    // 启动队列中的下一个文件上传（控制并发）
    startNextUpload() {
      if (!this.drawer) return // 如果停止上传，则不启动新任务
      Object.keys(this.uploadsNum).forEach((fileName) => {
        if (this.uploadsNum[fileName] === 100) {
          delete this.uploadsNum[fileName]
        }
      })

      if (this.queue.length === 0 || Object.values(this.uploadsNum).length >= this.maxConcurrentUploads) {
        return
      }
      const nextFile = this.queue.shift()
      this.uploadChunks(nextFile)
    },
    beforeUpload(file) {
      const maxSize = 2 * 1024 * 1024 * 1024 // 限制文件最大为 5MB
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过 2GB')
        return false // 阻止上传
      }
      console.log(file)
      if (file.size <= 0) {
        this.$message.error('文件大小不正确')
        return false // 阻止上传
      }
      return true // 允许上传
    },
    // 处理超出文件数限制的情况
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能选择50个文件，当前选择了 ${files.length + fileList.length} 个文件`)
    }
  }
}
</script>

<style scoped>
.el-upload__tip {
  font-size: 12px;
  color: #909399;
}

/* Optional: Adjust z-index of el-dialog if needed */
.el-dialog__wrapper {
  z-index: 1000 !important; /* Set a lower z-index for dialog */
}
</style>
