<!-- 业务组件 上传附件 -->
<template>
  <div>
    <van-field
      :name="item.label"
      :required="item.props[0].required"
      :label="item.label"
      :rules="rules(item.props[0], item.label)"
    >
      <template #input>
        <van-uploader
          v-model="fileList"
          :after-read="afterRead"
          :accept="item.accept"
          :max-count="item.props[0].limit"
          :max-size="maxSize"
          :image-fit="imageFit"
          :before-delete="deleteImg"
          @oversize="onOversize"
        />
      </template>
    </van-field>
  </div>
</template>
<script>
import { goUpload } from './../../api'
import { Notify } from 'vant'
import { downLoadImg } from './../downLoadImg'
import { downloadUrl } from './../../api'
export default {
  name: 'UploadAttachments',
  props: {
    item: {
      default: () => { },
      type: Object
    },
    // 校验规则
    rules: {
      type: Function,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      fileList: [],
      // 默认10M
      maxSize: '10 * 1024 * 1024',
      // 预览图裁剪模式
      imageFit: 'contain',
      // 删除失败文件的标志
      fileErrFlag: 0
    }
  },
  watch: {
    'item.props': {
      handler () {
        this.item.componentFeedback[0].value = this.item.props[0].value.map(val => {
          return {
            fileName: val.fileName,
            filePath: val.filePath
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    this.init()
  },
  methods: {
    // 初始化
    init () {
      if (this.item.props[0].value.length > 0) {
        this.item.props[0].value.map(item => {
          this.imgSrc(item)
        })
      }
      // 兼容旧数据
      this.item.accept = this.item.accept || '.jpg,.jpeg,.png,.gif,.bmp,.xls,.xlsx,.doc,.docx,.pdf,.ppt,.pptx,.zip,.rar,.txt,.mp3,.mp4,.mkv'
      // 数量上限1-99
      this.item.props[0].limit = this.item.props[0].limit || 99
    },
    imgSrc (path) {
      downLoadImg(`${downloadUrl}?path=${path.filePath}`).then((res) => {
        this.fileList.push({
          url: res,
          isImage: true,
          fileName: path.fileName,
          file: {
            name: path.fileName
          }
        })
      })
    },
    // 自行将文件上传至服务器
    afterRead (file) {
      file.status = 'uploading'
      file.message = '上传中...'
      file.status = 'uploading'
      file.message = '上传中...'
      const formData = new FormData()
      formData.append('file', file.file, file.file.name)
      goUpload({
        data: formData
      }).then(res => {
        if (res.code === 200) {
          file.status = 'done'
          file.message = ''
          file.fileName = res.data.fileName
          file.filePath = res.data.filePath
          this.item.props[0].value.push({
            fileName: file.fileName,
            filePath: file.filePath
          })
        }
      }).catch(() => {
        file.fileName = ''
        file.filePath = ''
        this.fileErrFlag++
        file.fileErrFlag = this.fileErrFlag
        file.status = 'failed'
        file.message = '上传失败'
      })
    },
    /**
   * @description 文件超出大小提示
   * @param {Object} file 文件对象
   */
    onOversize (file) {
      Notify({ type: 'warning', message: '文件不能超过10M' })
    },
    // 删除功能
    deleteImg (file) {
      if (file.filePath !== '') {
        Notify({ type: 'success', message: '删除成功' })
        // 不使用名字判断是因为名字可能会重复
        this.fileList = this.fileList.filter(item => {
          return item.filePath !== file.filePath
        })
        this.item.props[0].value = this.item.props[0].value.filter(val => {
          return val.filePath !== file.filePath
        })
      } else {
        // 上传失败文件的删除逻辑
        this.fileList = this.fileList.filter(item => {
          return item.fileErrFlag !== file.fileErrFlag
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.preview-cover {
  position: absolute;
  box-sizing: border-box;
  bottom: 0;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
</style>
