Tools.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /**
  2. * 工具类
  3. */
  4. export const setDocumentTitle = title => {
  5. /**
  6. * 修改浏览器title 兼容ios
  7. */
  8. document.title = title;
  9. if (window.Env.isIos) {
  10. const i = document.createElement('iframe');
  11. i.src = '/favicon.ico';
  12. i.style.display = 'none';
  13. i.onload = () => {
  14. setTimeout(() => {
  15. i.remove();
  16. }, 10);
  17. };
  18. setTimeout(() => {
  19. document.body.appendChild(i);
  20. }, 500);
  21. }
  22. };
  23. export const setCookie = (name, value, time) => {
  24. const exp = new Date();
  25. exp.setTime(exp.getTime() + time * 1000);
  26. document.cookie = `${name}=${escape(value)};expires=${exp.toGMTString()};path=/`;
  27. };
  28. export const getCookie = name => {
  29. const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
  30. const arr = reg;
  31. if (arr === document.cookie.match(reg)) {
  32. return unescape(arr[2]);
  33. }
  34. return null;
  35. };
  36. export const delCookie = name => {
  37. const exp = new Date();
  38. exp.setTime(exp.getTime() - 1);
  39. const cval = window.getCookie(name);
  40. if (cval != null) {
  41. document.cookie = `${name}=${cval};expires=${exp.toGMTString()};path=/`;
  42. }
  43. };
  44. export const getQuery = name => {
  45. /**
  46. * 获取url参数
  47. */
  48. const reg = new RegExp(`(^|\\?|&)${name}=([^&]*)(&|$)`);
  49. const r = window.location.href.substr(1).match(reg);
  50. if (r != null) return unescape(r[2]);
  51. return null;
  52. };
  53. export function formatUrl(path, query) {
  54. let url = query ? `${path}?` : path;
  55. if (query) {
  56. Object.keys(query).forEach(i => {
  57. if (query[i] instanceof Object && query[i].length > 0) {
  58. query[i].forEach(k => {
  59. url += `${i}[]=${k}&`;
  60. });
  61. } else if (query[i] || query[i] === 0) {
  62. url += `${i}=${query[i]}&`;
  63. }
  64. });
  65. }
  66. return url;
  67. }
  68. export function checkMobile(s) {
  69. const { length } = s;
  70. if (length === 11 && /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(14[0-9]{1})|)+\d{8})$/.test(s)) {
  71. return true;
  72. }
  73. return false;
  74. }
  75. export function checkEmail(s) {
  76. if (/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(s)) {
  77. return true;
  78. }
  79. return false;
  80. }
  81. export function zeroFill(num, length) {
  82. return (Array(length).join('0') + num).slice(-length);
  83. }
  84. export function loadScript(url, callback) {
  85. const script = document.createElement('script');
  86. script.type = 'text/javascript';
  87. script.async = true;
  88. script.defer = true;
  89. if (script.readyState) {
  90. script.onreadystatechange = function () {
  91. if (script.readyState === 'loaded' || script.readyState === 'complete') {
  92. script.onreadystatechange = null;
  93. if (callback) callback();
  94. }
  95. };
  96. } else {
  97. script.onload = function () {
  98. if (callback) callback();
  99. };
  100. }
  101. script.src = url;
  102. const head = document.getElementsByTagName('head')[0];
  103. head.appendChild(script);
  104. }
  105. export function generateUUID(len, radix) {
  106. const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  107. const id = [];
  108. radix = radix || chars.length;
  109. if (len) {
  110. for (let i = 0; i < len; i += 1) id[i] = chars[0 | (Math.random() * radix)];
  111. } else {
  112. id[8] = id[13] = id[18] = id[23] = '-';
  113. id[14] = '4';
  114. for (let i = 0; i < 36; i += 1) {
  115. if (!id[i]) {
  116. const r = 0 | (Math.random() * 16);
  117. id[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
  118. }
  119. }
  120. }
  121. return id.join('');
  122. }
  123. export function SortBy(a, b, asc, type) {
  124. if (!a && a !== 0) {
  125. return 1;
  126. }
  127. if (!b && b !== 0) {
  128. return -1;
  129. }
  130. if (a === b) {
  131. return 0;
  132. }
  133. if (a === '') {
  134. return 1;
  135. }
  136. if (b === '') {
  137. return -1;
  138. }
  139. a = `${a}`;
  140. b = `${b}`;
  141. return (
  142. (type === 'number'
  143. ? a.localeCompare(b, undefined, { numeric: true })
  144. : a.localeCompare(b, 'zh', { co: 'pinyin' })) * asc
  145. );
  146. }
  147. export function SortByProps(item1, item2, props) {
  148. const cps = [];
  149. for (let i = 0; i < props.length; i += 1) {
  150. const prop = props[i];
  151. const asc = prop.direction > 0 ? 1 : -1;
  152. cps.push(SortBy(item1[prop.key], item2[prop.key], asc, prop.type));
  153. }
  154. for (let j = 0; j < cps.length; j += 1) {
  155. if (cps[j] === 1 || cps[j] === -1) {
  156. return cps[j];
  157. }
  158. }
  159. return false;
  160. }
  161. export function flattenTree(tree, fn, children = 'children') {
  162. const l = tree.map(item => {
  163. if (item[children] && item[children].length > 0) {
  164. const list = flattenTree(item[children], fn, children);
  165. return list.map((row) => fn(row, item));
  166. }
  167. return [item];
  168. });
  169. return [].concat(...l);
  170. }
  171. export function getMap(list, key = 'value', value = null, children = null) {
  172. const map = {};
  173. for (let i = 0; i < list.length; i += 1) {
  174. const item = list[i];
  175. let v = value ? item[value] : item;
  176. if (children && item[children] && item[children].length > 0) {
  177. v = getMap(item[children], key, value, children);
  178. }
  179. map[item[key]] = v;
  180. }
  181. return map;
  182. }
  183. export function searchKeyword(data, key, keyword, limit) {
  184. const list = [];
  185. const tmp = {};
  186. for (let i = 0; i < data.length; i += 1) {
  187. const item = key ? data[i][key] : data[i];
  188. if (item && !tmp[item] && item.indexOf(keyword) >= 0) {
  189. list.push(item);
  190. tmp[item] = true;
  191. if (limit && list.length >= limit) break;
  192. }
  193. }
  194. return list;
  195. }
  196. export function search(data = [], key, value) {
  197. const index = -1;
  198. for (let i = 0; i < data.length; i += 1) {
  199. if ((key && data[i][key] === value) || data[i] === value) {
  200. return i;
  201. }
  202. }
  203. return index;
  204. }
  205. export function dataURLtoBlob(dataurl) {
  206. const arr = dataurl.split(',');
  207. const mime = arr[0].match(/:(.*?);/)[1];
  208. const bstr = atob(arr[1]);
  209. const n = bstr.length;
  210. const u8arr = new Uint8Array(n);
  211. for (let i = 0; i < n; i += 1) {
  212. u8arr[i] = bstr.charCodeAt(i);
  213. }
  214. return new Blob([u8arr], { type: mime });
  215. }
  216. export function formatSecond(value) {
  217. let secondTime = parseInt(value || 0, 10); // 秒
  218. let minuteTime = 0;
  219. let hourTime = 0;
  220. if (secondTime > 60) {
  221. minuteTime = parseInt(secondTime / 60, 10);
  222. secondTime = parseInt(secondTime % 60, 10);
  223. hourTime = parseInt(minuteTime / 60, 10);
  224. minuteTime = parseInt(minuteTime % 60, 10);
  225. }
  226. if (hourTime >= 10) {
  227. hourTime = `${hourTime}`;
  228. } else {
  229. hourTime = `0${hourTime}`;
  230. }
  231. if (minuteTime >= 10) {
  232. minuteTime = `${minuteTime}`;
  233. } else {
  234. minuteTime = `0${minuteTime}`;
  235. }
  236. if (secondTime >= 10) {
  237. secondTime = `${secondTime}`;
  238. } else {
  239. secondTime = `0${secondTime}`;
  240. }
  241. return `${hourTime}:${minuteTime}:${secondTime}`;
  242. }
  243. export function formatMinuteSecond(value) {
  244. let secondTime = parseInt(value || 0, 10); // 秒
  245. let minuteTime = 0;
  246. if (secondTime > 60) {
  247. minuteTime = parseInt(secondTime / 60, 10);
  248. secondTime = parseInt(secondTime % 60, 10);
  249. }
  250. if (minuteTime >= 10) {
  251. minuteTime = `${minuteTime}`;
  252. } else {
  253. minuteTime = `0${minuteTime}`;
  254. }
  255. if (secondTime >= 10) {
  256. secondTime = `${secondTime}`;
  257. } else {
  258. secondTime = `0${secondTime}`;
  259. }
  260. return `${minuteTime}:${secondTime}`;
  261. }
  262. export function formatFormError(data, err, prefix = '') {
  263. const r = {};
  264. Object.keys(err).forEach(field => {
  265. r[`${prefix}${field}`] = { value: data[field], errors: err[field].map(e => new Error(e)) };
  266. });
  267. return r;
  268. }
  269. export function formatDate(time, format = 'YYYY-MM-DD HH:mm:ss') {
  270. const date = new Date(time);
  271. const o = {
  272. 'M+': date.getMonth() + 1,
  273. 'D+': date.getDate(),
  274. 'H+': date.getHours(),
  275. 'm+': date.getMinutes(),
  276. 's+': date.getSeconds(),
  277. 'q+': Math.floor((date.getMonth() + 3) / 3),
  278. S: date.getMilliseconds(),
  279. };
  280. if (/(Y+)/.test(format)) format = format.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length));
  281. Object.keys(o).forEach(k => {
  282. if (new RegExp(`(${k})`).test(format)) {
  283. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length));
  284. }
  285. });
  286. return format;
  287. }
  288. export function formatMinute(seconds, number = true) {
  289. const time = parseInt(seconds || 0, 10);
  290. return number ? parseInt(time / 60, 10) : `${parseInt(time / 60, 10)}min`;
  291. }
  292. export function formatSeconds(seconds, rand = false) {
  293. const time = parseInt(seconds || 0, 10);
  294. if (time < 60) {
  295. return `${time}s`;
  296. }
  297. if (time >= 60 && time < 3600) {
  298. return `${parseInt(time / 60, 10)}min${rand ? '' : formatSeconds(time % 60)}`;
  299. }
  300. return `${parseInt(time / 3600, 10)}hour${rand ? '' : formatSecond(time % 3600)}hour`;
  301. }
  302. export function formatPercent(child, mother, number = true) {
  303. if (!mother || !child) return number ? 0 : '0%';
  304. return number ? Math.floor((child * 100) / mother) : `${Math.floor((child * 100) / mother)}%`;
  305. }
  306. export function formatTreeData(list, key = 'id', title = 'title', index = 'parent_id') {
  307. const map = getMap(list, key);
  308. const result = [];
  309. list.forEach(row => {
  310. row.children = [];
  311. row.title = row[title];
  312. if (!row.key) row.key = `${row[key]}`;
  313. row.value = row[key];
  314. });
  315. list.forEach(row => {
  316. if (row[index] && map[row[index]]) {
  317. if (!map[row[index]].children) map[row[index]].children = [];
  318. map[row[index]].children.push(row);
  319. } else {
  320. result.push(row);
  321. }
  322. });
  323. return result;
  324. }
  325. export function flattenObject(ob, prefix = '', force = false) {
  326. const toReturn = {};
  327. if (prefix) prefix = `${prefix}.`;
  328. Object.keys(ob).forEach(i => {
  329. if (typeof ob[i] === 'object' && ob[i] !== null && !ob[i].length) {
  330. const flatObject = flattenObject(ob[i]);
  331. Object.keys(flatObject).forEach(x => {
  332. toReturn[`${prefix}${i}.${x}`] = flatObject[x];
  333. });
  334. } else if (force && ob[i].length) {
  335. ob[i].forEach((row, index) => {
  336. const flatObject = flattenObject(row);
  337. Object.keys(flatObject).forEach(x => {
  338. toReturn[`${prefix}${i}.${index}.${x}`] = flatObject[x];
  339. });
  340. });
  341. } else {
  342. toReturn[`${prefix}${i}`] = ob[i];
  343. }
  344. });
  345. return toReturn;
  346. }
  347. function _formatMoney(s, n) {
  348. if (!s) s = 0;
  349. n = n > 0 && n <= 20 ? n : 2;
  350. s = `${parseFloat(`${s}`.replace(/[^\d.-]/g, '')).toFixed(n)}`;
  351. const l = s
  352. .split('.')[0]
  353. .split('')
  354. .reverse();
  355. const r = s.split('.')[1];
  356. let t = '';
  357. for (let i = 0; i < l.length; i += 1) {
  358. t += l[i] + ((i + 1) % 3 === 0 && i + 1 !== l.length ? ',' : '');
  359. }
  360. return `${t
  361. .split('')
  362. .reverse()
  363. .join('')}.${r}`;
  364. }
  365. export function formatMoney(price) {
  366. if (typeof price === 'object') {
  367. return `${price.symbol} ${_formatMoney(price.value, 2)}`;
  368. }
  369. return `${_formatMoney(price, 2)}`;
  370. }
  371. export function bindTags(targetList, field, render, def, notFound) {
  372. let index = -1;
  373. targetList.forEach((row, i) => {
  374. if (row.key === field) index = i;
  375. });
  376. targetList[index].notFoundContent = notFound;
  377. targetList[index].select = (def || []).map(row => {
  378. return render(row);
  379. });
  380. }
  381. export function bindSearch(targetList, field, Component, listFunc, render, def, notFound = null) {
  382. let index = -1;
  383. targetList.forEach((row, i) => {
  384. if (row.key === field) index = i;
  385. });
  386. const key = `lastFetchId${field}${index}${generateUUID(4)}`;
  387. if (!Component[key]) Component[key] = 0;
  388. const searchFunc = data => {
  389. Component[key] += 1;
  390. const fetchId = Component[key];
  391. targetList[index].loading = true;
  392. Component.setState({ fetching: true });
  393. listFunc(data).then(result => {
  394. if (fetchId !== Component[key]) {
  395. // for fetch callback order
  396. return;
  397. }
  398. targetList[index].select = (result.list || result || []).map(row => {
  399. return render(row);
  400. });
  401. targetList[index].loading = false;
  402. Component.setState({ fetching: false });
  403. });
  404. };
  405. const item = {
  406. showSearch: true,
  407. showArrow: true,
  408. filterOption: false,
  409. onSearch: keyword => {
  410. searchFunc({ page: 1, size: 5, keyword });
  411. },
  412. notFoundContent: notFound,
  413. };
  414. targetList[index] = Object.assign(targetList[index], item);
  415. if (def) {
  416. if (targetList[index].type === 'multiple' || targetList[index].mode === 'multiple') {
  417. searchFunc({ ids: def, page: 1, size: def.length });
  418. } else {
  419. searchFunc({ ids: [def], page: 1, size: 1 });
  420. }
  421. } else {
  422. item.onSearch();
  423. }
  424. }
  425. export function generateSearch(field, props, Component, listFunc, render, def, notFound = null) {
  426. const key = `lastFetchId${field}${generateUUID(4)}`;
  427. if (!Component[key]) Component[key] = 0;
  428. let item = {
  429. showSearch: true,
  430. showArrow: true,
  431. filterOption: false,
  432. notFoundContent: notFound,
  433. };
  434. item = Object.assign(props || {}, item);
  435. const searchFunc = data => {
  436. Component[key] += 1;
  437. const fetchId = Component[key];
  438. item.loading = true;
  439. Component.setState({ [field]: item, fetching: true });
  440. listFunc(data).then(result => {
  441. if (fetchId !== Component[key]) {
  442. // for fetch callback order
  443. return;
  444. }
  445. item.select = result.list.map(row => {
  446. return render(row);
  447. });
  448. item.loading = false;
  449. Component.setState({ [field]: item, fetching: false });
  450. });
  451. };
  452. item.onSearch = keyword => {
  453. searchFunc({ page: 1, size: 5, keyword });
  454. };
  455. if (def) {
  456. if (item.mode === 'multiple' || item.type === 'multiple') {
  457. searchFunc({ ids: def, page: 1, size: def.length });
  458. } else {
  459. searchFunc({ ids: [def], page: 1, size: 1 });
  460. }
  461. } else {
  462. item.onSearch();
  463. }
  464. Component.setState({ [field]: item });
  465. }
  466. export function getHtmlText(text) {
  467. text = text.replace(new RegExp(/\r\n/, 'g'), '\r').replace(new RegExp(/\n/, 'g'), '\r');
  468. let html = '';
  469. text.split('\r').forEach(item => {
  470. item.split(' ').forEach(t => {
  471. html += `< i uuid = "${generateUUID(4)}" > ${t}</i > `;
  472. });
  473. html += '<br/>';
  474. });
  475. return html;
  476. }
  477. export function getSimpleText(html) {
  478. let text = html.replace(new RegExp('<br/>', 'g'), '\n\r');
  479. text = text.replace(new RegExp('<.+?>', 'g'), '');
  480. return text;
  481. }
  482. export function randomList(length) {
  483. const list = [];
  484. for (let i = 0; i < length; i += 1) {
  485. list.push(i);
  486. }
  487. for (let i = 0; i < length; i += 1) {
  488. const o = Math.floor(Math.random() * length);
  489. const tmp = list[o];
  490. list[o] = list[i];
  491. list[i] = tmp;
  492. }
  493. return list;
  494. }
  495. export function sortListWithOrder(target, order) {
  496. const list = [];
  497. order.forEach(t => {
  498. list.push(target[t]);
  499. });
  500. return list;
  501. }
  502. export function resortListWithOrder(target, order) {
  503. const list = [];
  504. for (let i = 0; i < order.length; i += 1) {
  505. list.push('');
  506. }
  507. order.forEach((t, i) => {
  508. list[t] = target[i];
  509. });
  510. return list;
  511. }
  512. // 下划线转换驼峰
  513. export function toHump(name) {
  514. return name.replace(/_(\w)/g, (all, letter) => {
  515. return letter.toUpperCase();
  516. });
  517. }
  518. // 驼峰转换下划线
  519. export function toLine(name) {
  520. return name.replace(/([A-Z])/g, '_$1').toLowerCase();
  521. }
  522. export function formatMonth(days, number = true) {
  523. return number ? parseInt(days / 30, 10) : `${parseInt(days / 30, 10)}个月`;
  524. }
  525. export function timeRange(timerange) {
  526. let startTime = null;
  527. let endTime = null;
  528. switch (timerange) {
  529. case 'all':
  530. break;
  531. case 'week':
  532. endTime = new Date();
  533. startTime = new Date(endTime.getTime() - 86400000 * 7);
  534. break;
  535. case 'month':
  536. endTime = new Date();
  537. startTime = new Date();
  538. startTime.setMonth(startTime.getMonth() - 1);
  539. break;
  540. case 'month3':
  541. endTime = new Date();
  542. startTime = new Date();
  543. startTime.setMonth(startTime.getMonth() - 3);
  544. break;
  545. case 'today':
  546. default:
  547. startTime = new Date();
  548. startTime.setHours(0, 0, 0, 0);
  549. endTime = new Date(startTime.getTime() + 86400000);
  550. }
  551. return [startTime, endTime];
  552. }