<template>
  <el-upload :file-list="_value" ref="uploadRef"
             action="#"
             :headers="headers"
             :limit="maxSize"
             with-credentials
             :multiple="multiple"
             :data="uploadParams" :on-change="handleChange"
             :http-request="customUpload"
             :show-file-list="showFileList"
             :auto-upload="false"
             :before-upload="beforeUpload"
             :on-error="uploadError"
             :before-remove="beforeRemove"
             :on-remove="handleRemove"
  >
    <!--    :on-success="handleUploadSuccess"-->
    <el-button color="#DED0B2" :loading="loading" :disabled="disabled">上传文件</el-button>
  </el-upload>
</template>

<script setup>
import {ElLoading, ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {getToken} from '@/utils/auth'
import {nextTick} from "vue";
import axios from "axios";

const baseURL = import.meta.env.VITE_BASE_URL
const uploadFileUrl = ref(baseURL + "/workflow/process/file/upload")
const headers = reactive({
  'Content-Type': 'multipart/form-data',
  authorization: getToken()
})
const loading = ref(false)
const showTable = ref(false)
const uploadIndex = ref(0)
const uploadParams = ref({})
const props = defineProps({
  value: {
    type: Array,
    default: () => {
      return []
    }
  },
  maxSize: {
    type: Number,
    default: 999999
  },
  showFileList: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: true
  }
})
const uploadRef = ref(null); // el-upload 的 ref
const uploadPromises = ref([]); // 跟踪每个文件的上传状态
const emit = defineEmits(["input", "beforeUpload", "getFile", "delete"])
const fileList = ref([])
const _value = computed({
  get() {
    return props.value;
  },
  set(val) {
    emit("input", val);
  }
})
const beforeRemove = (file) => {
  return ElMessageBox.confirm(`确认删除名称为${file.name}的文件吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => true)
}

const uploadLoading = ref(false)
const uploadFile = ref([])
const handleRemove = (file) => {
  emit("delete", file.response.data.id)
}

// 文件选择变化时触发
const handleChange = (file, files) => {
  const deleteFileRow = JSON.parse(localStorage.getItem('deleteFileRow'));
  console.log("🚀 ~ file:deleteFileRow ", deleteFileRow, uploadFile.value)
  let deleteIndex = null
  if (deleteFileRow) {
    deleteIndex = uploadFile.value.findIndex((item) => item.name === deleteFileRow.originalFileName && item.size === deleteFileRow.size)
    console.log("🚀 ~ file:deleteIndex ", deleteIndex)

    if (deleteIndex != -1) {
      uploadFile.value.splice(deleteIndex, 1);
    }
  }


  console.log(file, files, 'files')
  uploadIndex.value++
  uploadFile.value.push(file)
  console.log("🚀 ~ file:uploadFile.value ", uploadFile.value)
  localStorage.removeItem('deleteFileRow')
};
watch(() => uploadIndex.value, (newVal) => {
  console.log('newVal', newVal)
  startUpload(uploadFile.value); // 自动触发上传
}, {
  deep: true
})
// 自定义上传逻辑
const customUpload = async (options) => {
  const formData = new FormData();
  formData.append('file', options.raw);
  try {
    const response = await axios.post(uploadFileUrl.value, formData, {
      headers: headers,
    });

    fileList.value.push(response.data.data)

    emit("getFile", response.data.data)
    return response.data; // 成功时返回响应
  } catch (error) {
    throw new Error('上传失败'); // 失败时抛出错误
  }
};

// 触发所有文件上传
const startUpload = (files) => {
  uploadLoading.value = ElLoading.service({
    fullscreen: true,
    text: '文件上传中...',
  })
  if (files.length === 0) {
    return; // 没有文件时直接返回
  }
  uploadPromises.value = []; // 重置 Promise 数组
  files.forEach((file) => {
    // 触发每个文件的上传
    const promise = new Promise((resolve, reject) => {
      customUpload(file).then(resolve)
          .catch(reject);
    });
    uploadPromises.value.push(promise);
  });

  // 使用 Promise.all 监听所有文件上传完成
  Promise.all(uploadPromises.value)
      .then(() => {
        ElNotification({
          title: '提示',
          message: '所有文件上传完成！',
          type: 'success'
        })
        files = []; // 清空文件列表
        uploadRef.value.clearFiles(); // 清空上传组件
        uploadFile.value = [] // 清空文件列表
        nextTick(() => {
          uploadLoading.value.close()
          uploadLoading.value = null
        })
      })

};

const beforeUpload = () => {
  loading.value = true
  return true
}
const handleUploadSuccess = (res) => {

  ElNotification({
    title: '提示',
    message: res.code === 1000 ? '上传成功' : '上传失败',
    type: res.code === 1000 ? 'success' : 'error'
  })
  loading.value = false
  showTable.value = true
  let data = res.data
  fileList.value.push(data)
  // emit("getFile", res.data)
}
const uploadError = () => {
  loading.value = false
  ElNotification({
    title: '提示',
    message: "上传失败，请稍后再试！",
    type: 'error'
  })
}
defineExpose({
  handleRemove
})
</script>

<style lang="scss" scoped>
a {
  font-size: 14px;
  color: #2a99ff;
}

:deep(.el-upload-list) {
  width: 400px;
}
</style>
