<template>
  <div>
    <el-upload
      ref="upload"
      class="upload"
      multiple
      :file-list="fileList"
      :action="uploadFileUrl"
      :headers="headers"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="handleUploadSuccess"
    >
      <!-- :auto-upload="false" -->
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { listFileBusinessId, delFile } from "@/api/system/file";
export default {
  props: {
  },
  data() {
    return {
      fileList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  mounted() {
    if (this.id) {
      this.getListFileBusinessId(this.id);
    }
  },
  methods: {
    // 根据附件业务ID()获取附件详情信息列表
    getListFileBusinessId(id) {
      if (id) {
        listFileBusinessId(id).then((response) => {
          if (response.data.length > 0) {
            let list = response.data;
            for (let i in list) {
              list[i].name = list[i].newUploadName;
            }
            this.fileList = list;
          }
        });
      }
    },
    handleChange(file, fileList) {
      //   console.log("----", file, fileList);
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      if (file.id) {
        const id = file.id;
        delFile(id).then((response) => {
          // 给父组件传值
          this.$emit("getFileList", this.fileList);
        });
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleUploadSuccess(res, file, fileList) {
      let that = this;
      if (fileList.every((item) => item.status == "success")) {
        fileList.map((item) => {
          if (item.response) {
            item.response.file.name = item.response.file.newUploadName;
            this.fileList.push(item.response.file);
            that.$emit("getFileList", this.fileList);
          }
        });
      }
    },
  },
};
</script>