utils.js 5.32 KB
Newer Older
1
import Cookies from 'js-cookie';
邓晓峰's avatar
邓晓峰 committed
2 3
import pathRegexp from 'path-to-regexp';
import { parse } from 'querystring';
4
import { cloneDeep } from 'lodash';
5
import pkg from '../../package.json';
6

邓晓峰's avatar
邓晓峰 committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/* 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 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 (
邓晓峰's avatar
邓晓峰 committed
43
    !!obj && // 有实际含义的变量才执行方法,变量null,undefined和''空串都为false
邓晓峰's avatar
邓晓峰 committed
44 45 46 47
    (typeof obj === 'object' || typeof obj === 'function') && // 初始promise 或 promise.then返回的
    typeof obj.then === 'function'
  );
}
邓晓峰's avatar
邓晓峰 committed
48 49 50 51

export function getBaseName() {
  return pkg.name.toLocaleLowerCase();
}
邓晓峰's avatar
邓晓峰 committed
52

邓晓峰's avatar
邓晓峰 committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
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()));
  };
};
73

74 75
export function getToken() {
  return Cookies.get('token');
76
}
77
export function setToken(token) {
78
  Cookies.set(token);
79
}
80 81 82 83 84 85 86 87
export function getVideoUrl() {
  const { protocol } = window.location;
  const address =
    protocol === 'https:'
      ? window.location.origin.replace(protocol, 'wss:')
      : window.location.origin.replace(protocol, 'ws:');
  return `${address}/`;
}
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
export const getImageUrl = path => {
  if (!path || typeof path !== 'string') return '';
  if (path.indexOf('http') === 0) {
    return path;
  }
  if (path.indexOf('data:') === 0) {
    return path;
  }
  if (path.startsWith('assets')) {
    return `${window.location.origin}/civweb4/${path}`.replace(/\\/g, '/');
  }
  if (path.startsWith('center/images')) {
    return `${window.location.origin}/${path}`.replace(/\\/g, '/');
  }
  if (path.includes('/个人信息/')) {
    path = `/cityinterface/rest/services/filedownload.svc/download${path}`;
    return path;
  }
  if (!path.includes('CityTemp') && !path.includes('图库')) {
    path = `CityTemp\\图库\\${path}`;
  }

  return `/PandaOMS/OMS/FileCenter/DownLoadFiles?module=图库&filePath=${encodeURIComponent(path)}`;
};
112 113 114 115 116 117 118

/**
 * 跳转到指定页面
 * @param {*} path  功能地址
 */
export const goToPath = (path, data, widgetId, mode) => {
  const routes = window.globalConfig?.allWidgets || [];
周宏民's avatar
周宏民 committed
119
  if (!path || !routes.length) return;
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  let info = null;
  const target = path.substr(0, 1) === '/' ? path.slice(1) : path;
  function urlSearch(arr) {
    arr.forEach(a => {
      if (a.url) {
        if (a.url.indexOf(target) > -1 && (!widgetId || a.url.indexOf(widgetId) > -1)) {
          // 跳转到指定板块功能
          if (mode) {
            if (a.widgetId && a.widgetId.split('_').includes(mode)) {
              info = cloneDeep(a);
            }
          } else {
            info = cloneDeep(a);
          }
        }
      }
      if (a.widgets) {
        urlSearch(a.widgets);
      }
    });
  }
  urlSearch(routes);
  if (!info) return info;
  info.url = info.url.substr(0, 1) === '/' ? info.url : `/${info.url}`;
  let url = `/civbase/${info.product}${info.url}`;
  const arr = url.split('|');
  let params = {};
  url = arr[0];
  if (arr[1]) {
    url += encodeURI(`|${arr[1]}`);
    const arrObj = arr[1].split('&');
    arrObj.forEach(item => {
      const temp = item.split('=');
      params[temp[0]] = temp[1];
    });
  }
  params = { ...params, ...data };
  params.widget = widgetId || params.widget;
  console.log(params, url);
  window.history.pushState(params, '', url);
};
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

/**
 * 查找功能的跳转地址
 * @param {*} path  功能地址
 */
export const searchUrl = path => {
  const routes = window.globalConfig?.widgets || [];

  let url = '';
  if (!path || !routes.length) return url;
  const target = path.substr(0, 1) === '/' ? path.slice(1) : path;
  function urlSearch(arr) {
    arr.forEach(a => {
      if (a.url) {
        if (a.url.indexOf(target) > -1) {
          url = a.url.substr(0, 1) === '/' ? a.url : `/${a.url}`;
          url = `/civbase/${a.product}${url}`;
        }
      }
      if (a.widgets) {
        urlSearch(a.widgets);
      }
    });
  }
  urlSearch(routes);
  if (!url) return url;
  return url;
};