utils.js 5.6 KB
Newer Older
1
import moment from 'moment';
ddcat1115's avatar
ddcat1115 committed
2
import React from 'react';
3
import { parse, stringify } from 'qs';
4

偏右's avatar
偏右 committed
5
export function fixedZero(val) {
6 7 8
  return val * 1 < 10 ? `0${val}` : val;
}

偏右's avatar
偏右 committed
9
export function getTimeDistance(type) {
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

jim's avatar
jim committed
32
    const beginTime = now.getTime() - day * oneDay;
33

jim's avatar
jim committed
34
    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
35 36 37 38 39 40 41 42 43
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

jim's avatar
jim committed
44 45 46 47
    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
    ];
48 49
  }

愚道's avatar
愚道 committed
50 51
  const year = now.getFullYear();
  return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
52
}
ddcat1115's avatar
ddcat1115 committed
53

54
export function getPlainNode(nodeList, parentPath = '') {
ddcat1115's avatar
ddcat1115 committed
55
  const arr = [];
jim's avatar
jim committed
56
  nodeList.forEach(node => {
ddcat1115's avatar
ddcat1115 committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

72 73 74 75
function accMul(arg1, arg2) {
  let m = 0;
  const s1 = arg1.toString();
  const s2 = arg2.toString();
jim's avatar
jim committed
76 77 78
  m += s1.split('.').length > 1 ? s1.split('.')[1].length : 0;
  m += s2.split('.').length > 1 ? s2.split('.')[1].length : 0;
  return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / 10 ** m;
79 80
}

81 82 83
export function digitUppercase(n) {
  const fraction = ['', ''];
  const digit = ['', '', '', '', '', '', '', '', '', ''];
jim's avatar
jim committed
84
  const unit = [['', '', '亿'], ['', '', '', '', '']];
85 86 87
  let num = Math.abs(n);
  let s = '';
  fraction.forEach((item, index) => {
88
    s += (digit[Math.floor(accMul(num, 10 * 10 ** index)) % 10] + item).replace(/零./, '');
89 90 91 92 93 94 95 96 97 98 99 100
  });
  s = s || '';
  num = Math.floor(num);
  for (let i = 0; i < unit[0].length && num > 0; i += 1) {
    let p = '';
    for (let j = 0; j < unit[1].length && num > 0; j += 1) {
      p = digit[num % 10] + unit[1][j] + p;
      num = Math.floor(num / 10);
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '') + unit[0][i] + s;
  }

jim's avatar
jim committed
101 102 103 104
  return s
    .replace(/(零.)*零元/, '')
    .replace(/(零.)+/g, '')
    .replace(/^整$/, '零元整');
105
}
ddcat1115's avatar
ddcat1115 committed
106 107 108

function getRelation(str1, str2) {
  if (str1 === str2) {
jim's avatar
jim committed
109
    console.warn('Two path are equal!'); // eslint-disable-line
ddcat1115's avatar
ddcat1115 committed
110 111 112 113 114
  }
  const arr1 = str1.split('/');
  const arr2 = str2.split('/');
  if (arr2.every((item, index) => item === arr1[index])) {
    return 1;
115 116
  }
  if (arr1.every((item, index) => item === arr2[index])) {
ddcat1115's avatar
ddcat1115 committed
117 118 119 120 121
    return 2;
  }
  return 3;
}

陈帅's avatar
陈帅 committed
122
function getRenderArr(routes) {
ddcat1115's avatar
ddcat1115 committed
123 124 125
  let renderArr = [];
  renderArr.push(routes[0]);
  for (let i = 1; i < routes.length; i += 1) {
陈帅's avatar
陈帅 committed
126
    // 去重
ddcat1115's avatar
ddcat1115 committed
127
    renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
Amumu's avatar
Amumu committed
128 129
    // 是否包含
    const isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
ddcat1115's avatar
ddcat1115 committed
130 131 132 133
    if (isAdd) {
      renderArr.push(routes[i]);
    }
  }
陈帅's avatar
陈帅 committed
134 135 136 137 138 139 140 141 142 143
  return renderArr;
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path, routerData) {
jim's avatar
jim committed
144 145 146
  let routes = Object.keys(routerData).filter(
    routePath => routePath.indexOf(path) === 0 && routePath !== path
  );
陈帅's avatar
陈帅 committed
147 148 149 150 151
  // Replace path to '' eg. path='user' /user/name => name
  routes = routes.map(item => item.replace(path, ''));
  // Get the route to be rendered to remove the deep rendering
  const renderArr = getRenderArr(routes);
  // Conversion and stitching parameters
jim's avatar
jim committed
152
  const renderRoutes = renderArr.map(item => {
ddcat1115's avatar
ddcat1115 committed
153 154
    const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
    return {
155
      exact,
ddcat1115's avatar
ddcat1115 committed
156
      ...routerData[`${path}${item}`],
ddcat1115's avatar
ddcat1115 committed
157 158 159 160 161 162
      key: `${path}${item}`,
      path: `${path}${item}`,
    };
  });
  return renderRoutes;
}
163

yoyo837's avatar
yoyo837 committed
164 165 166 167
export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

168 169 170 171 172 173 174 175
export function getQueryPath(path = '', query = {}) {
  const search = stringify(query);
  if (search.length) {
    return `${path}?${search}`;
  }
  return path;
}

176
/* eslint no-useless-escape:0 */
177
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
178 179 180 181

export function isUrl(path) {
  return reg.test(path);
}
ddcat1115's avatar
ddcat1115 committed
182 183 184

export function formatWan(val) {
  const v = val * 1;
185
  if (!v || Number.isNaN(v)) return '';
ddcat1115's avatar
ddcat1115 committed
186 187 188 189 190 191 192

  let result = val;
  if (val > 10000) {
    result = Math.floor(val / 10000);
    result = (
      <span>
        {result}
jim's avatar
jim committed
193 194
        <span
          styles={{
ddcat1115's avatar
ddcat1115 committed
195 196 197 198 199 200 201 202 203
            position: 'relative',
            top: -2,
            fontSize: 14,
            fontStyle: 'normal',
            lineHeight: 20,
            marginLeft: 2,
          }}
        >
          
ddcat1115's avatar
ddcat1115 committed
204
        </span>
ddcat1115's avatar
ddcat1115 committed
205 206 207 208 209
      </span>
    );
  }
  return result;
}
陈帅's avatar
陈帅 committed
210 211 212 213

export function isAntdPro() {
  return window.location.hostname === 'preview.pro.ant.design';
}