import { Tips } from "./util";

const __LOG = (...arg) => {
  try {
    wx.$log.info(...arg);
    wx.$env.env !== "prod" && console.debug(...arg);
  } catch (e) {
    console.error("axios config error", e);
  }
};

// 重写请求
const _request = wx.request;
function _transformRequest(method, { url = '', header = {}, ...options }) {
  const { baseUrl } = wx.$env;
  url = (/^htt[p|ps]/.test(url) ? "" : baseUrl) + url;
  __LOG({ str: "发送请求:" }, JSON.stringify({ url, header, options }));
  return method.call(this, { ...options, url, header });
}
Object.defineProperties(wx, {
  request: {
    get() {
      return _transformRequest.bind(this, _request);
    },
  },
});

function request(url, urldata, params, method, success, fail) {
  this.requestLoading(url, urldata, params, method, "", success, fail);
  this.requestLoadingmember(url, urldata, params, method, "", success, fail);
  this.requestLoadingno(url, urldata, params, method, "", success, fail);
  this.requestOss(url, urldata, params, method, "", success, fail);
}

const passArr = [200, 404, 601, 3030, 521, 222, 6003, 10];

const codeFn = new Map([
  [
    1001,
    () => {
      getApp().getData();
    },
  ],
  [
    520,
    ({ _success, data }) => {
      const { message } = data;
      wx.showToast({
        title: message,
        duration: 1000,
        mask: true,
        icon: "none",
        success: function () {
          setTimeout(function () {
            _success(data);
          }, 1000);
        },
      });
    },
  ],
  [
    2002,
    () => {
      wx.showToast({
        title: res.data.message,
        duration: 1000,
        mask: true,
        icon: "none",
        success: function () {
          setTimeout(function () {
            wx.redirectTo({
              url: "/pages/empty/empty",
            });
          }, 2000);
        },
      });
    },
  ],
  [
    525,
    ({ _success, data }) => {
      wx.showToast({
        title: data.message,
        duration: 1000,
        mask: true,
        icon: "none",
        success: function () {
          setTimeout(function () {
            _success(data);
          }, 1000);
        },
      });
    },
  ],
  [
    522,
    ({ _success, data }) => {
      wx.showToast({
        title: data.message,
        duration: 2000,
        mask: true,
        icon: "none",
        success: function () {
          setTimeout(function () {
            _success(data);
          }, 2000);
        },
      });
    },
  ],
]);

const __ERROR_MESSAGE = "您的网络开了个小差，请稍后重试！";

// fail;
const __FAIL_FN = ({ _fail, res }) => {
  const { data = {} } = res || {};
  const { message = __ERROR_MESSAGE, code } = data;
  wx.hideNavigationBarLoading();
  const msg = typeof message === "string" ? message : __ERROR_MESSAGE;
  Tips(msg);
  console.log(`报错原因:${msg}`);
  __LOG({ str: "请求错误:" }, { response: data });
  // _fail && _fail(res);
  if (code !== 9999) _fail && _fail(res);
};

const __SUCCESS_FN = (_success, _fail, res, unHideLoad) => {
  const { data } = res;
  const { code } = data;
  if (passArr.includes(code)) {
    _success(data);
    !unHideLoad && wx.hideLoading();
  } else if (codeFn.has(code)) {
    const fn = codeFn.get(code);
    fn ? fn({ _success, _fail, data }) : _fail(res);
    setTimeout(() => {
      !unHideLoad && wx.hideLoading();
    }, 1000 * 1.2);
  } else {
    __FAIL_FN({ _fail, res });
  }
};

// 展示进度条的网络请求// url:网络请求的url
// // params:请求参数
// // message:进度条的提示信息
// // success:成功的回调函数
// // fail：失败的回调

function requestLoadingmember(
  url,
  urldata,
  params,
  method,
  message,
  _success,
  _fail
) {
  wx.showLoading({
    title: message,
    mask: true,
  });
  const hospitalInfo = getApp().getHospitalInfo();
  urldata = { ...urldata, ...hospitalInfo };
  params = { ...params, ...hospitalInfo };
  url += (url.indexOf("?") < 0 ? "?" : "&") + paramurl(urldata);
  wx.request({
    url: url,
    data: params,
    header: {
      "Content-Type": "application/json",
      "WX-MINI-APP-TOKEN": wx.getStorageSync("token"),
      "origin-name": "client",
    },
    method: method,
    success: function (res) {
      wx.hideLoading();
      __SUCCESS_FN(_success, _fail, res);
    },
    fail: function (res) {
      __FAIL_FN({ _fail, res });
    },
    complete: function (res) {},
  });
}

