import ERROR_CODE from '../../config/error_code'
import { API_BASE_URL } from './../../config/config'
const BASE_URL = `${API_BASE_URL}/app/`
// 需要登录的错误码
const needLoginErrorCode = [3018, 3019]

Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
      function (value) {
          Promise.resolve(callback()).then(
              function () {
                  return value;
              }
          );
      },
      function (reason) {
          Promise.resolve(callback()).then(
              function () {
                  throw reason;
              }
          );
      }
  );
}

function request (url, options) {
  return new Promise((resolve, reject) => {
    wx.request(Object.assign({
      url: url.indexOf('://') === -1 ? BASE_URL + url : url,
      method: options.method,
      data: options.data,
      header: options.header || {},
      // header: {
      //   token: app.globalData.token
      // },
      success (res) {
        console.log(res.data, '请求成功')
        if (res.data.code == 0 || res.data.code == 200 || res.data.errno === 0) {
          resolve(res.data)
        } else if (needLoginErrorCode.indexOf(Number(res.data.code)) !== -1) {
          wx.navigateTo({
            url: `/pages/login/login`
          })
        } else {
          
          reject(res)
        }
      },
      fail (err) {
        console.log(err, '请求失败')
        reject(err)
      }
    }, options))
    setTimeout(() => reject('time out'), 5000)
  })
}

function get (url, data, options = {}) {
  options.method = 'GET'
  options.data = data
  return request(url, options)
}

function post (url, data = {}, options = {}) {
  options.method = 'POST'
  // token和user_ID放在url上, 后续后端再做优化
  const app = getApp();
  url += `?token=${getApp().globalData.token || ''}&viewerId=${getApp().globalData.userinfo.viewerId}`
  options.data = Object.assign({
    user_id: app.globalData.userinfo.user_id
  }, data)
  return request(url, options)
}

export default {
  request,
  get,
  post
}
