const { envDomain } = require('../utils/config')
const sessionStorageKey = 'baoGeDaBaReqSessionId'
const req = {
  baseURL: envDomain.apiDomain,
  header: {
    'content-type': 'application/json'
  }
}
let loading = 0
// 当前正在请求的数量
let needLoadingRequestCount = 0

// 显示loading
function _showLoading() {
  if (needLoadingRequestCount === 0 && !loading) {
    wx.showToast({
      title: '拼命获取中',
      icon: 'loading',
      duration: 86400000 // 设置1小时：类似一直显示
    })
    loading = 1
  }
  needLoadingRequestCount++
}

// 隐藏loading
function _hideLoading() {
  needLoadingRequestCount--
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) // 做个保护
  if (needLoadingRequestCount === 0) {
    // 关闭loading
    wx.hideToast()
    loading = 0
  }
}

/**
 * 登录
 */
function login() {
  return new Promise((resolve, reject) => {
    // 微信登录
    wx.login({
      success(res) {
        if (res.code) {
          resolve(res.code)
        } else {
          reject(res)
        }
      },
      fail: reject
    })
  })
}

/**
 * 判断请求状态是否成功
 * @param {number} status
 */
function isHttpSuccess(status) {
  return (status >= 200 && status < 300) || status === 304
}

/**
 * wx.request二次封装
 * @param options
 * @param keepLogin
 * @returns {Promise<unknown>}
 */
function request(options = {}, keepLogin = true) {
  const header = Object.assign({ 'access-token': wx.getStorageSync(sessionStorageKey) }, req.header,
    options.header)
  const url = /^http/.test(options.url) ? options.url : (req.baseURL + options.url)
  // 判断当前请求是否设置了不显示Loading
  if (options.showLoading) {
    _showLoading()
  }
  return new Promise((resolve, reject) => {
    wx.request(Object.assign({}, options, {
        url,
        header,
        success(r) {
          const isSuccess = isHttpSuccess(r.statusCode)
          const err = {
            msg: `服务器好像出了点小问题，请与客服联系~（错误代码：${r.statusCode}）`,
            detail: r
          }
          const pages = getCurrentPages()

          if (isSuccess) {
            if (r.data.code === 403) {
              wx.removeStorage({
                key: sessionStorageKey
              })
            }
            if (r.data.code === 403 && keepLogin) {
              const { route } = Array.isArray(pages) && pages.length ? pages[pages.length - 1] : {}
              if (!/^pages\/login\/login/.test(route)) {
                wx.navigateTo({
                  url: `/pages/login/login`
                })
              }
              reject(err)
              return
            }
            resolve(r.data)
            return
          }
          reject(err)
        },
        fail(err) {
          reject(err)
        },
        complete() {
          if (loading) {
            _hideLoading()
          }
        }
      }
    ))
  })
}

function handleUpload(filePath) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: `${req.baseURL}/api/upload/img`,
      filePath: filePath,
      name: 'file',
      formData: {
        'user': 'test'
      },
      success(r) {
        const isSuccess = isHttpSuccess(r.statusCode)
        if (isSuccess) {
          const temp = JSON.parse(r.data)
          if (temp.status && Object.prototype.toString.call(temp.data) === '[object Object]' &&
            temp.data.path) {
            resolve(temp.data.path)
          } else {
            reject(r)
          }
        } else {
          reject(r)
        }
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

module.exports = {
  request,
  handleUpload,
  login,
  sessionStorageKey
}
