tool.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import { cloneDeep } from 'lodash';
  2. export const extractFileName = (str) => {
  3. if (/filename=([^;\s]*)/gi.test(str)) {
  4. return decodeURIComponent(RegExp.$1);
  5. }
  6. return '下载文件';
  7. };
  8. const typeColor = (type = 'default') => {
  9. let color = '';
  10. switch (type) {
  11. case 'default':
  12. color = '#35495E';
  13. break;
  14. case 'primary':
  15. color = '#3488ff';
  16. break;
  17. case 'success':
  18. color = '#43B883';
  19. break;
  20. case 'warning':
  21. color = '#e6a23c';
  22. break;
  23. case 'danger':
  24. color = '#f56c6c';
  25. break;
  26. default:
  27. break;
  28. }
  29. return color;
  30. };
  31. /**
  32. * LocalStorage
  33. */
  34. export const local = {
  35. set(table, settings) {
  36. const _set = JSON.stringify(settings);
  37. return localStorage.setItem('sop_' + table, _set);
  38. },
  39. get(table) {
  40. let data = localStorage.getItem('sop_' + table);
  41. try {
  42. data = JSON.parse(data);
  43. } catch (err) {
  44. return null;
  45. }
  46. return data;
  47. },
  48. remove(table) {
  49. return localStorage.removeItem('sop_' + table);
  50. },
  51. clear() {
  52. return localStorage.clear();
  53. },
  54. };
  55. /**
  56. * SessionStorage
  57. */
  58. export const session = {
  59. set(table, settings) {
  60. const _set = JSON.stringify(settings);
  61. return sessionStorage.setItem('sop_' + table, _set);
  62. },
  63. get(table) {
  64. let data = sessionStorage.getItem('sop_' + table);
  65. try {
  66. data = JSON.parse(data);
  67. } catch (err) {
  68. return null;
  69. }
  70. return data;
  71. },
  72. remove(table) {
  73. return sessionStorage.removeItem('sop_' + table);
  74. },
  75. clear() {
  76. return sessionStorage.clear();
  77. },
  78. };
  79. export const clear = () => {
  80. localStorage.clear();
  81. sessionStorage.clear();
  82. };
  83. /**
  84. * CookieStorage
  85. */
  86. export const cookie = {
  87. set(name, value, config = {}) {
  88. const cfg = {
  89. expires: null,
  90. path: null,
  91. domain: null,
  92. secure: false,
  93. httpOnly: false,
  94. ...config,
  95. };
  96. let cookieStr = `${name}=${escape(value)}`;
  97. if (cfg.expires) {
  98. const exp = new Date();
  99. exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000);
  100. cookieStr += `;expires=${exp.toGMTString()}`;
  101. }
  102. if (cfg.path) {
  103. cookieStr += `;path=${cfg.path}`;
  104. }
  105. if (cfg.domain) {
  106. cookieStr += `;domain=${cfg.domain}`;
  107. }
  108. document.cookie = cookieStr;
  109. },
  110. get(name) {
  111. const arr = document.cookie.match(new RegExp(`(^| )${name}=([^;]*)(;|$)`));
  112. if (arr != null) {
  113. return unescape(arr[2]);
  114. }
  115. return null;
  116. },
  117. remove(name) {
  118. const exp = new Date();
  119. exp.setTime(exp.getTime() - 1);
  120. document.cookie = `${name}=;expires=${exp.toGMTString()}`;
  121. },
  122. };
  123. /* Fullscreen */
  124. export const screen = (element) => {
  125. const isFull = !!(
  126. document.webkitIsFullScreen ||
  127. document.mozFullScreen ||
  128. document.msFullscreenElement ||
  129. document.fullscreenElement
  130. );
  131. if (isFull) {
  132. if (document.exitFullscreen) {
  133. document.exitFullscreen();
  134. } else if (document.msExitFullscreen) {
  135. document.msExitFullscreen();
  136. } else if (document.mozCancelFullScreen) {
  137. document.mozCancelFullScreen();
  138. } else if (document.webkitExitFullscreen) {
  139. document.webkitExitFullscreen();
  140. }
  141. } else if (element.requestFullscreen) {
  142. element.requestFullscreen();
  143. } else if (element.msRequestFullscreen) {
  144. element.msRequestFullscreen();
  145. } else if (element.mozRequestFullScreen) {
  146. element.mozRequestFullScreen();
  147. } else if (element.webkitRequestFullscreen) {
  148. element.webkitRequestFullscreen();
  149. }
  150. };
  151. /* 复制对象 */
  152. export const objCopy = (obj) => {
  153. if (obj === undefined) {
  154. return undefined;
  155. }
  156. return JSON.parse(JSON.stringify(obj));
  157. };
  158. export const generateId = function () {
  159. return Math.floor(
  160. Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000
  161. );
  162. };
  163. /* 日期格式化 */
  164. export const dateFormat = (
  165. date,
  166. fmt = 'yyyy-MM-dd hh:mm:ss',
  167. isDefault = '-'
  168. ) => {
  169. if (date.toString().length === 10) {
  170. date *= 1000;
  171. }
  172. date = new Date(date);
  173. if (date.valueOf() < 1) {
  174. return isDefault;
  175. }
  176. const o = {
  177. 'M+': date.getMonth() + 1, // 月份
  178. 'd+': date.getDate(), // 日
  179. 'h+': date.getHours(), // 小时
  180. 'm+': date.getMinutes(), // 分
  181. 's+': date.getSeconds(), // 秒
  182. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  183. 'S': date.getMilliseconds(), // 毫秒
  184. };
  185. if (/(y+)/.test(fmt)) {
  186. fmt = fmt.replace(
  187. RegExp.$1,
  188. `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
  189. );
  190. }
  191. for (const k in o) {
  192. if (new RegExp(`(${k})`).test(fmt)) {
  193. fmt = fmt.replace(
  194. RegExp.$1,
  195. RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
  196. );
  197. }
  198. }
  199. return fmt;
  200. };
  201. /* 千分符 */
  202. export const groupSeparator = (num) => {
  203. num += '';
  204. if (!num.includes('.')) {
  205. num += '.';
  206. }
  207. return num
  208. .replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
  209. return `${$1},`;
  210. })
  211. .replace(/\.$/, '');
  212. };
  213. export const capsule = (title, info, type = 'primary') => {
  214. console.log(
  215. `%c ${title} %c ${info} %c`,
  216. 'background:#35495E; padding: 1px; border-radius: 3px 0 0 3px; color: #fff;',
  217. `background:${typeColor(
  218. type
  219. )}; padding: 1px; border-radius: 0 3px 3px 0; color: #fff;`,
  220. 'background:transparent'
  221. );
  222. };
  223. export const download = (res, downName = '') => {
  224. const aLink = document.createElement('a');
  225. let fileName = downName;
  226. let blob = res; // 第三方请求返回blob对象
  227. // 通过后端接口返回
  228. if (res.headers && res.data) {
  229. blob = new Blob([res.data], {
  230. type: res.headers['content-type'].replace(';charset=utf8', ''),
  231. });
  232. if (!downName) {
  233. fileName = extractFileName(res.headers?.['content-disposition']);
  234. }
  235. }
  236. aLink.href = URL.createObjectURL(blob);
  237. // 设置下载文件名称
  238. aLink.setAttribute('download', fileName);
  239. document.body.appendChild(aLink);
  240. aLink.click();
  241. document.body.removeChild(aLink);
  242. URL.revokeObjectURL(aLink.href);
  243. };
  244. /**
  245. * 对象转url参数
  246. * @param {*} data
  247. * @param {*} isPrefix
  248. */
  249. export const httpBuild = (data, isPrefix = false) => {
  250. const prefix = isPrefix ? '?' : '';
  251. const _result = [];
  252. for (const key in data) {
  253. const value = data[key];
  254. // 去掉为空的参数
  255. if (['', undefined, null].includes(value)) {
  256. continue;
  257. }
  258. if (value.constructor === Array) {
  259. value.forEach((_value) => {
  260. _result.push(
  261. `${encodeURIComponent(key)}[]=${encodeURIComponent(_value)}`
  262. );
  263. });
  264. } else {
  265. _result.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
  266. }
  267. }
  268. return _result.length ? prefix + _result.join('&') : '';
  269. };
  270. export const getRequestParams = (url) => {
  271. const theRequest = new Object();
  272. if (url.indexOf('?') != -1) {
  273. const params = url.split('?')[1].split('&');
  274. for (let i = 0; i < params.length; i++) {
  275. const param = params[i].split('=');
  276. theRequest[param[0]] = decodeURIComponent(param[1]);
  277. }
  278. }
  279. return theRequest;
  280. };
  281. export const getTreeList = (oldDataList, sortField = '') => {
  282. if (!Array.isArray(oldDataList)) {
  283. throw new TypeError(`${oldDataList}不是数组`);
  284. }
  285. const dataList = cloneDeep(oldDataList);
  286. const formatObj = dataList.reduce((pre, cur) => {
  287. return { ...pre, [cur.id]: cur };
  288. }, {});
  289. const sortArray = sortField
  290. ? dataList.sort((a, b) => a.sort - b.sort)
  291. : dataList;
  292. const formatArray = sortArray.reduce((arr, cur) => {
  293. const pid = cur.parentId ? cur.parentId : '-1';
  294. const parent = formatObj[pid];
  295. if (parent) {
  296. parent.children ? parent.children.push(cur) : (parent.children = [cur]);
  297. } else {
  298. arr.push(cur);
  299. }
  300. return arr;
  301. }, []);
  302. return formatArray;
  303. };
  304. /**
  305. * 将一维数组转换为二维数组
  306. * @param {*} arr
  307. * @returns
  308. */
  309. export const toSecondFloorArray = (arr) => {
  310. if (!Array.isArray(arr)) {
  311. throw new TypeError(`${arr}不是数组`);
  312. }
  313. const newArr = arr.reduce((initArr, item, index) => {
  314. if (index % 2 == 0) {
  315. initArr.push([item]);
  316. } else {
  317. initArr[initArr.length - 1].push(item);
  318. }
  319. return initArr;
  320. }, []);
  321. return newArr;
  322. };