<template>
  <el-form-item :label="title">
    <el-upload
      class="upload-demo"
      action="/admin/sysFile/uploadVoucher"
      :headers="headers"
      :data="fileData"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-error="handleUploadErr"
      :on-success="handleAvatarSuccess"
    >
      <el-button type="primary" :loading="uploading">上传附件</el-button>
      <template #tip>
        <div class="el-upload__tip">只可上传图片，大小不可超过20M</div>
      </template>
    </el-upload>
  </el-form-item>

  <el-row v-for="item in uploadList" :key="item.fileId">
    <el-col :span="24">
      <el-form-item label="附件名">
        <div class="file_item">
          <div class="file_item_detail">
            <el-input v-model="item.fileName" readonly placeholder="文件名" />
            <filePreview :file="item" @removeFile="removeFile" />
          </div>
        </div>
      </el-form-item>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import filePreview from "./filePreview.vue";

import { computed, ref } from "vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import type { UploadProps } from "element-plus";

const store = useStore();
const props = defineProps({
  title: {
    type: String,
    default: "附件信息"
  },
  maxLength: {
    type: Number,
    default: 1
  },
  fileList: {
    // 文件列表
    type: Array,
    default() {
      return [];
    }
  }
});
const emit = defineEmits(["update:fileList"]);

const uploadList: any = computed({
  get() {
    return props.fileList;
  },
  set(val) {
    emit("update:fileList", val);
  }
});
const headers = {
  Authorization: "Bearer " + store.getters.access_token
  // "Content-Type": "multipart/form-data;charset=UTF-8"
};
const fileData = {
  bucket: "reservoir"
};

const uploading = ref(false);

// 上传前对附件进行的操作
const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  if (props.maxLength > 0 && uploadList.value.length === props.maxLength) {
    ElMessage.warning(`附件最多上传${props.maxLength}个`);
    return false;
  }
  uploading.value = true;
  const typeList = ".pdf.jpg.png.gif.jpeg.PDF.JPG.PNG.GIF.JPEG";
  const { name, type } = fileNameDispose(file.name);
  if (!typeList.includes(type)) {
    ElMessage.error("不支持此类型，请重新上传。");
    uploading.value = false;
    return false;
  }
  if (name.length > 30) {
    ElMessage.error("文件名不可超30字，请重新命名后再上传。");
    uploading.value = false;
    return false;
  }
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    ElMessage.error("文件大小不可超过 20MB。");
    uploading.value = false;
    return false;
  }
  return true;
};

// 获取上传附件的名字和类型
const fileNameDispose = (name: string) => {
  const arr = name.split(".");
  if (arr.length === 2) {
    return { name: arr[0], type: arr[1] };
  } else {
    const type = arr.splice(arr.length - 1, 1)[0];
    const name = arr.join(".");
    return { name, type };
  }
};

// 上传失败时的回调
const handleUploadErr = () => {
  uploading.value = false;
  ElMessage.error("文件上传失败，请重新上传。");
};

// 上传成功后的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (res) => {
  if (res.code === 0) {
    const data = res.data;
    const param = {
      fileType: fileNameDispose(data.fileCustomizeName).type,
      fileName: data.fileCustomizeName,
      fileId: data.fileName,
      bucket: data.bucketName
    };
    uploadList.value.push(param);
    uploading.value = false;
  }
};

// 删除附件
const removeFile = (fileId: string) => {
  uploadList.value.splice(
    uploadList.value.findIndex((item: any) => item.fileId === fileId),
    1
  );
};
</script>

<style lang="scss" scoped>
.file_item {
  width: 100%;
  &_detail {
    display: flex;
    align-items: center;
    justify-content: space-between;
    :deep(.el-input__inner) {
      flex: 1;
    }
  }
}
</style>
