<template>
  <span>
    <!-- <a href="javascript:;" class="file" v-if="fileType === 'directoryImage'">
      上传文件
      <input
        type="file"
        name="file"
        ref="file"
        @change="upload($event, 'directoryImage')"
        webkitdirectory
      />
    </a> -->
    <el-button
      type="primary"
      @click="upload"
      v-if="fileType === 'directoryImage'"
    >
      确定
    </el-button>
    <a href="javascript:;" class="file" v-if="fileType === 'excel'">
      批量导入
      <input
        type="file"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        ID="fileSelect"
        runat="server"
        @change="upload($event, 'excel')"
      />
    </a>
  </span>
</template>

<script>
import * as XLSX from "xlsx";
export default {
  name: "BatchUpload",
  components: {},
  props: {
    //图片允许的文件格式
    formatStyles: {
      type: Array,
      default() {
        return ["png", "jpg", "jpeg"];
      },
    },
    //要求文件命名至少包含的项数，并指定返回的key值;----> 命名规则 A-B-C-D-E.XXX   则返回，A=name  B=idNumber  C=cardIdEx
    needFileNameList: {
      type: Array,
      // default() {
      //   return ["name", "idNumber", "cardIdEx"];
      // },
    },
    //调用种类 directoryImage->文件夹图片  excel->excel文件
    fileType: {
      type: String,
      default: "directoryImage",
    },
    file: {
      type: FileList,
    },
  },
  data() {
    return {};
  },
  watch: {},
  methods: {
    upload(e, type) {
      let files = e.target.files || this.file;
      //若出现files赋值未知错误值或照片长度不对则return
      if (!files || files.length < 1) {
        return this.$message.error("请上传");
      }
      // 如果是批量上传图片走这里
      if (this.file) {
        if (!this.needFileNameList) {
          return this.$message.error("请选择命名参数");
        }
        if (this.needFileNameList.indexOf("name") === -1) {
          return this.$message.error("姓名为必填项");
        }
        if (
          this.needFileNameList.indexOf("idNumber") > -1 ||
          this.needFileNameList.indexOf("cardIdEx") > -1 ||
          this.needFileNameList.indexOf("phone") > -1
        ) {
          //找出所有图片
          this.getPhotoList(Array.from(files));
        } else {
          return this.$message.error("手机号、身份证、卡号任选其一必选");
        }
      }
      //判断文件类型,调用不同的处理办法
      switch (type) {
        case "directoryImage":
          //找出所有图片
          this.getPhotoList(Array.from(files));
          break;
        case "excel":
          //处理excel
          this.getJsonList(Array.from(files));
          break;
        default:
          break;
      }
    },
    getPhotoList(files) {
      let photoList = {
        correct: [],
        incorrect: [],
      };
      files.forEach((item) => {
        let arr = item.name.split(".");
        let formatStyle = arr[arr.length - 1];
        //若文件类型不在指定类型中，则不处理
        if (!this.formatStyles.includes(formatStyle)) {
          photoList.incorrect.push({
            reason:
              "文件格式要求为" +
              this.formatStyles.join(",") +
              ",上传的类型为" +
              formatStyle,
            file: item,
          });
          return;
        } else if (item.size > 1024 * 1024 * 2) {
          //要求文件大小不大于指定值 单位：字节
          photoList.incorrect.push({
            reason:
              "单张图片大小要求为2M内,上传的图片大小为" +
              item.size / 1024 / 1024 +
              "M",
            file: item,
          });
          return;
        }

        let obj = this.matchNeedFileNameList(item, arr[0]);
        photoList[obj.status ? "correct" : "incorrect"].push(obj.file);
      });
      this.doUpload(photoList);
    },
    matchNeedFileNameList(file, fileName) {
      let arrContent = fileName.split("-");
      let obj = {
        status: true,
        file: {},
      };
      if (
        arrContent.length < this.needFileNameList.length ||
        arrContent.some((name) => {
          return !name;
        })
      ) {
        return {
          status: false,
          file: {
            reason:
              "文件没有按指定要求命名,需要" + this.needFileNameList.join(","),
            file: file,
          },
        };
      }
      this.needFileNameList.forEach((item, index) => {
        obj.file[item] = arrContent[index].trim() || "";
      });
      obj.file["avatar"] = file;
      return obj;
    },
    doUpload(photoList) {
      this.$emit("getFileList", photoList);
    },
    // 处理excel文件的内容
    getJsonList(files) {
      //只处理第一个文件;
      let file = files[0];
      let reader = new FileReader();
      let photoList = {
        correct: [],
        incorrect: [],
      };
      reader.readAsBinaryString(file);
      reader.onload = (e) => {
        // 获取传递的表格
        let binaryString = e.target.result;
        // 以二进制流方式读取到整份的excel 表格对象
        let workbook = XLSX.read(binaryString, {
          type: "binary",
          sheetRows: 0,
          codepage: 936,
        });
        let data = [];
        // 遍历每张表读取
        for (let sheet in workbook.Sheets) {
          data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
        }
        photoList["correct"] = data;
        this.doUpload(photoList);
      };
    },
  },
  mounted() {},
};
</script>

<style scoped>
/*批量导入按钮*/
.file {
  margin: 10px 0 0 10px;
  position: relative;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 10px 20px;
  box-sizing: border-box;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
}
.file input {
  position: absolute;
  font-size: 14px;
  width: 106px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}
.el-button {
  margin-left: 10px;
}
</style>
