Tools.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 formatSecondAuto(value) {
  263. let secondTime = parseInt(value || 0, 10); // 秒
  264. let minuteTime = 0;
  265. let hourTime = 0;
  266. if (secondTime > 60) {
  267. minuteTime = parseInt(secondTime / 60, 10);
  268. secondTime = parseInt(secondTime % 60, 10);
  269. }
  270. if (minuteTime > 60) {
  271. hourTime = parseInt(minuteTime / 60, 10);
  272. minuteTime = parseInt(minuteTime % 60, 10);
  273. }
  274. if (hourTime >= 10) {
  275. hourTime = `${hourTime}`;
  276. } else {
  277. hourTime = `0${hourTime}`;
  278. }
  279. if (minuteTime >= 10) {
  280. minuteTime = `${minuteTime}`;
  281. } else {
  282. minuteTime = `0${minuteTime}`;
  283. }
  284. if (secondTime >= 10) {
  285. secondTime = `${secondTime}`;
  286. } else {
  287. secondTime = `0${secondTime}`;
  288. }
  289. if (hourTime > 0) {
  290. return `${hourTime}:${minuteTime}:${secondTime}`;
  291. }
  292. return `${minuteTime}:${secondTime}`;
  293. }
  294. export function formatFormError(data, err, prefix = '') {
  295. const r = {};
  296. Object.keys(err).forEach(field => {
  297. r[`${prefix}${field}`] = { value: data[field], errors: err[field].map(e => new Error(e)) };
  298. });
  299. return r;
  300. }
  301. export function formatDate(time, format = 'YYYY-MM-DD HH:mm:ss') {
  302. const date = new Date(time);
  303. const o = {
  304. 'M+': date.getMonth() + 1,
  305. 'D+': date.getDate(),
  306. 'H+': date.getHours(),
  307. 'm+': date.getMinutes(),
  308. 's+': date.getSeconds(),
  309. 'q+': Math.floor((date.getMonth() + 3) / 3),
  310. S: date.getMilliseconds(),
  311. };
  312. if (/(Y+)/.test(format)) format = format.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length));
  313. Object.keys(o).forEach(k => {
  314. if (new RegExp(`(${k})`).test(format)) {
  315. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length));
  316. }
  317. });
  318. return format;
  319. }
  320. export function formatMinute(seconds, number = true) {
  321. const time = parseInt(seconds || 0, 10);
  322. return number ? parseInt(time / 60, 10) : `${parseInt(time / 60, 10)}min`;
  323. }
  324. export function formatSeconds(seconds, rand = false) {
  325. const time = parseInt(seconds || 0, 10);
  326. if (time < 60) {
  327. return `${time}s`;
  328. }
  329. if (time >= 60 && time < 3600) {
  330. return `${parseInt(time / 60, 10)}min${rand ? '' : formatSeconds(time % 60)}`;
  331. }
  332. return `${parseInt(time / 3600, 10)}hour${rand ? '' : formatSeconds(time % 3600)}`;
  333. }
  334. export function formatPercent(child, mother, number = true) {
  335. if (!mother || !child) return number ? 0 : '0%';
  336. return number ? Math.floor((child * 100) / mother) : `${Math.floor((child * 100) / mother)}%`;
  337. }
  338. export function formatTreeData(list, key = 'id', title = 'title', index = 'parent_id') {
  339. const map = getMap(list, key);
  340. const result = [];
  341. list.forEach(row => {
  342. row.children = [];
  343. row.title = row[title];
  344. if (!row.key) row.key = `${row[key]}`;
  345. row.value = row[key];
  346. });
  347. list.forEach(row => {
  348. if (row[index] && map[row[index]]) {
  349. if (!map[row[index]].children) map[row[index]].children = [];
  350. map[row[index]].children.push(row);
  351. } else {
  352. result.push(row);
  353. }
  354. });
  355. return result;
  356. }
  357. export function flattenObject(ob, prefix = '', force = false) {
  358. const toReturn = {};
  359. if (prefix) prefix = `${prefix}.`;
  360. Object.keys(ob).forEach(i => {
  361. if (typeof ob[i] === 'object' && ob[i] !== null && !ob[i].length) {
  362. const flatObject = flattenObject(ob[i]);
  363. Object.keys(flatObject).forEach(x => {
  364. toReturn[`${prefix}${i}.${x}`] = flatObject[x];
  365. });
  366. } else if (force && ob[i].length) {
  367. ob[i].forEach((row, index) => {
  368. const flatObject = flattenObject(row);
  369. Object.keys(flatObject).forEach(x => {
  370. toReturn[`${prefix}${i}.${index}.${x}`] = flatObject[x];
  371. });
  372. });
  373. } else {
  374. toReturn[`${prefix}${i}`] = ob[i];
  375. }
  376. });
  377. return toReturn;
  378. }
  379. function _formatMoney(s, n) {
  380. if (!s) s = 0;
  381. n = n > 0 && n <= 20 ? n : 2;
  382. s = `${parseFloat(`${s}`.replace(/[^\d.-]/g, '')).toFixed(n)}`;
  383. const l = s
  384. .split('.')[0]
  385. .split('')
  386. .reverse();
  387. const r = s.split('.')[1];
  388. let t = '';
  389. for (let i = 0; i < l.length; i += 1) {
  390. t += l[i] + ((i + 1) % 3 === 0 && i + 1 !== l.length ? ',' : '');
  391. }
  392. return `${t
  393. .split('')
  394. .reverse()
  395. .join('')}.${r}`;
  396. }
  397. export function formatMoney(price) {
  398. if (typeof price === 'object') {
  399. return `${price.symbol} ${_formatMoney(price.value, 2)}`;
  400. }
  401. return `${_formatMoney(price, 2)}`;
  402. }
  403. export function bindTags(targetList, field, render, def, notFound) {
  404. let index = -1;
  405. targetList.forEach((row, i) => {
  406. if (row.key === field) index = i;
  407. });
  408. targetList[index].notFoundContent = notFound;
  409. targetList[index].select = (def || []).map(row => {
  410. return render(row);
  411. });
  412. }
  413. export function bindSearch(targetList, field, Component, listFunc, render, def, notFound = null) {
  414. let index = -1;
  415. targetList.forEach((row, i) => {
  416. if (row.key === field) index = i;
  417. });
  418. const key = `lastFetchId${field}${index}${generateUUID(4)}`;
  419. if (!Component[key]) Component[key] = 0;
  420. const searchFunc = data => {
  421. Component[key] += 1;
  422. const fetchId = Component[key];
  423. targetList[index].loading = true;
  424. Component.setState({ fetching: true });
  425. listFunc(data).then(result => {
  426. if (fetchId !== Component[key]) {
  427. // for fetch callback order
  428. return;
  429. }
  430. targetList[index].select = (result.list || result || []).map(row => {
  431. return render(row);
  432. });
  433. targetList[index].loading = false;
  434. Component.setState({ fetching: false });
  435. });
  436. };
  437. const item = {
  438. showSearch: true,
  439. showArrow: true,
  440. filterOption: false,
  441. onSearch: keyword => {
  442. searchFunc({ page: 1, size: 5, keyword });
  443. },
  444. notFoundContent: notFound,
  445. };
  446. targetList[index] = Object.assign(targetList[index], item);
  447. if (def) {
  448. if (targetList[index].type === 'multiple' || targetList[index].mode === 'multiple') {
  449. searchFunc({ ids: def, page: 1, size: def.length });
  450. } else {
  451. searchFunc({ ids: [def], page: 1, size: 1 });
  452. }
  453. } else {
  454. item.onSearch();
  455. }
  456. }
  457. export function generateSearch(field, props, Component, listFunc, render, def, notFound = null) {
  458. const key = `lastFetchId${field}${generateUUID(4)}`;
  459. if (!Component[key]) Component[key] = 0;
  460. let item = {
  461. showSearch: true,
  462. showArrow: true,
  463. filterOption: false,
  464. notFoundContent: notFound,
  465. };
  466. item = Object.assign(props || {}, item);
  467. const searchFunc = data => {
  468. Component[key] += 1;
  469. const fetchId = Component[key];
  470. item.loading = true;
  471. Component.setState({ [field]: item, fetching: true });
  472. listFunc(data).then(result => {
  473. if (fetchId !== Component[key]) {
  474. // for fetch callback order
  475. return;
  476. }
  477. item.select = result.list.map(row => {
  478. return render(row);
  479. });
  480. item.loading = false;
  481. Component.setState({ [field]: item, fetching: false });
  482. });
  483. };
  484. item.onSearch = keyword => {
  485. searchFunc({ page: 1, size: 5, keyword });
  486. };
  487. if (def) {
  488. if (item.mode === 'multiple' || item.type === 'multiple') {
  489. searchFunc({ ids: def, page: 1, size: def.length });
  490. } else {
  491. searchFunc({ ids: [def], page: 1, size: 1 });
  492. }
  493. } else {
  494. item.onSearch();
  495. }
  496. Component.setState({ [field]: item });
  497. }
  498. export function getHtmlText(text) {
  499. text = text.replace(new RegExp(/\r\n/, 'g'), '\r').replace(new RegExp(/\n/, 'g'), '\r');
  500. let html = '';
  501. text.split('\r').forEach(item => {
  502. item.split(' ').forEach(t => {
  503. html += `< i uuid = "${generateUUID(4)}" > ${t}</i > `;
  504. });
  505. html += '<br/>';
  506. });
  507. return html;
  508. }
  509. export function getSimpleText(html) {
  510. let text = html.replace(new RegExp('<br/>', 'g'), '\n\r');
  511. text = text.replace(new RegExp('<.+?>', 'g'), '');
  512. return text;
  513. }
  514. export function randomList(length) {
  515. const list = [];
  516. for (let i = 0; i < length; i += 1) {
  517. list.push(i);
  518. }
  519. for (let i = 0; i < length; i += 1) {
  520. const o = Math.floor(Math.random() * length);
  521. const tmp = list[o];
  522. list[o] = list[i];
  523. list[i] = tmp;
  524. }
  525. return list;
  526. }
  527. export function sortListWithOrder(target, order) {
  528. const list = [];
  529. order.forEach(t => {
  530. list.push(target[t]);
  531. });
  532. return list;
  533. }
  534. export function resortListWithOrder(target, order) {
  535. const list = [];
  536. for (let i = 0; i < order.length; i += 1) {
  537. list.push('');
  538. }
  539. order.forEach((t, i) => {
  540. list[t] = target[i];
  541. });
  542. return list;
  543. }
  544. // 下划线转换驼峰
  545. export function toHump(name) {
  546. return name.replace(/_(\w)/g, (all, letter) => {
  547. return letter.toUpperCase();
  548. });
  549. }
  550. // 驼峰转换下划线
  551. export function toLine(name) {
  552. return name.replace(/([A-Z])/g, '_$1').toLowerCase();
  553. }
  554. export function formatMonth(days, number = true) {
  555. return number ? parseInt(days / 30, 10) : `${parseInt(days / 30, 10)}个月`;
  556. }
  557. export function timeRange(timerange) {
  558. let startTime = null;
  559. let endTime = null;
  560. switch (timerange) {
  561. case 'week':
  562. endTime = new Date();
  563. endTime.setHours(0, 0, 0, 0);
  564. endTime.setDate(endTime.getDate() + 1);
  565. startTime = new Date(endTime.getTime() - 86400000 * 7);
  566. break;
  567. case 'month':
  568. endTime = new Date();
  569. endTime.setHours(0, 0, 0, 0);
  570. endTime.setDate(endTime.getDate() + 1);
  571. startTime = new Date();
  572. startTime.setHours(0, 0, 0, 0);
  573. startTime.setMonth(startTime.getMonth() - 1);
  574. break;
  575. case 'month3':
  576. endTime = new Date();
  577. endTime.setHours(0, 0, 0, 0);
  578. endTime.setDate(endTime.getDate() + 1);
  579. startTime = new Date();
  580. startTime.setHours(0, 0, 0, 0);
  581. startTime.setMonth(startTime.getMonth() - 3);
  582. break;
  583. case 'today':
  584. startTime = new Date();
  585. startTime.setHours(0, 0, 0, 0);
  586. endTime = new Date(startTime.getTime() + 86400000);
  587. break;
  588. case 'all':
  589. default:
  590. return [null, null];
  591. }
  592. return [formatDate(startTime, 'YYYY-MM-DD'), formatDate(endTime, 'YYYY-MM-DD')];
  593. }