// created by gpake
(function() {
  const app = getApp()
  var imgTempUrl = [] //上传图片后临时存放容器
  var config = {
    qiniuUploadURL: '',
    qiniuImageURLPrefix: '',
    qiniuUploadToken: '',
    qiniuUploadTokenURL: '',
    qiniuUploadTokenFunction: null
  }

  module.exports = {
    init: init,
    upload: upload,
  }

  // 在整个程序生命周期中，只需要 init 一次即可
  // 如果需要变更参数，再调用 init 即可
  function init(options) {
    config = {
      qiniuUploadURL: '',
      qiniuImageURLPrefix: '',
      qiniuUploadToken: '',
      qiniuUploadTokenURL: '',
      qiniuUploadTokenFunction: null
    };
    updateConfigWithOptions(options);
  }

  function updateConfigWithOptions(options) {
    if (options.uploadURL) {
      config.qiniuUploadURL = options.uploadURL;
    } else {
      console.error('qiniu uploader need uploadURL');
    }
    if (options.uptoken) {
      config.qiniuUploadToken = options.uptoken;
    } else if (options.uptokenURL) {
      config.qiniuUploadTokenURL = options.uptokenURL;
    } else if (options.uptokenFunc) {
      config.qiniuUploadTokenFunction = options.uptokenFunc;
    }
    if (options.domain) {
      config.qiniuImageURLPrefix = options.domain;
    }
  }

  function upload(i = 0,filePath, success, fail, options) {
    if (null == filePath) {
      console.error('qiniu uploader need filePath to upload');
      return;
    }
    if (options) {
      init(options);
    }
    if (config.qiniuUploadToken) {
      doUpload(i= 0,filePath, success, fail, options);
    } else if (config.qiniuUploadTokenURL) {
      getQiniuToken(function() {
        upload(i = 0,filePath, success, fail, options);
      });
    } else if (config.qiniuUploadTokenFunction) {
      config.qiniuUploadToken = config.qiniuUploadTokenFunction();
    } else {
      console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
      return;
    }
  }

  function doUpload(i= 0,filePath, success, fail, options) {
    var url = config.qiniuUploadURL;
    var fileName = filePath[i].split('//')[1];
    if (options && options.key) {
      fileName = options.key;
    }
    var formData = {
      'token': config.qiniuUploadToken,
      'key': fileName
    };
    wx.uploadFile({
      url: url,
      filePath: filePath[i],
      name: 'file',
      formData: formData,
      success: function(res) {
        // wx.hideLoading();
        var dataString = res.data
        var dataObject = JSON.parse(dataString);
        var imageUrl = config.qiniuImageURLPrefix + dataObject.key;
        dataObject.imageURL = imageUrl;
        imgTempUrl.push(dataObject)
        if (i + 1 < filePath.length) {
          doUpload(i + 1, filePath, success)
        } else {
          setTimeout(()=>{
            wx.hideLoading()
          },3000)
          success(imgTempUrl)
          imgTempUrl = []
        }
      },
      fail: function(error) {
        wx.hideLoading();
        fail(error);
      }
    }).onProgressUpdate(res => {
      var progress = '上传中(' + (i + 1) + '/' + filePath.length + ')'
      wx.showLoading({
        title: progress,
        mask: true
      })
    })
  }

  function getQiniuToken(callback) {
    // var that = this
    wx.request({
      url: config.qiniuUploadTokenURL,
      data: {
				token: app.globalData.token
			},
      success: function(res) {
        console.log(res)
        if (res.data.meta.code == 200) {
					var token = res.data.data.uptoken;
					config.qiniuUploadToken = token;
					if (callback) {
						callback();
					}
				} else if (res.data.meta.code == 400) {
          app.getSessionKey(function () {
            getQiniuToken(callback)
          })
				}
      },
      fail: function(error) {
        console.log(error);
      }
    })
  }

})();