import Cookies from 'js-cookie';
import pathRegexp from 'path-to-regexp';
import { parse } from 'querystring';

import pkg from '../../package.json';

const { toString } = Object.prototype;
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = path => reg.test(path);

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

export const getAuthorityFromRouter = (router, pathname) => {
  const authority = router.find(
    ({ routes, path = '/', target = '_self' }) =>
      (path && target !== '_blank' && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};

export const getRouteAuthority = (path, routeData) => {
  let authorities;
  routeData.forEach(route => {
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      }
      if (route.path === path) {
        authorities = route.authority || authorities;
      }

      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

export function isPromise(obj) {
  return (
    !!obj && // 有实际含义的变量才执行方法，变量null，undefined和''空串都为false
    (typeof obj === 'object' || typeof obj === 'function') && // 初始promise 或 promise.then返回的
    typeof obj.then === 'function'
  );
}

export function getBaseName() {
  return pkg.name.toLocaleLowerCase();
}
let cache = {};
export function findPathByLeafId(leafId, nodes, path, key, clear) {
  if (path === undefined) {
    path = {};
  }
  let tmpPath = path;
  if(clear) {
    cache = {};
  }
  if (cache[leafId]) {
    return cache[leafId];
  }
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < nodes.length; i++) {
    if (nodes[i] && nodes[i][key] && leafId === nodes[i][key]) {
      tmpPath = nodes[i];
      cache[leafId] = tmpPath;
      return tmpPath;
    }
    if (nodes[i] && nodes[i].routes) {
      const findResult = findPathByLeafId(
        leafId,
        nodes[i].routes,
        tmpPath,
        key,
      );
      if (findResult) {
        cache[leafId] = findResult;
        return findResult;
      }
    }
  }
}

export function transformURL(path) {
  //civweb4/
  // path = path.replace(/[(\\|)|(&)]widget=[0-9]*/, '');
  const el = document.createElement('input');
  el.value = path;
  String.fromCharCode(92);
  return el.value.replace(/\\/g, '/');
}

export function findPathByWidget(leafId, nodes, path, key) {
  if (path === undefined) {
    path = {};
  }
  let tmpPath = path;
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < nodes.length; i++) {
    if (nodes[i] && nodes[i][key] && nodes[i][key].indexOf(leafId) > -1) {
      tmpPath = nodes[i];
      return tmpPath;
    }
    if (nodes[i] && nodes[i].widgets) {
      const findResult = findPathByWidget(
        leafId,
        nodes[i].widgets,
        tmpPath,
        key,
        // eslint-disable-next-line no-restricted-globals
        location,
      );
      if (findResult) {
        return findResult;
      }
    }
  }
  return tmpPath;
}

export function isJSON(str) {
  if (typeof str === 'string') {
    try {
      const obj = JSON.parse(str);
      if (typeof obj === 'object' && obj) {
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }
}

export function isString(str) {
  return toString.call(str) === '[object String]';
}

export const getKeyName = path => {
  const truePath = path.split('?')[0];
  const curRoute = [].filter(item => item.path.includes(truePath));

  if (!curRoute[0]) {
    return {
      title: '暂无权限',
      tabKey: '403',
    };
  }
  const { name, key, component } = curRoute[0];
  return { title: name, tabKey: key, component };
};

export const asyncAction = action => {
  const wait = new Promise(resolve => resolve(action));
  return callback => {
    wait.then(() => setTimeout(() => callback()));
  };
};

export function getToken() {
  return Cookies.get('token');
}
export function setToken(token) {
  Cookies.set(token);
}
export const closeTabAction = (history, returnUrl, callback) => {};
