<script setup lang="ts">
const dialogVisible = ref(false)
const openDialog = () => {
  dialogVisible.value = true
}

const fileType = ref('Certificate of Origin')
defineExpose({
  openDialog
})

const fileTypeList = ['Certificate of Origin', 'House Bill of Lading', 'E-Packing List']

const uploadFileList = ref()

const changeFileList = (file: any, fileList: any) => {
  // 给当前文件添加fileType属性
  file.raw.fileType = fileType.value
  uploadFileList.value = fileList
}

function bytesToKB(bytes: number) {
  return (bytes / 1024).toFixed(0) // 将字节转换为KB，保留两位小数
}

const uploadRef = ref()
const removeFile = (file: any) => {
  uploadRef.value.handleRemove(file)
}

const handleSave = () => {
  uploadRef.value.submit()
}

// 文件上传进度处理
const handleProgress = (event: any, file: any) => {
  // 在 fileList 中找到对应的文件并更新其上传进度
  const targetFile = uploadFileList.value.find((f: any) => f.uid === file.uid)
  if (targetFile) {
    targetFile.percentage = Math.round(event.percent) // 更新百分比
  }
}

// 文件上传成功处理
const handleSuccess = (response: any, file: any) => {
  const targetFile = uploadFileList.value.find((f: any) => f.uid === file.uid)
  if (targetFile) {
    // 文件上传成功后将进度条隐藏
    setTimeout(() => {
      targetFile.percentage = undefined // 上传完成后隐藏进度条
    }, 500) // 可设置一个短暂的延时，让用户看到上传完成
  }
}

const clearData = () => {
  uploadFileList.value = []
}
const beforeAvatarUpload = (rawFile: any) => {
  if (
    ![
      'application/pdf',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ].includes(rawFile.type)
  ) {
    ElMessage.error('The file types allowed for upload are: PDF, DOCX, and XLSX.')
    return false
  } else if (rawFile.size / 1024 / 1024 > 25) {
    ElMessage.error('File size must not exceed 25MB!')
    return false
  }
  return true
}
</script>

<template>
  <el-dialog
    class="upload-files-dialog"
    @closed="clearData"
    v-model="dialogVisible"
    title="Upload Files"
    width="480"
  >
    <div class="upload-template">
      <div class="label">File Type</div>
      <el-select v-model="fileType" placeholder="string">
        <el-option v-for="item in fileTypeList" :key="item" :label="item" :value="item"></el-option>
      </el-select>
      <el-upload
        class="upload-demo"
        ref="uploadRef"
        drag
        :accept="'application/pdf,.docx,.xlsx'"
        :show-file-list="false"
        :action="'http://localhost:3000/upload'"
        multiple
        :before-upload="beforeAvatarUpload"
        @change="changeFileList"
        @remove="changeFileList"
        @progress="handleProgress"
        @success="handleSuccess"
      >
        <div class="el-upload-text">
          <span class="font_family icon-icon_upload_b"></span> <span>Upload</span>
        </div>
        <div class="el-upload-tips">
          <span class="font_family icon-icon_info_b"></span>
          <span style="font-size: 12px"
            >Supported formats: pdf, docx, xlsx ; Maximum Size: 25MB</span
          >
        </div>
      </el-upload>
    </div>
    <el-scrollbar class="uploaded-file">
      <div class="file-item" v-for="item in uploadFileList" :key="item.uid">
        <div class="header">
          <span class="label">File Type: </span>
          <span class="file-type">{{ item.raw.fileType }}</span>
          <span @click="removeFile(item)" class="font_family icon-icon_delete_b"></span>
        </div>
        <div class="file">
          <span class="font_family icon-icon_edoc_b"></span>
          <span class="file-name">{{ item.name }}</span>
          <span class="size">{{
            item.percentage !== undefined ? item.percentage + '%' : bytesToKB(item.size) + 'KB'
          }}</span>
        </div>
        <!-- 添加进度条 -->
        <el-progress
          style="width: 100%"
          v-if="item.percentage !== undefined"
          :percentage="item.percentage"
          type="line"
          color="#ed6d00"
          status="success"
          :stroke-width="4"
        />
      </div>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          style="height: 40px; padding: 8px 40px"
          class="download-btn el-button--dark"
          @click="handleSave"
          >Finish</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.upload-template {
  padding: 8px 16px;
  border-bottom: 1px solid var(--color-border);
  .label {
    font-size: 12px;
    color: var(--color-neutral-2);
  }
  .el-select {
    margin: 8px 0;
    :deep(.el-select__wrapper) {
      height: 40px;
    }
  }
  :deep(.el-upload-dragger) {
    padding-top: 19px;
    padding-bottom: 19px;
    background-color: #fef8f2;
    border: 1px dashed #f5b279;
  }
  .el-upload-text {
    margin-bottom: 8px;
    span {
      color: var(--color-theme);
    }
  }
  .el-upload-tips {
    .font_family {
      display: inline-block;
      margin-right: 2px;
      transform: translateY(2px);
    }
    span {
      color: var(--color-neutral-3);
    }
  }
}

.uploaded-file {
  max-height: 340px;
  padding: 8px 16px;
  overflow: auto;
  .file-item {
    padding: 10px 8px;
    margin-bottom: 8px;
    background-color: var(--color-header-bg);
    & > .header {
      margin-bottom: 8px;
      .label {
        color: var(--color-neutral-2);
      }
      .font_family {
        float: right;
        cursor: pointer;
      }
    }
    .file {
      padding-top: 8px;
      border-top: 1px solid var(--color-border);
      .font_family {
        position: relative;
        top: 2px; /* 根据需要调整数值 */
      }
      .file-name {
        margin-left: 4px;
        line-height: 14px;
        font-weight: 600;
      }
      .size {
        float: right;
        line-height: 22px;
        color: var(--color-neutral-2);
      }
    }
    .el-progress {
      width: 100%;
      margin-top: 8px;
      :deep(.el-progress__text) {
        display: none;
      }
    }
  }
}
</style>
<style lang="scss">
div.upload-files-dialog {
  .el-dialog__body {
    padding: 0;
  }
}
</style>
