tool.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import { cloneDeep } from 'lodash';
  2. import { useUserStore } from '@/store';
  3. export const extractFileName = (str) => {
  4. if (/filename=([^;\s]*)/gi.test(str)) {
  5. return decodeURIComponent(RegExp.$1);
  6. }
  7. return '下载文件';
  8. };
  9. const typeColor = (type = 'default') => {
  10. let color = '';
  11. switch (type) {
  12. case 'default':
  13. color = '#35495E';
  14. break;
  15. case 'primary':
  16. color = '#3488ff';
  17. break;
  18. case 'success':
  19. color = '#43B883';
  20. break;
  21. case 'warning':
  22. color = '#e6a23c';
  23. break;
  24. case 'danger':
  25. color = '#f56c6c';
  26. break;
  27. default:
  28. break;
  29. }
  30. return color;
  31. };
  32. /**
  33. * LocalStorage
  34. */
  35. export const local = {
  36. set(table, settings) {
  37. const _set = JSON.stringify(settings);
  38. return localStorage.setItem('sop_' + table, _set);
  39. },
  40. get(table) {
  41. let data = localStorage.getItem('sop_' + table);
  42. try {
  43. data = JSON.parse(data);
  44. } catch (err) {
  45. return null;
  46. }
  47. return data;
  48. },
  49. remove(table) {
  50. return localStorage.removeItem('sop_' + table);
  51. },
  52. clear() {
  53. return localStorage.clear();
  54. },
  55. };
  56. /**
  57. * SessionStorage
  58. */
  59. export const session = {
  60. set(table, settings) {
  61. const _set = JSON.stringify(settings);
  62. return sessionStorage.setItem('sop_' + table, _set);
  63. },
  64. get(table) {
  65. let data = sessionStorage.getItem('sop_' + table);
  66. try {
  67. data = JSON.parse(data);
  68. } catch (err) {
  69. return null;
  70. }
  71. return data;
  72. },
  73. remove(table) {
  74. return sessionStorage.removeItem('sop_' + table);
  75. },
  76. clear() {
  77. return sessionStorage.clear();
  78. },
  79. };
  80. export const clear = () => {
  81. localStorage.clear();
  82. sessionStorage.clear();
  83. };
  84. /**
  85. * CookieStorage
  86. */
  87. export const cookie = {
  88. set(name, value, config = {}) {
  89. const cfg = {
  90. expires: null,
  91. path: null,
  92. domain: null,
  93. secure: false,
  94. httpOnly: false,
  95. ...config,
  96. };
  97. let cookieStr = `${name}=${escape(value)}`;
  98. if (cfg.expires) {
  99. const exp = new Date();
  100. exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000);
  101. cookieStr += `;expires=${exp.toGMTString()}`;
  102. }
  103. if (cfg.path) {
  104. cookieStr += `;path=${cfg.path}`;
  105. }
  106. if (cfg.domain) {
  107. cookieStr += `;domain=${cfg.domain}`;
  108. }
  109. document.cookie = cookieStr;
  110. },
  111. get(name) {
  112. const arr = document.cookie.match(new RegExp(`(^| )${name}=([^;]*)(;|$)`));
  113. if (arr != null) {
  114. return unescape(arr[2]);
  115. }
  116. return null;
  117. },
  118. remove(name) {
  119. const exp = new Date();
  120. exp.setTime(exp.getTime() - 1);
  121. document.cookie = `${name}=;expires=${exp.toGMTString()}`;
  122. },
  123. };
  124. /* Fullscreen */
  125. export const screen = (element) => {
  126. const isFull = !!(
  127. document.webkitIsFullScreen ||
  128. document.mozFullScreen ||
  129. document.msFullscreenElement ||
  130. document.fullscreenElement
  131. );
  132. if (isFull) {
  133. if (document.exitFullscreen) {
  134. document.exitFullscreen();
  135. } else if (document.msExitFullscreen) {
  136. document.msExitFullscreen();
  137. } else if (document.mozCancelFullScreen) {
  138. document.mozCancelFullScreen();
  139. } else if (document.webkitExitFullscreen) {
  140. document.webkitExitFullscreen();
  141. }
  142. } else if (element.requestFullscreen) {
  143. element.requestFullscreen();
  144. } else if (element.msRequestFullscreen) {
  145. element.msRequestFullscreen();
  146. } else if (element.mozRequestFullScreen) {
  147. element.mozRequestFullScreen();
  148. } else if (element.webkitRequestFullscreen) {
  149. element.webkitRequestFullscreen();
  150. }
  151. };
  152. /* 复制对象 */
  153. export const objCopy = (obj) => {
  154. if (obj === undefined) {
  155. return undefined;
  156. }
  157. return JSON.parse(JSON.stringify(obj));
  158. };
  159. export const generateId = function () {
  160. return Math.floor(
  161. Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000
  162. );
  163. };
  164. /* 日期格式化 */
  165. export const dateFormat = (
  166. date,
  167. fmt = 'yyyy-MM-dd hh:mm:ss',
  168. isDefault = '-'
  169. ) => {
  170. if (!date) {
  171. return '-';
  172. }
  173. if (date.toString().length === 10) {
  174. date *= 1000;
  175. }
  176. date = new Date(date);
  177. if (date.valueOf() < 1) {
  178. return isDefault;
  179. }
  180. const o = {
  181. 'M+': date.getMonth() + 1, // 月份
  182. 'd+': date.getDate(), // 日
  183. 'h+': date.getHours(), // 小时
  184. 'm+': date.getMinutes(), // 分
  185. 's+': date.getSeconds(), // 秒
  186. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  187. 'S': date.getMilliseconds(), // 毫秒
  188. };
  189. if (/(y+)/.test(fmt)) {
  190. fmt = fmt.replace(
  191. RegExp.$1,
  192. `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
  193. );
  194. }
  195. for (const k in o) {
  196. if (new RegExp(`(${k})`).test(fmt)) {
  197. fmt = fmt.replace(
  198. RegExp.$1,
  199. RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
  200. );
  201. }
  202. }
  203. return fmt;
  204. };
  205. /* 千分符 */
  206. export const groupSeparator = (num) => {
  207. num += '';
  208. if (!num.includes('.')) {
  209. num += '.';
  210. }
  211. return num
  212. .replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
  213. return `${$1},`;
  214. })
  215. .replace(/\.$/, '');
  216. };
  217. export const capsule = (title, info, type = 'primary') => {
  218. console.log(
  219. `%c ${title} %c ${info} %c`,
  220. 'background:#35495E; padding: 1px; border-radius: 3px 0 0 3px; color: #fff;',
  221. `background:${typeColor(
  222. type
  223. )}; padding: 1px; border-radius: 0 3px 3px 0; color: #fff;`,
  224. 'background:transparent'
  225. );
  226. };
  227. export const download = (res, downName = '') => {
  228. const aLink = document.createElement('a');
  229. let fileName = downName;
  230. let blob = res; // 第三方请求返回blob对象
  231. // 通过后端接口返回
  232. if (res.headers && res.data) {
  233. blob = new Blob([res.data], {
  234. type: res.headers['content-type'].replace(';charset=utf8', ''),
  235. });
  236. if (!downName) {
  237. fileName = extractFileName(res.headers?.['content-disposition']);
  238. }
  239. }
  240. aLink.href = URL.createObjectURL(blob);
  241. // 设置下载文件名称
  242. aLink.setAttribute('download', fileName);
  243. document.body.appendChild(aLink);
  244. aLink.click();
  245. document.body.removeChild(aLink);
  246. URL.revokeObjectURL(aLink.href);
  247. };
  248. /**
  249. * 下载url
  250. * @param {String} url 文件下载地址
  251. * @param {String}} filename 文件名
  252. */
  253. export function downloadByUrl(url, filename) {
  254. const tempLink = document.createElement('a');
  255. tempLink.style.display = 'none';
  256. tempLink.href = url;
  257. const fileName = filename || url.split('/').pop().split('?')[0];
  258. tempLink.setAttribute('download', fileName);
  259. if (tempLink.download === 'undefined') {
  260. tempLink.setAttribute('target', '_blank');
  261. }
  262. document.body.appendChild(tempLink);
  263. tempLink.click();
  264. document.body.removeChild(tempLink);
  265. window.URL.revokeObjectURL(url);
  266. }
  267. /**
  268. * 对象转url参数
  269. * @param {*} data
  270. * @param {*} isPrefix
  271. */
  272. export const httpBuild = (data, isPrefix = false) => {
  273. const prefix = isPrefix ? '?' : '';
  274. const _result = [];
  275. for (const key in data) {
  276. const value = data[key];
  277. // 去掉为空的参数
  278. if (['', undefined, null].includes(value)) {
  279. continue;
  280. }
  281. if (value.constructor === Array) {
  282. value.forEach((_value) => {
  283. _result.push(
  284. `${encodeURIComponent(key)}[]=${encodeURIComponent(_value)}`
  285. );
  286. });
  287. } else {
  288. _result.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
  289. }
  290. }
  291. return _result.length ? prefix + _result.join('&') : '';
  292. };
  293. export const getRequestParams = (url) => {
  294. const theRequest = new Object();
  295. if (url.indexOf('?') != -1) {
  296. const params = url.split('?')[1].split('&');
  297. for (let i = 0; i < params.length; i++) {
  298. const param = params[i].split('=');
  299. theRequest[param[0]] = decodeURIComponent(param[1]);
  300. }
  301. }
  302. return theRequest;
  303. };
  304. export const getTreeList = (oldDataList, sortField = '') => {
  305. if (!Array.isArray(oldDataList)) {
  306. throw new TypeError(`${oldDataList}不是数组`);
  307. }
  308. const dataList = cloneDeep(oldDataList);
  309. const formatObj = dataList.reduce((pre, cur) => {
  310. return { ...pre, [cur.id]: cur };
  311. }, {});
  312. const sortArray = sortField
  313. ? dataList.sort((a, b) => a.sort - b.sort)
  314. : dataList;
  315. const formatArray = sortArray.reduce((arr, cur) => {
  316. const pid = cur.parentId ? cur.parentId : '-1';
  317. const parent = formatObj[pid];
  318. if (parent) {
  319. parent.children ? parent.children.push(cur) : (parent.children = [cur]);
  320. } else {
  321. arr.push(cur);
  322. }
  323. return arr;
  324. }, []);
  325. return formatArray;
  326. };
  327. /**
  328. * 将一维数组转换为二维数组
  329. * @param {*} arr
  330. * @returns
  331. */
  332. export const toSecondFloorArray = (arr) => {
  333. if (!Array.isArray(arr)) {
  334. throw new TypeError(`${arr}不是数组`);
  335. }
  336. const newArr = arr.reduce((initArr, item, index) => {
  337. if (index % 2 == 0) {
  338. initArr.push([item]);
  339. } else {
  340. initArr[initArr.length - 1].push(item);
  341. }
  342. return initArr;
  343. }, []);
  344. return newArr;
  345. };
  346. /**
  347. * 字典数据转成option list
  348. * @param {Object} data 字典数据
  349. * @returns list
  350. */
  351. export const dictToOptionList = (data) => {
  352. return Object.keys(data).map((k) => {
  353. const kstr = typeof k === 'number' ? k : k + '';
  354. return { value: kstr, label: data[k] };
  355. });
  356. };
  357. /**
  358. * 判断用户的权限集里有没有
  359. * @param {*} key
  360. * @returns
  361. */
  362. export const hasPerm = (key) => {
  363. const userStore = useUserStore();
  364. return userStore.finePermissionIds.includes(key);
  365. };
  366. /**
  367. * 获取随机code,默认获取16位
  368. * @param {Number} len 推荐8的倍数
  369. *
  370. */
  371. export function randomCode(len = 16) {
  372. if (len <= 0) return;
  373. let steps = Math.ceil(len / 8);
  374. let stepNums = [];
  375. for (let i = 0; i < steps; i++) {
  376. let ranNum = Math.random().toString(32).slice(-8);
  377. stepNums.push(ranNum);
  378. }
  379. return stepNums.join('');
  380. }
  381. /**
  382. * 判断对象类型
  383. * @param {*} obj 对象
  384. */
  385. export function objTypeOf(obj) {
  386. const toString = Object.prototype.toString;
  387. const map = {
  388. '[object Boolean]': 'boolean',
  389. '[object Number]': 'number',
  390. '[object String]': 'string',
  391. '[object Function]': 'function',
  392. '[object Array]': 'array',
  393. '[object Date]': 'date',
  394. '[object RegExp]': 'regExp',
  395. '[object Undefined]': 'undefined',
  396. '[object Null]': 'null',
  397. '[object Object]': 'object',
  398. '[object Blob]': 'blob',
  399. };
  400. return map[toString.call(obj)];
  401. }
  402. /**
  403. * 获取时间长度文字
  404. * @param {Number} timeNumber 时间数值,单位:毫秒
  405. */
  406. export function timeNumberToText(timeNumber) {
  407. const DAY_TIME = 24 * 60 * 60 * 1000;
  408. const HOUR_TIME = 60 * 60 * 1000;
  409. const MINUTE_TIME = 60 * 1000;
  410. const SECOND_TIME = 1000;
  411. let [day, hour, minute, second] = [0, 0, 0, 0];
  412. let residueTime = timeNumber;
  413. if (residueTime >= DAY_TIME) {
  414. day = Math.floor(residueTime / DAY_TIME);
  415. residueTime -= day * DAY_TIME;
  416. day += '天';
  417. }
  418. if (residueTime >= HOUR_TIME) {
  419. hour = Math.floor(residueTime / HOUR_TIME);
  420. residueTime -= hour * HOUR_TIME;
  421. hour += '小时';
  422. }
  423. if (residueTime >= MINUTE_TIME) {
  424. minute = Math.floor(residueTime / MINUTE_TIME);
  425. residueTime -= minute * MINUTE_TIME;
  426. minute += '分钟';
  427. }
  428. if (residueTime >= SECOND_TIME) {
  429. second = Math.round(residueTime / SECOND_TIME);
  430. second += '秒';
  431. }
  432. return [day, hour, minute, second].filter((item) => !!item).join('');
  433. }