import { baseUrl } from '../utils/env'

const http = (data) => {
  var data = Object.assign({}, {
    url: '',
    method: 'POST',
    data: {},
    success: null,
    error: null,
    loadTitle: '加载中',
    showLoading: true
  }, data)
  if (data.showLoading) {
    wx.showLoading({
      title: data.loadTitle,
    })
  }

  var userinfo = wx.getStorageSync('sg-userinfo')
  var token = userinfo ? userinfo.token : ''
  wx.request({
    url: baseUrl + data.url,
    method: data.method,
    data: data.data,
    header: {
      'X-Token': token
    },
    success: function (res) {
      if (data.showLoading) wx.hideLoading()
      if (res.statusCode != 200) {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
        return false
      }
      if (res.data.code != 0) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
        if (res.data.code == -100) {
          var url = getCurrentUrl()
          if (url != 'pages/login/index') {
            wx.navigateTo({
              url: '/pages/login/index',
            })
          }
        }
      }
      typeof data.success === "function" && data.success(res.data)
    },
    fail: function (res) {
      console.log(res)
      typeof data.error === "function" && data.error(res.data)
    }
  })
}

const getCurrentUrl = () => {
  var pages = getCurrentPages()
  var page = pages[pages.length - 1]
  return page.route
}

module.exports = http