import store from '@/store/index'

let token = ''

export const baseUrl = 'http://192.168.0.103:9095/baby-institute-back-end' // 本地开发
// export const baseUrl = 'https://ex.by-health.com/baby-institute-back-end' // 生产

// 获取最新 token
export function getToken () {
  if (!token) {
    token = (store.state.userInfo && store.state.userInfo.token) || ''
  }

  return token
}

// 每 .5s 校验一次 token 是否存在
function checkToken () {
  return new Promise(async (resolve, reject) => {
    let inter = setInterval(() => {
      if (getToken()) {
        clearInterval(inter)
        resolve()
      } else {
        console.log('等待token')
      }
    }, 500)
  })
}

export function request (url, method, data) {
  return new Promise(async (resolve, reject) => {
    // 除登录接口外都需要 token
    // mpvue 生命周期不能同步执行问题 定时校验token
    if (url.indexOf('login') < 0 && !getToken()) {
      await checkToken()
    }
    wx.request({
      url: baseUrl + url, // 仅为示例，并非真实的接口地址
      method: method,
      data: data,
      header: {
        'content-type': 'application/json',
        'Authorization': token
      },
      success: function (res) {
        let {code, data, msg} = res.data

        if (code === 200) {
          resolve(data)
        // } else if (code === 401) {
        } else {
          wx.showToast({
            title: msg || '网络错误',
            icon: 'none'
          })
          reject(res.data)
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}

export function put (url, data) {
  return request(url, 'PUT', data)
}

export function get (url, data) {
  return request(url, 'GET', data)
}

export function post (url, data) {
  return request(url, 'POST', data)
}