function requestLoading(
  url,
  urldata,
  params,
  method,
  message,
  _success,
  _fail,
  unHideLoad = false
) {
  !unHideLoad &&
    wx.showLoading({
      title: message,
      mask: true,
    });
  const hospitalInfo = getApp().getHospitalInfo();
  urldata = { ...urldata, ...hospitalInfo };
  params = { ...params, ...hospitalInfo };
  url += (url.indexOf("?") < 0 ? "?" : "&") + paramurl(urldata);
  wx.request({
    url: url,
    data: params,
    header: {
      "Content-Type": "application/json",
      "TOP50-WAIMAI-API-VERSION": "1.0.7",
      "origin-name": "client",
      "WX-MINI-APP-TOKEN": wx.getStorageSync("token"),
    },
    method: method,
    success: function (res) {
      __SUCCESS_FN(_success, _fail, res, unHideLoad);
    },
    fail: function (res) {
      __FAIL_FN({ _fail, res });
    },
    complete: function (res) {},
  });
}
// oss的请求
function requestOss(url, urldata, params, method, message, _success, _fail) {
  wx.showLoading({
    title: message,
    mask: true,
  });
  const hospitalInfo = getApp().getHospitalInfo();
  urldata = { ...urldata, ...hospitalInfo };
  params = { ...params, ...hospitalInfo };
  url += (url.indexOf("?") < 0 ? "?" : "&") + paramurl(urldata);
  wx.request({
    url: url,
    data: params,
    header: {
      "Content-Type": "application/json",
      "origin-name": "client",
      "WX-MINI-APP-TOKEN": wx.getStorageSync("token"),
      "OSS-SERVICE-TOKEN" : "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1Nzg2MjE4MzcsInN1YiI6IntcImZyb21TZXJ2aWNlU3lzdGVtXCI6XCJUb3A1MFwifSJ9.lKXaeSgt_yO1SYl2Oz27UHdXqt_-PKPWo2KlWDJ02iQ",
      "TOP50-SERVICE-TOKEN":
        "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1Nzg2MjE4MzcsInN1YiI6IntcImZyb21TZXJ2aWNlU3lzdGVtXCI6XCJUb3A1MFwifSJ9.lKXaeSgt_yO1SYl2Oz27UHdXqt_-PKPWo2KlWDJ02iQ",
    },
    method: method,
    success: function (res) {
      wx.hideLoading();
      __SUCCESS_FN(_success, _fail, res);
    },
    fail: function (res) {
      __FAIL_FN({ _fail, res });
    },
    complete: function (res) {},
  });
}
// 无token请求
function requestLoadingno(
  url,
  urldata,
  params,
  method,
  message,
  _success,
  _fail,
  unHideLoad
) {
  wx.showLoading({
    title: message,
    mask: true,
  });
  const hospitalInfo = getApp().getHospitalInfo();
  urldata = { ...urldata, ...hospitalInfo };
  params = { ...params, ...hospitalInfo };
  url += (url.indexOf("?") < 0 ? "?" : "&") + paramurl(urldata);
  wx.request({
    url: url,
    data: params,
    header: {
      "Content-Type": "application/json",
      "TOP50-WAIMAI-API-VERSION": "1.0.7",
      "origin-name": "client",
    },
    method: method,
    success: function (res) {
      __SUCCESS_FN(_success, _fail, res, unHideLoad);
    },
    fail: function (res) {
      __FAIL_FN({ _fail, res });
    },
    complete: function (res) {},
  });
}

function paramurl(data) {
  let url = "";
  // 遍历data对象，取出需要的参数
  for (var k in data) {
    // 如果当前value为undefined ，则返回空字符串
    let value = data[k] !== undefined ? data[k] : "";
    // 得到参数，并且拼接参数，为下一步拼接到url后面做准备
    url += "&" + k + "=" + encodeURIComponent(value);
  }
  // 如果url存在，则去除首字符并返回，因为主函数已经包含了'&'，否则返回空串
  return url ? url.substring(1) : "";
}

module.exports = {
  request: request,
  requestLoading: requestLoading,
  requestLoadingno: requestLoadingno,
  requestLoadingmember: requestLoadingmember,
  requestOss: requestOss,
  __FAIL_FN,
};
