const app = getApp();
const baseURL = "https://www.wxmini.getensh.com/api/v1";
const FN = require('../public');
const Request = (options) => {
  return new Promise((resolve, reject) => {
    FN.Loading()
    wx.request({
      url: baseURL + options.url || '',
      data: options.data || {},
      method: options.method || 'GET',
      header: {
        token: wx.getStorageSync('token') || "",
        "Access-Control-Allow-Origin": "*"
      },
      responseType: options.responseType || "",
      timeout: 15000,
      dataType: "json",
      success(res) {
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            if (['put', 'post', 'delete'].includes(options.method)) {
              resolve(res.data);
            } else {
              resolve(res.data.data);
            }
          } else if ([10009, 10008].includes(res.data.code)) {
            app.getWxCode();
            if (res.data.code == 10008) {
              FN.Toast("请先登录")
              setTimeout(() => {
                wx.switchTab({
                  url: '/page/tabBar/mine/index',
                })
              }, 1000)
            } else {
              wx.showToast({
                title: '登录已过期，请重新登录',
                icon: "none",
                success() {
                  app.globalData.user_encrypt = {};
                  app.globalData.user_iv = {};
                  app.loginout();
                  wx.clearStorageSync(),
                    setTimeout(() => {
                      wx.switchTab({
                        url: '/page/tabBar/mine/index',
                      })
                    }, 1000)
                }
              })
            }
          } else {
            if (res.data.message) {
              wx.showToast({
                title: res.data.message,
                icon: "none"
              })
            }
            resolve(res.data);
          }
        } else if (res.statusCode === 502) {
          FN.Toast("服务不可用");
        } else {
          FN.Toast(res.errMsg);
        };
      },
      fail(res) {
        FN.Toast("网络开小差了");
        reject(res);
      },
      complete(e) {
        setTimeout(() => {
          FN.LoadingOff();
        }, 500)
      }
    })
  })
};


module.exports = {
  Request
};