<template>
  <div>
    <div v-if="mode === 'DESIGN'">
      <a-upload :file-list="[]" :disabled="true">
        <a-button size="small" class="button-font">选择文件</a-button>
      </a-upload>
      <p class="font">{{ placeholder }} {{ sizeTip }}</p>
    </div>
    <div v-else>
      <a-upload
        :action="fileUploadUrl"
        :headers="headers"
        :multiple="true"
        :file-list="[]"
        :data="{}"
        :before-upload="beforeUpload"
        @change="handleChange"
      >
        <a-button size="small" class="button-font">选择文件</a-button>
      </a-upload>
      <p class="font">{{ placeholder }} {{ sizeTip }}</p>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name: 'FileUpload',
  props: {
    mode: {
      type: String,
      default: 'DESIGN'
    },
    placeholder: {
      type: String,
      default: '请选择附件'
    },
    readerMode: {
      type: Boolean,
      default: false
    },
    value: {
      type: Array,
      default: () => []
    },
    onlyRead: {
      type: Boolean,
      default: false
    },
    maxSize: {
      type: Number,
      default: 50
    },
    maxNumber: {
      type: Number,
      default: 3
    },
    fileTypes: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      fileUploadUrl: 'sys/upload/uploadMinioNew'
    }
  },
  computed: {
    ...mapState({
      userAuth: state => this.$store.state
    }),
    headers() {
      return {
        token: this.userAuth.token,
        tanentId: this.userAuth.tenantid
      };
    },
    sizeTip() {
      if (this.fileTypes.length > 0) {
        return `只允许上传[${this.fileTypes.join('、')}]格式的文件，且单个附件不超过${this.maxSize}MB`;
      }
      return ` | 单个附件不超过${this.maxSize}MB`;
    }
  },
  methods: {
    beforeUpload(file) {
      const isAllowType =
        this.fileTypes.length === 0 ||
        this.fileTypes.includes(file.name.split('.').pop().toLowerCase());

      const isLtSize = file.size / 1024 / 1024 < this.maxSize;

      if (!isAllowType) {
        this.$message.error('上传文件类型不允许');
        return false;
      }
      if (!isLtSize) {
        this.$message.error(`文件大小不能超过 ${this.maxSize}MB`);
        return false;
      }

      return true;
    },
    handleChange(info) {
      const res = info.file.response;
      if (res && res.data) {
        const newValue = [...this.value, res.data.id];
        this.$emit('input', newValue);
      }
    }
  }
};
</script>

<style scoped>
.button-font {
  padding: 0 26px;
  font-size: 12px;
  color: #606266;
}
.font {
  font-size: 12px;
  color: #303133;
  margin-top: 7px;
}
</style>
