<template>
  <div>
    <el-upload
      action="/api-web/import/oaUploadFile"
      :on-success="handleSuccess"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUploadFile"
      :before-remove="beforeRemove"
      multiple
      :limit="element.options.length"
      :headers="element.options.headers"
      :on-exceed="handleExceed"
      :data="uploadData"
      :file-list="dataModel"
      :disabled="element.options.disabled"
      :style="{ width: element.options.width }"
    >
      <div v-if="!preview">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">{{ element.options.tip }}</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: "FileUpload",
  // eslint-disable-next-line vue/require-prop-types
  props: ["element", "preview", "dataModel"],
  data() {
    return {
      fileListTmp: [],
      uploadData: {}
    };
  },
  mounted() {
    const query = this.$route.query;
    if (query.processId) {
      this.uploadData.processId = query.processId;
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileListTmp = fileList;
      this.$emit("fileList", fileList);
    },
    handlePreview(file) {
      window.open(file.url, "_blank");
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `最多允许上传 ${this.element.options.length} 个文件。`
      );
    },
    async beforeUploadFile(file) {
      return new Promise((resolve, reject) => {
        const isLt2M = file.size / 1024 / 1024 < 20;
        if (!isLt2M) {
          this.$message.error("上传附件大小不能超过 20MB!");
          return reject(false);
        } else {
          return resolve(true);
        }
      });
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定要移除 ${file.name}？`);
    },
    handleSuccess(response, file, fileList) {
      console.log(response, file, fileList);
      if (response.code === 200) {
        this.fileListTmp.push({
          uid: file.uid,
          name: file.name,
          url: response.data.url,
          file: {
            name: file.name
          }
        });
        this.$emit("fileList", this.fileListTmp);
      } else {
        const index = fileList.findIndex(item => item.uid === file.uid);
        fileList.splice(index, 1);

        this.$message.error(response.msg);
      }
    }
  }
};
</script>

<style scoped></style>
