import store from '@/store/index'

// 统一请求方法
export default function fetch(url, params = {}, method = 'POST', showFail = true) {
  let showLoading = true
  if (params && params.notShowLoading) {
    showLoading = false
  }
  if (showLoading) {
    uni.showLoading({
      mask: true,
      title: '加载中...'
    })
  }
  url = process.env.VUE_APP_BASE_URL + url
  params.token = store.getters.token
  params.student_id = params.student_id || store.getters.kid
  return new Promise((resolve, reject) => {
    uni.request({
      url,
      data: params,
      method,
      header: {},
      success: (res) => {
        uni.hideLoading()
        // 0:错误; 1:正确; 10000:没有token -2: 需要绑定手机
        const rs = res.data
        if (rs && rs.code === 1) {
          resolve(rs)
        } else if (rs.code === 10000) {
          // // 跳转至登录页
          uni.showModal({
            title: '请先登录',
            content: '您还没有登录,请先去登录',
            success: res => {
              if (res.confirm) {
                uni.navigateTo({ url: '/pages/login/index' })
              }
            }
          })
        } else {
          if (showFail) uni.showToast({ title: rs.msg, icon: 'none', duration: 2000 })// 直接提示错误
          resolve(rs)
        }
      },
      fail: (err) => {
        uni.hideLoading()
        uni.showToast({ title: err, icon: 'none', duration: 2000 })
        reject(err)
      }
    })
  })
}
