import { useStores } from "@/store/modules/index";
import configs from "@/config";
import { getToken } from "@/utils/auth";
import modal from "@/plugins/modal.plugins";
import common from "@/plugins/common.plugins";

let timeout = 10000;

/**
 * @校验结果方法
 * @param {数据集} res 
 * @param {结果抛出} resolve 
 * @param {控制台打印} reject 
 */
function verification(res, resolve, reject) {
  const data = typeof res.data === "string" ? JSON.parse(res.data) : res.data;
  const code = data.code || 200;

  if (code === 401) {
    useStores().LogOut().then(() => {
      //#ifdef H5
      uni.reLaunch({ url: "/pages/login" });
      //#endif

      //#ifdef APP-PLUS || MP-WEIXIN
      uni.reLaunch({ url: "/pages/login" });
      //#endif
    });
    modal.closeLoading();
    reject("无效的会话，或者会话已过期，请重新登录。");
  } else if (code === 404 || res.statusCode === 404) {
    if (data.msg.indexOf(":") !== -1) {
      modal.msg(data.msg.split(":")[1]);
      reject(data.msg.split(":")[1]);
    } else {
      modal.msg(data.msg);
      reject(data.msg);
    }
    modal.closeLoading();
  } else if (code === 500 || res.statusCode === 500 || code === 'BIZ-0000') {
    if (data.msg.indexOf(":") !== -1) {
      modal.msg(data.msg.split(":")[1]);
      reject(data.msg.split(":")[1]);
    } else {
      modal.msg(data.msg);
      reject(data.msg);
    }
    modal.closeLoading();
  } else if (code !== 200 && code !== "0") {
    reject(code);
  }
  resolve(data);
}

const request = (config) => {

  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getToken() && !isToken) {
    config.header["Authorization"] = getToken();
  }

  // get请求映射params参数
  if (config.params) {
    let url = config.url + "?" + common.tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }

  // 外部接口get请求映射params参数
  if (config.baseUrl) {
    let url = config.url + "?" + common.tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
    config.baseUrl = config.baseUrl + url
  }

  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || "get",
        timeout: config.timeout || timeout,
        url: config.baseUrl || configs.baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: "json",
      })
      .then((res) => {
        if (res.error) {
          modal.msg("后端接口连接异常");
          reject("后端接口连接异常");
          return;
        }
        verification(res, resolve, reject);//调用校验结果方法
      })
      .catch((error) => {
        let { errMsg } = error;
        if (!errMsg) return;
        if (errMsg === "Network Error") {
          errMsg = "后端接口连接异常";
        } else if (errMsg.includes("timeout")) {
          errMsg = "系统接口请求超时";
        } else if (errMsg.includes("Request failed with status code")) {
          errMsg = "系统接口" + errMsg.substr(errMsg.length - 3) + "异常";
        }
        if (errMsg != "request:fail") {
          modal.msg(errMsg);
        }
        reject(error);
      });
  });
};

const uploads = (config) => {
  const useStore = useStores();
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getToken() && !isToken) {
    config.header["Authorization"] = getToken();
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + "?" + common.tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      timeout: config.timeout || timeout,
      url: configs.baseUrl + config.url,
      filePath: config.filePath,
      name: config.name || "file",
      header: config.header,
      formData: config.formData,
      success: (res) => {
        verification(res, resolve, reject);//调用校验结果方法
      },
      fail: (error) => {
        let { errMsg } = error;
        if (errMsg == "Network Error") {
          errMsg = "后端接口连接异常";
        } else if (errMsg.includes("timeout")) {
          errMsg = "系统接口请求超时";
        } else if (errMsg.includes("Request failed with status code")) {
          errMsg = "系统接口" + errMsg.substr(errMsg.length - 3) + "异常";
        }
        if (errMsg != "request:fail") {
          modal.msg(errMsg);
        }
        reject(error);
      },
    });
  });
};

export {
  request,
  uploads
};
