const defaultHeader = {
  'Content-Type': 'application/x-www-form-urlencoded'
}

const jheader = {
  'Content-Type': 'application/json'
}


const url = 'http://118.24.176.28:8778'

let RQ = []
function request(api, method, header, data, hideLoading) {
  if (RQ.indexOf(api) > -1) {
    return console.error('http duplicate api:', api)
  }
  RQ.push(api)
  if (!hideLoading) {
    wx.showLoading({
      title: '加载中...'
    })
  }
  let pdata = {
    "companyId": 0,
    "from": 0,
    "page": 1,
    "reqdata": {},
    "rows": 10,
    "sidx": "",
    "sord": "",
    "token": "",
    "userId": 1
  }
  data = data || {}
  Object.assign(pdata, data)
  // data.token = getApp().data.at
  return new Promise((resolve, reject) => {
    wx.request({
      url: url + api,
      method: method,
      header: header,
      data: pdata,
      success: r => {
        if (r.statusCode == 200) {
          resolve(r.data)
        } else {
          wx.showToast({
            title: '系统繁忙！'
          })
        }
      },
      fail: e => {
        reject(e)
      },
      complete: e => {
        if (!hideLoading) {
          wx.hideLoading()
        }
        RQ.splice(RQ.indexOf(api), 1)
      }
    })
  })
}


function uploadFile(api, data, file, hideLoading) {
  if (!hideLoading) {
    wx.showLoading({
      title: '上传中...'
    })
  }
  data = data || {}
  // data.token = getApp().data.at
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: url + api,
      filePath: file,
      name: 'file',
      formData: data,
      success(r) {
        if (r.statusCode == 200) {
          console.log(r);
          resolve({url: r.data, state: 100})
        } else {
          console.log(r);
          console.error(r.errMsg)
          wx.showToast({
            title: '系统繁忙！'
          })
        }
      },
      fail(e) {
        reject(e)
      },
      complete(e) {
        if (!hideLoading) {
          wx.hideLoading()
        }
      }
    })
  })
}


module.exports = {
  post(api, data, hideLoading) {
    return request(api, "POST", jheader, data, hideLoading)
  },
  get(api, data, hideLoading) {
    return request(api, "GET", defaultHeader, data, hideLoading)
  },
  upload(api, data, file, hideLoading) {
    return uploadFile(api, data, file, hideLoading)
  }
}