<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: [],
      // 提交用原始数据（相对路径）；组件内维护，避免并行上传时 prop 回传延迟导致丢图
      innerList: [],
      imageStyles: {
        width: 100,
        height: 100,
        border: {
          radius: '5px'
        }
      }
    }
  },
  props: {
    maxSize: {
      type: Number,
      default: 1
    },
    value: {
      type: Array,
      default() {
        return []
      }
    }
  },
  watch: {
    value: {
      deep: true,
      handler: function (newV) {
        // 数据为空的三种情况
        if (newV === null || newV === '' || newV === undefined) {
          this.fileList = []
          this.innerList = []
          return
        }
        // 同步内部数据源，再转展示数据；新数组引用才能触发 uni-file-picker 刷新
        this.innerList = newV
        this.fileList = this.toDisplayList(newV)
      }
    }
  },
  methods: {
    // 生成展示数据：相对路径转完整地址；克隆处理，不修改提交用的原始数据，避免重复拼接前缀
    toDisplayList(list) {
      return (list || []).map(item => {
        const data = Object.assign({}, item)
        if (data.url && data.url.substr(0, 4) !== 'http') {
          data.url = this.$BaseTool.UserUtil.getFileUrl(data.url)
        }
        return data
      })
    },
    deletefile(e) {
      // e.tempFilePath 为展示用的完整地址，按原始 url 后缀匹配，同步删除提交数据中的对应项
      const newValue = (this.innerList || []).filter(item => {
        return !(item.url && e.tempFilePath && e.tempFilePath.endsWith(item.url))
      })
      this.innerList = newValue
      this.$emit('input', newValue)
      this.$emit('change', newValue)
    },
    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 {
            // 回传原始文件实体（相对路径），保证提交数据不变；
            // 新数组引用触发父组件更新 -> watch 转为展示数据 -> 列表刷新展示
            const newValue = (that.innerList || []).concat([data.data])
            that.innerList = newValue
            that.$emit('input', newValue)
            that.$emit('change', newValue)
          }
        },
        fail: () => {
          uni.showToast({ icon: 'none', title: '上传失败!' })
        }
      })
    }
  }
}
</script>

<style></style>