import { baseUrl } from "../config";

function getHeader() {
  if (wx.getStorageSync("token")) {
    return {
      "content-type": "application/json",
      "x-token": wx.getStorageSync("token"),
    };
  }
  return {
    "content-type": "application/json",
  };
}

function showErrToast(e) {
  wx.showToast({
    title: typeof e === "string" ? e : e.errMsg || e.toString(),
    icon: "none",
    duration: 1500,
  });
}

function getPromise(url, data, method) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseUrl}${url}`,
      header: getHeader(),
      method: method,
      data: data,
      success: function (res) {
        if (res.data.code === 200) {
          resolve(res.data.data);
        } else {
          if (res.statusCode === 401) {
            reject(401);
          } else {
            reject(res.data.message);
          }
        }
      },
      fail: function (err) {
        reject(err);
      },
    });
  }).catch((e) => {
    if (401 === e) {
      // redirect to login page
      wx.navigateTo({
        url: "/pages/login/login",
      });
    } else {
      console.error(`in promise error, url: ${baseUrl}${url}`);
      console.error(e);
      if (e) {
        showErrToast(e);
      }
    }
  });
}

const http = {
  get: function (url, data) {
    return getPromise(url, data, "GET");
  },
  post: function (url, data) {
    return getPromise(url, data, "POST");
  },
};

export default http;
