import { apiCode } from '../config/code'

function isArray (arg) {
  return Object.prototype.toString.call(arg) === '[object Array]';
}

export default (config = {}) => {
  return new Promise((resolve, reject) => {
    wx.showLoading({ title: '数据处理中, 请稍后...', mask: true })

    let { query, url } = config

    // query 只支持 url rfc 定义的内容
    if (query) {
      const searchStr = Object.keys(query).map((key) => {
        const val = query[key]
        return !isArray(val) ? `${key}=${val}` : val.map(it => `${key}=${it}`).join('&')
      }).join('&')

      const sign = url.indexOf('?') > -1 ? '&' : '?'
      url = `${url}${sign}${searchStr}`
    }

    wx.request({
      url: url,
      method: config.method,
      data: config.data,
      success(res) {
        wx.hideLoading()
        if (res.statusCode === apiCode.success && res.data.code === apiCode.success) {
          resolve(res.data)
        } else {
          reject(res.data.message + "失败")
        }
      },
      error(msg) {
        wx.hideLoading()
        reject(msg)
      }
    })
  })
}
