const { handleUpload } = require('../api/request')

module.exports = {
  compressJs(file) {
    return new Promise(async (resolve, reject) => {
      try {
        const { errMsg, tempFilePath } = await wx.compressImage({
          src: file.filePath, // 图片路径
          quality: 80 // 压缩质量
        })

        if (errMsg === 'compressImage:ok') {
          resolve({ ...file, filePath: tempFilePath })
          return
        }
        resolve(file)
      } catch (err) {
        resolve(file)
      }
    })
  },
  async afterRead(event) {
    const { form } = this.data
    const { file } = event.detail
    const { formkey, maxsize = '2' } = event.currentTarget.dataset
    const maxSize = maxsize * 1024 * 1024
    let _file = file

    if (Object.prototype.toString.call(file) === '[object Object]') {
      _file = [file]
    }

    wx.showToast({
      title: '上传中',
      icon: 'loading',
      duration: 600 * 1000
    })

    const result = _file.map(async item => {
      // 压缩图片时传入的路径
      item.filePath = item.url
      item.formkey = formkey
      // item.url = ''

      const compressResult = item.size > maxSize ? await this.compressJs(item) : item

      return handleUpload(compressResult)
    })

    try {
      const res = await Promise.all(result)

      this.setData({
        ['form.' + formkey]: form[formkey].concat(...res)
      })
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 2000
      })
    } catch (err) {
      wx.showToast({
        title: '上传出错',
        icon: 'none',
        duration: 2000
      })
    }
  },
  delete(event) {
    const { formkey } = event.currentTarget.dataset
    const { index } = event.detail

    this.data.form[formkey].splice(index, 1)
    this.setData({
      ['form.' + formkey]: this.data.form[formkey]
    })
  }
}
