<template>
  <div>
    <template v-if="type === 'file'">
      <a-upload
        :multiple="multiple"
        :file-list="value"
        :accept="accept"
        :customRequest="uploadFile"
        :remove="handlerRemove"
      >
        <a-button> <a-icon type="upload" /> 上传附件 </a-button>
      </a-upload>
    </template>
    <template v-if="type === 'img'">
      <a-upload
        list-type="picture-card"
        :multiple="multiple"
        :file-list="value"
        :accept="accept"
        :customRequest="uploadFile"
        :remove="handlerRemove"
        @preview="handlePreview"
      >
        <div v-if="max>value.length">
          <a-icon type="plus" />
          <div class="ant-upload-text">
            上传图片
          </div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </template>
  </div>
</template>

<script>
import _ from 'lodash'
import { reqUploadFile } from '@/api/sys/upload'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  name: 'DbUpload',
  props: {
    multiple: {
      type: Boolean,
      default: true
    },
    type: {
      type: String,
      default: 'img' // img: 图片上传, file: 文件上传
    },
    // 最大上传数量
    max: {
      type: [Number, String],
      default: 2 // 默认不做限制
    },
    // [{name: '必传', uid: '必传', url: '必传'}]
    value: {
      type: Array,
      default: () => []
    },
    accept: {
      type: String,
      default: 'image/*' // 默认只能上传图片,如果需要上传其他请改为*或者自己需要的格式
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      previewVisible: false,
      previewImage: ''
    }
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    // 重写上传文件
    uploadFile(data) {
      const { max } = this
      const formData = new FormData()
      formData.append('file', data.file)
      reqUploadFile(formData).then(res => {
        if (res.code === 200) {
          const file = {
            uid: res.uid,
            name: res.name, // 文件名
            url: res.url
          }
          const list = [...this.value]
          list.push(file)
          if (list.length > max) {
            this.$message.warning(`最多只能上传${max}个附件`)
            return
          }
          this.$emit('change', list)
        }
      })
    },
    // 点击删除
    handlerRemove(file) {
      const index = _.findIndex(this.value, ['uid', file.uid])
      const newFileList = this.value.slice()
      newFileList.splice(index, 1)
      this.$emit('change', newFileList)
    }
  }
}
</script>

<style lang="less" scope>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
