<template>
  <div>
    <div v-if="read">
      <a class="av" target="_blank" :href="baseUrl + item.url" v-for="(item, index) in value" :key="index">{{ item.name }}</a>
    </div>
    <el-upload
      v-else
      multiple
      :show-file-list="true"
      :file-list="fileList"
      :limit="5"
      :headers="upload.headers"
      :action="upload.url"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :on-progress="handleFileUploadProgress"
      :on-remove="handleDelete"
    >
      <el-button icon="el-icon-upload" :loading="upload.isUploading">选取文件</el-button>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
export default {
  props: {
    read: {
      type: Boolean,
      default: false
    },
    value: {
      type: Array
    }
  },
  data() {
    return {
      fileList: [],
      frist: true,
      upload: {
        headers: { Authorization: 'Bearer ' + getToken() },
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        isUploading: false
      }
    };
  },
  watch: {
    value(val) {
      if (this.frist) {
        this.frist = false;
        this.fileList = JSON.parse(JSON.stringify(val));
      }
    }
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      this.upload.isUploading = true;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError('上传文件数量不能超过5个!');
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError('上传图片失败，请重试');
      this.upload.isUploading = false;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.upload.isUploading = false;
      if (res.code === 200) {
        this.value.push({ name: file.name, url: res.fileName });
        this.$emit('input', this.value);
        this.$modal.msgSuccess('上传成功');
      } else {
        this.$refs.fileUpload.handleRemove(file);
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 删除文件
    handleDelete(file, fileList) {
      this.$emit('input', fileList);
    }
  }
};
</script>
<style lang="scss" scoped>
.av {
  color: #1890ff;
  display: block;
  line-height: 25px;
}
</style>
