<template>
  <div>
    <div class="flex-box">
      <van-uploader
          multiple
          :accept="fileType.toString()"
          :max-count="limit"
          :max-size="fileSize * 1024 * 1024"
          @oversize="onOversize"
          :before-read="beforeRead"
          :after-read="afterRead">
        <van-button icon="plus" type="primary" class="button">上传文件</van-button>
      </van-uploader>
      <slot></slot>
    </div>
    <div v-if="isShowTip" class="upload-tip">
      <div v-if="fileType">1、支持{{ fileType.join('、') }}文件</div>
      <div v-if="limit">2、最多支持上传{{limit}}个文件</div>
    </div>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list" name="el-fade-in-linear" tag="ul">
      <li v-for="(file, index) in fileList" :key="file.uid" class="upload-list-item">
        <div class="text-primary" @click="handleDownload(file)">
          {{ getFileName(file.name) }}
        </div>
        <van-icon name="delete-o" class="delete-icon" @click="handleDelete(index)"/>
      </li>
    </transition-group>
  </div>
</template>

<script lang="ts" setup name="FileUpload">
import {showFailToast, showToast} from "vant";
import {ref} from "vue";
import { v1 as uuidv1 } from 'uuid';
import {download2, globalHeaders} from "@/utils/request";
import axios from "axios";

const props = defineProps({
  modelValue: {
    type: [String, Object, Array],
    default: () => []
  },
  buttonText: {
    type: String,
    default: '选取文件'
  },
  // 数量限制
  limit: {
    type: Number,
    default: 5
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 100
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf']
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(['update:modelValue']);
const number = ref(0);
const uploadList = ref<any[]>([]);

const baseUrl = import.meta.env.VITE_BASE_API;
const downLoadApi = import.meta.env.VITE_BASE_DOWNLOAD_API;
const uploadFileUrl = ref(baseUrl + '/resource/oss/upload'); // 上传文件服务器地址
const headers = ref(globalHeaders());

const fileList = ref<any[]>([]);

const onOversize = () => {
  showToast('文件大小不能超过' + props.fileSize + 'MB');
};
// 上传前置处理
const beforeRead = (file: any) => {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      showToast(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      showToast(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  number.value++;
  return true;
};

// 上传
const afterRead = async (file: any) => {
  let url = baseUrl + '/file/upload/uploadfile'; //上传文件接口
  try {
    // 如果文件大于等于5MB，分片上传
    const res = await uploadByPieces(url, file);
    // 分片上传后操作
    if (res.code === 200) {
      uploadList.value.push({
        name: res.originalName,
        url: res.filename
      });
      uploadedSuccessfully();
    } else {
      number.value--;
      showFailToast(res.msg)
      // fileUploadRef.value?.handleRemove(file);
      uploadedSuccessfully();
    }
  } catch (e) {
    return e;
  }
};
//分片上传
const uploadByPieces = async (url, { file }) => {
  // 上传过程中用到的变量
  const chunkSize = 5 * 1024 * 1024; // 5MB一片
  const chunkCount = Math.ceil(file.size / chunkSize); // 总片数
  // 获取当前chunk数据
  const identifier = uuidv1();
  const getChunkInfo = (file, index) => {
    let start = index * chunkSize;
    let end = Math.min(file.size, start + chunkSize);
    let chunknumber = file.slice(start, end);
    const fileName = file.name;
    return { chunknumber, fileName };
  };
  // 分片上传接口
  const uploadChunk = (data, params) => {
    return new Promise((resolve, reject) => {
      axios({
        url,
        method: 'post',
        data,
        params,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
          .then((res) => {
            return resolve(res.data);
          })
          .catch((err) => {
            return reject(err);
          });
    });
  };
  // 针对单个文件进行chunk上传
  const readChunk = (index) => {
    const { chunknumber } = getChunkInfo(file, index);
    let fetchForm = new FormData();
    fetchForm.append('file', chunknumber);
    return uploadChunk(fetchForm, {
      chunknumber: index,
      identifier: identifier
    });
  };
  // 针对每个文件进行chunk处理
  const promiseList = [];
  try {
    for (let index = 0; index < chunkCount; ++index) {
      promiseList.push(readChunk(index));
    }
    await Promise.all(promiseList);
    // 文件分片上传完成后，调用合并接口
    const res = await mergeChunks(identifier, file.name);
    res.originalName = file.name;
    return res;
  } catch (e) {
    return e;
  }
};
const mergeChunks = async (identifier: string, filename: string) => {
  try {
    const response = await axios.post(baseUrl + '/file/upload/mergefile', null, {
      params: {
        identifier: identifier,
        filename: filename,
        chunkstar: 0 // 假设所有分片的开始序号为0
      }
    });

    return response.data;
  } catch (error) {
    throw new Error('合并请求失败');
  }
};
// 上传结束处理
const uploadedSuccessfully = () => {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit('update:modelValue', fileList.value);
  }
};
// 删除文件
const handleDelete = (index: number) => {
  fileList.value.splice(index, 1);
  emit('update:modelValue', fileList.value);
};
// 获取文件名称
const getFileName = (name: string) => {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf('/') > -1) {
    return name.slice(name.lastIndexOf('/') + 1);
  } else {
    return name;
  }
};

// 下载方法
const handleDownload = (file: any) => {
  download2(baseUrl + downLoadApi + file.url, file.name);
};
</script>

<style lang="scss" scoped>
.button {
  padding: 0 10px;
  height: 26px;
  background: #2C81FF;
  border-radius: 2px;
  margin-bottom: 6px;
}
.upload-tip {
  font-size: 14px;
}
.upload-file-list {
  .upload-list-item {
    display: flex;
    align-items: center;
    .text-primary {
      color: #2c81ff;
      font-size: 14px;
    }
    .delete-icon {
      color: #969799;
      font-size: 20px;
      margin-left: 5px;
    }
  }
}
.flex-box {
  display: flex;
  align-items: center;
}
</style>
