<template>
  <div class="upload-file">
    <div v-if="!disabled" class="upload-flex">
      <el-upload
        ref="fileUploadRef"
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :show-file-list="false"
        :headers="headers"
        :http-request="uploadFile"
        class="upload-file-uploader"
      >
        <!-- 上传按钮 -->
        <el-button v-if="!$slots.default" type="primary">
          <div class="button-flex">
            <i class="upload-icon" />
            {{ buttonText }}
          </div>
        </el-button>
        <slot></slot>
      </el-upload>
      <!-- 上传提示 -->
      <div v-if="showTip" class="el-upload__tip">
        <div>1.支持{{ fileType.join('、') }}文件</div>
        <div>2.最多支持上传{{ limit }}个文件</div>
      </div>
    </div>
    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      :style="{ margin: disabled ? '0' : '10px 0 0' }"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li v-for="(file, index) in fileList" :key="file.uid" class="el-upload-list__item ele-upload-list__item-content">
        <el-text class="common-btn-text-primary" @click="handleDownload(file)">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-text>
        <i v-if="!disabled" class="delete-icon" @click="handleDelete(index)" />
      </li>
    </transition-group>
  </div>
</template>

<script setup name="FileUpload">
import { propTypes } from '@/utils/propTypes';
import { getToken } from '@/utils/auth';
import { download2, globalHeaders } from '@/utils/request';
import { v1 as uuidv1 } from 'uuid';
import axios from 'axios';

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

const { proxy } = getCurrentInstance();
const emit = defineEmits(['update:modelValue', 'change']);
const number = ref(0);
const uploadList = ref([]);

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

const fileList = ref([]);
const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));

const fileUploadRef = ref();

watch(
  () => props.modelValue,
  async (val) => {
    if (val) {
      let temp = 1;
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(',');
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        if (typeof item === 'string') {
          item = { name: item, url: item };
        }
        item.uid = item.uid || new Date().getTime() + temp++;
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

// 上传前校检格式和大小
const handleBeforeUpload = (file) => {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy?.$modal.loading('正在上传文件，请稍候...');
  number.value++;
  return true;
};

// 文件个数超出
const handleExceed = () => {
  proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
};

// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError('上传文件失败');
};

const uploadFile = async ({ data, file }) => {
  // data是上传时附带的额外参数，file是文件
  let url = baseUrl + '/file/upload/uploadfile'; //上传文件接口
  try {
    // 如果文件大于等于5MB，分片上传
    data.file = file;
    const res = await uploadByPieces(url, data);
    // 分片上传后操作
    return res;
  } catch (e) {
    return e;
  }
};

//分片上传
const uploadByPieces = async (url, { fileName, 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',
          'Authorization': 'Bearer ' + getToken()
        }
      })
        .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, filename) => {
  try {
    const response = await axios.post(baseUrl + '/file/upload/mergefile', null, {
      params: {
        identifier: identifier,
        filename: filename,
        chunkstar: 0 // 假设所有分片的开始序号为0
      },
      headers: {
        'Authorization': 'Bearer ' + getToken()
      }
    });

    return response.data;
  } catch (error) {
    throw new Error('合并请求失败');
  }
};
// 上传成功回调
const handleUploadSuccess = (res, file) => {
  if (res.code === 200) {
    uploadList.value.push({
      name: res.originalName,
      url: res.filename
    });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgError(res.msg);
    fileUploadRef.value?.handleRemove(file);
    uploadedSuccessfully();
  }
};

// 删除文件
const handleDelete = (index) => {
  fileList.value.splice(index, 1);
  emit('update:modelValue', fileList.value);
  emit('change', fileList.value);
};

// 上传结束处理
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);
    emit('change', fileList.value);
    proxy?.$modal.closeLoading();
  }
};

// 获取文件名称
const getFileName = (name) => {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf('/') > -1) {
    return name.slice(name.lastIndexOf('/') + 1);
  } else {
    return name;
  }
};

// 对象转成指定字符串分隔
const listToString = (list, separator) => {
  let strs = '';
  separator = separator || ',';
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : '';
};

// 下载方法
const handleDownload = (file) => {
  download2(baseUrl + downLoadApi + file.url, file.name ? file.name : '导入模板');
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  line-height: 22px;
  margin-bottom: 10px;
  position: relative;
  padding: 3px 5px;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
.upload-flex {
  display: flex;
  align-items: flex-start;
  .el-upload__tip {
    font-size: 12px;
    line-height: 22px;
    margin-left: 28.5px;
    margin-top: 0;
  }
}
.button-flex {
  display: flex;
  align-items: center;
  .upload-icon {
    width: 18px;
    height: 14px;
    background: url('@/assets/images/upload.png') no-repeat;
    background-size: 100% 100%;
    display: inline-block;
    margin-right: 5px;
  }
}
.el-upload-list__item:hover {
  background-color: #fff !important;
}
.delete-icon {
  width: 15px;
  height: 16px;
  background: url('@/assets/images/delete.png') no-repeat;
  background-size: 100% 100%;
  cursor: pointer;
  margin-left: 7.5px;
  display: inline-block;
}
</style>
