<template>
  <div class="images-list">
    <el-upload
      :action="uploadUrl"
      :before-upload="handleBeforeUpload"
      :on-success="handleSuccess"
      :on-error="handleUploadError"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :file-list="fileList"
      :multiple="fileLimit > 1"
      :headers="headers"
      :limit="fileLimit"
      :list-type="listType"
      name="files"
      :accept="fileAccept"
      ref="AutoUploader"
      :http-request="httpRequest"
    >
      <i v-if="listType === 'picture-card'" class="el-icon-plus"></i>
      <el-button v-else size="small" type="primary">点击上传</el-button>
      <div v-if="showTip" slot="tip" class="el-upload__tip">
        只能上传{{ fileTypeName || "jpg/png" }}文件，且不超过
        {{ fileSize }}MB，最多上传{{ fileLimit }}个文件
      </div>
    </el-upload>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { upload } from "@/utils/file";
import { deleteFiles } from "@/api/file";
export default {
  name: "AutoUploader",
  props: {
    // 值
    value: [String, Object, Array],
    files: {
      type: Array,
      default: () => [],
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如["doc", "xls", "ppt", "txt", "pdf"]
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 文件列表类型 text/picture/picture-card
    listType: {
      type: String,
      default: "picture",
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    // 最大允许上传个数
    fileLimit: {
      type: Number,
      default: 99,
    },
  },
  data() {
    return {
      uploadUrl:
        process.env.NODE_ENV === "test" ||
        process.env.NODE_ENV === "development"
          ? "/api/sysFiles/upload"
          : process.env.NODE_ENV + "/sysFiles/upload", // 上传的图片服务器地址
      headers: {
        authorization: getToken(),
      },
      fileList: [],
      // tempFileList: [],
      uploadDisabled: false,
    };
  },
  watch: {
    value: {
      handler: function (val) {
        this.fileList = JSON.parse(JSON.stringify(val));
      },
      immediate: true,
      deep: true,
    },
    // files: {
    //   handler: function (val) {
    //     this.fileList = JSON.parse(JSON.stringify(val));
    //     // debugger
    //   },
    //   immediate: true,
    //   deep: true,
    // },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    fileTypeName() {
      let typeName = "";
      this.fileType.forEach((item) => {
        typeName += `${item}，`;
      });
      return typeName;
    },
    fileAccept() {
      let fileAccept = "";
      this.fileType.forEach((element) => {
        fileAccept += `.${element},`;
      });
      return fileAccept;
    },
  },
  // created() {
  //   this.fileList = JSON.parse(JSON.stringify(this.files));
  // },
  methods: {
    httpRequest(file) {
      var formData = new FormData();
      formData.append("files", file.file);
      upload(formData).then((res) => {
        if (res.code == 0) {
          this.fileList = res.data;
          this.changeFileList(res.data);
        }
      });
    },

    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      this.$emit("endLoading");
      this.$emit("startLoading");
      if (this.fileType && file) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk & file) {
          this.$message.error(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          this.$emit("endLoading");
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize && file) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`超出上传文件个数,请删除以后再上传！`);
    },
    // 文件上传成功的钩子
    handleSuccess(res, file, fileList) {
      console.log("res", res);
      console.log("fileList", fileList);
      this.$message.success("上传成功");
      this.changeFileList(fileList);
    },
    // 文件列表移除文件时的钩子
   async handleRemove(file, fileList) {
      this.changeFileList(fileList);
      const { fileId } = file;
      let res = await deleteFiles([fileId]);
      if (res.code == 0) {
        this.$message.success("删除成功！");
      }
    },

    handleChange(file, fileList) {},

    // 文件列表改变的时候，更新组件的v-model的文的数据
    changeFileList(fileList) {
      this.$emit("input", fileList);
    },
  },
};
</script>
<style lang="scss" >
.disabled .el-upload--picture-card {
  display: none !important;
}
</style>