<template>
  <view>
    <uni-file-picker @select="select" mode="grid" @delete="deletefile" v-model="fileList" :limit="maxSize" file-mediatype="image" :image-styles="imageStyles"></uni-file-picker>
  </view>
</template>

<script>
export default {
  name: 'MUpload',
  data() {
    return {
      fileList: [],
      imageStyles: {
        width: 100,
        height: 100,
        border: {
          radius: '5px'
        }
      }
    }
  },
  props: {
    maxSize: {
      type: Number,
      default: 1
    },
    value: {
      type: Array,
      default() {
        return []
      }
    }
  },
  watch: {
    value: {
      deep: true,
      // immediate: true,
      handler: function (newV) {
        // 数据为空的三种情况
        if (newV === null || newV === '' || newV === undefined) {
          this.fileList = []
          this.isWatch = true
          return
        }
        // if (this.isWatch) {
        //   this.isWatch = false
        //   if (newV.length > 0) {

        // #ifndef H5
        this.fileList = this.$BaseTool.UserUtil.transImg(newV)
        // #endif
        // #ifdef H5
        this.fileList = newV
        // #endif
        //   } else {
        //     this.isWatch = true
        //   }
        // }
      }
    }
  },
  methods: {
    deletefile(e) {
      this.fileList = this.fileList.filter(item => item.path !== e.tempFilePath)
      this.$emit('input', this.fileList)
      this.$emit('change', this.fileList)
    },
    select(e) {
      // 根据所选图片的个数，多次调用上传函数
      console.log(e)
      let promises = []
      for (let i = 0; i < e.tempFilePaths.length; i++) {
        const promise = this.uploadFiles(e.tempFilePaths, i)
        promises.push(promise)
      }
      Promise.all(promises).then(() => {})
    },
    // 上传函数
    async uploadFiles(tempFilePaths, i) {
      let that = this
      await uni.uploadFile({
        url: that.$BaseTool.UserUtil.getUploadUrl(),
        filePath: tempFilePaths[i],
        name: 'file',
        header: {
          Authorization: that.$BaseTool.UserUtil.getToken(tempFilePaths[0])
        },
        success: res => {
          let data = JSON.parse(res.data) //返回的是字符串，需要转成对象格式
          const reg = new RegExp('[；，。！？;,]')
          if (reg.test(res.data.fileName)) {
            uni.showToast({ icon: 'none', title: '文件名包含非法字符!' })
          } else {
            that.fileList.push(data.data)
            this.$emit('input', this.fileList)
            that.$emit('change', that.fileList)
          }
        },
        fail: () => {
          uni.showToast({ icon: 'none', title: '上传失败!' })
        }
      })
    }
  }
}
</script>

<style>
</style>