/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-06-15 18:13:37
 * @LastEditors: HJ
 * @LastEditTime: 2021-06-17 18:50:16
 */
const _JUMP_TYPE = {
  push: "navigateTo",
  replace: "redirectTo",
  reLaunch: "reLaunch",
  switchTab: "switchTab",
};

const _DEFAULT = {
  type: "push",
  query: {},
};

/**
 * 统一错误处理函数
 * @param {String|Object} error 错误信息
 */
const _errorHandle = (error) => {
  // wx.$log(error);
  console.error(error);
};

/**
 * 用户连接用户输入的query
 * @param {String} url 待处理url
 */
const _formatQuery = (url, rawQuery) => {
  const hasQuery = url.indexOf("?") !== -1;
  url += hasQuery ? "" : "?";

  for (let i in rawQuery) {
    url += `&${i}=${rawQuery[i]}`;
  }

  return url;
};

/**
 * 检测目标页面路径为空判断及是否为自身
 * @param {String} url 目标页面路径
 */
const _checkUrlOfLegitimate = (url) => {
  if (!url) {
    _errorHandle("Error: 目标页面路径不能为空");
    return false;
  }
  const { route } = getCurrentPages().pop();
  if (url === route) {
    _errorHandle("Error: 请勿将当前页面地址设置为跳转的目标页面路径");
    return false;
  }
  return true;
};

/**
 * 检测路由跳转方式是否合法
 * @param {String} type 路由跳转方式
 */
const _checkTypeLegitimate = (type) => {
  if (!_JUMP_TYPE[type]) {
    _errorHandle("Error: 请使用正确的跳转方式");
    return false;
  }
  return true;
};

/**
 * 拼接原生Api所需字符串，附带switchTab参数过滤功能
 * @param {String} url 目标页面路径
 * @param {String} query 已转码的路由参数
 * @param {String} type 路由跳转方式
 */
const _mergeQuery = (url, query, type) => {
  if (type === "switchTab") return url;
  return _formatQuery(url, query);
};

/**
 * 通用路由跳转参数，统一处理四种前进路由方法
 * @param {Object} param { url: String, query: Object, type: String success: Function } 路由跳转方法所需参数
 */
const _jump = ({ url: unprocessedUrl, query, type, success = () => {} }) => {
  const isUrlLegitimate = _checkUrlOfLegitimate(unprocessedUrl);
  if (!isUrlLegitimate) return undefined;
  const isTypeLegitimate = _checkTypeLegitimate(type);
  if (!isTypeLegitimate) return undefined;
  const url = _mergeQuery(unprocessedUrl, query, type);
  wx[_JUMP_TYPE[type]]({
    url,
    success,
    fail: (err) => _errorHandle(err),
  });
};

export const routerTo = (param, ...rest) => {
  const type = Object.prototype.toString.call(param);
  if (type === "[object String]") {
    const [query = {}] = rest;
    const options = {
      ..._DEFAULT,
      url: param,
      query,
    };
    _jump(options);
    return undefined;
  }
  if (type === "[object Object]") {
    const options = {
      ..._DEFAULT,
      ...param,
    };
    _jump(options);
    return undefined;
  }
  _errorHandle("Error: 参数有误");
};

export const back = (delta = 1) => wx.navigateBack({ delta });

export const goHome = () => wx.navigateBack({ delta: 100 });

wx.$routerTo = routerTo;
wx.$routerBack = back;

export default { routerTo, back, goHome };
