tool.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import CryptoJS from "crypto-js";
  2. import CityLinkageJson from "@/components/ma-cityLinkage/lib/city.json";
  3. /**
  4. * 根据类型获取颜色
  5. */
  6. const typeColor = (type = "default") => {
  7. let color = "";
  8. switch (type) {
  9. case "default":
  10. color = "#35495E";
  11. break;
  12. case "primary":
  13. color = "#3488ff";
  14. break;
  15. case "success":
  16. color = "#43B883";
  17. break;
  18. case "warning":
  19. color = "#e6a23c";
  20. break;
  21. case "danger":
  22. color = "#f56c6c";
  23. break;
  24. default:
  25. break;
  26. }
  27. return color;
  28. };
  29. const tool = {};
  30. /**
  31. * LocalStorage
  32. */
  33. tool.local = {
  34. set(table, settings) {
  35. let _set = JSON.stringify(settings);
  36. return localStorage.setItem(table, _set);
  37. },
  38. get(table) {
  39. let data = localStorage.getItem(table);
  40. try {
  41. data = JSON.parse(data);
  42. } catch (err) {
  43. return null;
  44. }
  45. return data;
  46. },
  47. remove(table) {
  48. return localStorage.removeItem(table);
  49. },
  50. clear() {
  51. return localStorage.clear();
  52. },
  53. };
  54. /**
  55. * SessionStorage
  56. */
  57. tool.session = {
  58. set(table, settings) {
  59. let _set = JSON.stringify(settings);
  60. return sessionStorage.setItem(table, _set);
  61. },
  62. get(table) {
  63. let data = sessionStorage.getItem(table);
  64. try {
  65. data = JSON.parse(data);
  66. } catch (err) {
  67. return null;
  68. }
  69. return data;
  70. },
  71. remove(table) {
  72. return sessionStorage.removeItem(table);
  73. },
  74. clear() {
  75. return sessionStorage.clear();
  76. },
  77. };
  78. /**
  79. * CookieStorage
  80. */
  81. tool.cookie = {
  82. set(name, value, config = {}) {
  83. var cfg = {
  84. expires: null,
  85. path: null,
  86. domain: null,
  87. secure: false,
  88. httpOnly: false,
  89. ...config,
  90. };
  91. var cookieStr = `${name}=${escape(value)}`;
  92. if (cfg.expires) {
  93. var exp = new Date();
  94. exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000);
  95. cookieStr += `;expires=${exp.toGMTString()}`;
  96. }
  97. if (cfg.path) {
  98. cookieStr += `;path=${cfg.path}`;
  99. }
  100. if (cfg.domain) {
  101. cookieStr += `;domain=${cfg.domain}`;
  102. }
  103. document.cookie = cookieStr;
  104. },
  105. get(name) {
  106. var arr = document.cookie.match(
  107. new RegExp("(^| )" + name + "=([^;]*)(;|$)")
  108. );
  109. if (arr != null) {
  110. return unescape(arr[2]);
  111. } else {
  112. return null;
  113. }
  114. },
  115. remove(name) {
  116. var exp = new Date();
  117. exp.setTime(exp.getTime() - 1);
  118. document.cookie = `${name}=;expires=${exp.toGMTString()}`;
  119. },
  120. };
  121. /**
  122. * 全屏操作
  123. */
  124. tool.screen = (element) => {
  125. let 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 {
  142. 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. /**
  154. * 获取设备信息
  155. */
  156. tool.getDevice = function () {
  157. const hasTouchScreen =
  158. "ontouchstart" in window || navigator.maxTouchPoints > 0;
  159. const isSmallScreen = window.innerWidth < 768;
  160. if (hasTouchScreen && isSmallScreen) {
  161. return "mobile";
  162. } else {
  163. return "desktop";
  164. }
  165. };
  166. /**
  167. * 处理图片
  168. */
  169. tool.parseImage = (url) => {
  170. if (url === undefined) {
  171. return import.meta.env.VITE_APP_BASE + "not-image.png";
  172. }
  173. if (typeof url === "string" && url !== null) {
  174. return url;
  175. } else {
  176. if (url !== null) {
  177. return url[0];
  178. } else {
  179. return import.meta.env.VITE_APP_BASE + "not-image.png";
  180. }
  181. }
  182. };
  183. /**
  184. * 城市代码翻译成名称
  185. */
  186. tool.cityToCode = function (
  187. province,
  188. city = undefined,
  189. area = undefined,
  190. split = " / "
  191. ) {
  192. try {
  193. let provinceData = CityLinkageJson.filter(
  194. (item) => province == item.code
  195. )[0];
  196. if (!city) {
  197. return provinceData.name;
  198. }
  199. let cityData = provinceData.children.filter((item) => city == item.code)[0];
  200. if (!area) {
  201. return [provinceData.name, cityData.name].join(split);
  202. }
  203. let areaData = cityData.children.filter((item) => area == item.code)[0];
  204. return [provinceData.name, cityData.name, areaData.name].join(split);
  205. } catch (e) {
  206. return "";
  207. }
  208. };
  209. /**
  210. * 复制对象
  211. */
  212. tool.objCopy = (obj) => {
  213. if (obj === undefined) {
  214. return undefined;
  215. }
  216. return JSON.parse(JSON.stringify(obj));
  217. };
  218. /**
  219. * 生车随机id
  220. */
  221. tool.generateId = function () {
  222. return Math.floor(
  223. Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000
  224. );
  225. };
  226. /**
  227. * 日期格式化
  228. */
  229. tool.dateFormat = (date, fmt = "yyyy-MM-dd hh:mm:ss", isDefault = "-") => {
  230. if (date.toString().length == 10) {
  231. date = date * 1000;
  232. }
  233. date = new Date(date);
  234. if (date.valueOf() < 1) {
  235. return isDefault;
  236. }
  237. let o = {
  238. "M+": date.getMonth() + 1, //月份
  239. "d+": date.getDate(), //日
  240. "h+": date.getHours(), //小时
  241. "m+": date.getMinutes(), //分
  242. "s+": date.getSeconds(), //秒
  243. "q+": Math.floor((date.getMonth() + 3) / 3), //季度
  244. S: date.getMilliseconds(), //毫秒
  245. };
  246. if (/(y+)/.test(fmt)) {
  247. fmt = fmt.replace(
  248. RegExp.$1,
  249. (date.getFullYear() + "").substr(4 - RegExp.$1.length)
  250. );
  251. }
  252. for (let k in o) {
  253. if (new RegExp("(" + k + ")").test(fmt)) {
  254. fmt = fmt.replace(
  255. RegExp.$1,
  256. RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  257. );
  258. }
  259. }
  260. return fmt;
  261. };
  262. /**
  263. * 千分符
  264. */
  265. tool.groupSeparator = (num) => {
  266. num = num + "";
  267. if (!num.includes(".")) {
  268. num += ".";
  269. }
  270. return num
  271. .replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
  272. return $1 + ",";
  273. })
  274. .replace(/\.$/, "");
  275. };
  276. /**
  277. * md5加密
  278. */
  279. tool.md5 = (str) => {
  280. return CryptoJS.MD5(str).toString();
  281. };
  282. /**
  283. * Base64加密解密
  284. */
  285. tool.base64 = {
  286. encode(data) {
  287. return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data));
  288. },
  289. decode(cipher) {
  290. return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8);
  291. },
  292. };
  293. /**
  294. * AES加密解密
  295. */
  296. tool.aes = {
  297. encode(data, secretKey) {
  298. const result = CryptoJS.AES.encrypt(
  299. data,
  300. CryptoJS.enc.Utf8.parse(secretKey),
  301. {
  302. mode: CryptoJS.mode.ECB,
  303. padding: CryptoJS.pad.Pkcs7,
  304. }
  305. );
  306. return result.toString();
  307. },
  308. decode(cipher, secretKey) {
  309. const result = CryptoJS.AES.decrypt(
  310. cipher,
  311. CryptoJS.enc.Utf8.parse(secretKey),
  312. {
  313. mode: CryptoJS.mode.ECB,
  314. padding: CryptoJS.pad.Pkcs7,
  315. }
  316. );
  317. return CryptoJS.enc.Utf8.stringify(result);
  318. },
  319. };
  320. /**
  321. * 打印信息
  322. */
  323. tool.capsule = (title, info, type = "primary") => {
  324. console.log(
  325. `%c ${title} %c ${info} %c`,
  326. "background:#35495E; padding: 1px; border-radius: 3px 0 0 3px; color: #fff;",
  327. `background:${typeColor(
  328. type
  329. )}; padding: 1px; border-radius: 0 3px 3px 0; color: #fff;`,
  330. "background:transparent"
  331. );
  332. };
  333. /**
  334. * 文件大小单位处理
  335. */
  336. tool.formatSize = (size) => {
  337. if (typeof size == "undefined") {
  338. return "0";
  339. }
  340. let units = ["B", "KB", "MB", "GB", "TB", "PB"];
  341. let index = 0;
  342. for (let i = 0; size >= 1024 && i < 5; i++) {
  343. size /= 1024;
  344. index = i;
  345. }
  346. return Math.round(size, 2) + units[index];
  347. };
  348. /**
  349. * 下载资源
  350. */
  351. tool.download = (res, downName = "") => {
  352. const aLink = document.createElement("a");
  353. let fileName = downName;
  354. let blob = res; //第三方请求返回blob对象
  355. //通过后端接口返回
  356. if (res.headers && res.data) {
  357. blob = new Blob([res.data], {
  358. type: res.headers["content-type"].replace(";charset=utf8", ""),
  359. });
  360. if (!downName) {
  361. const contentDisposition = decodeURI(res.headers["content-disposition"]);
  362. const result = contentDisposition.match(/filename=\"(.+)/gi);
  363. fileName = result[0].replace(/filename=\"/gi, "");
  364. fileName = fileName.replace('"', "");
  365. }
  366. }
  367. aLink.href = URL.createObjectURL(blob);
  368. // 设置下载文件名称
  369. aLink.setAttribute("download", fileName);
  370. document.body.appendChild(aLink);
  371. aLink.click();
  372. document.body.removeChild(aLink);
  373. URL.revokeObjectURL(aLink.href);
  374. };
  375. /**
  376. * 对象转url参数
  377. * @param {*} data
  378. * @param {*} isPrefix
  379. */
  380. tool.httpBuild = (data, isPrefix = false) => {
  381. let prefix = isPrefix ? "?" : "";
  382. let _result = [];
  383. for (let key in data) {
  384. let value = data[key];
  385. // 去掉为空的参数
  386. if (["", undefined, null].includes(value)) {
  387. continue;
  388. }
  389. if (value.constructor === Array) {
  390. value.forEach((_value) => {
  391. _result.push(
  392. encodeURIComponent(key) + "[]=" + encodeURIComponent(_value)
  393. );
  394. });
  395. } else {
  396. _result.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
  397. }
  398. }
  399. return _result.length ? prefix + _result.join("&") : "";
  400. };
  401. /**
  402. * 获取URL请求参数
  403. */
  404. tool.getRequestParams = (url) => {
  405. const theRequest = new Object();
  406. if (url.indexOf("?") != -1) {
  407. const params = url.split("?")[1].split("&");
  408. for (let i = 0; i < params.length; i++) {
  409. const param = params[i].split("=");
  410. theRequest[param[0]] = decodeURIComponent(param[1]);
  411. }
  412. }
  413. return theRequest;
  414. };
  415. tool.attachUrl = (path) => {
  416. // 非完整url地址在此处理
  417. return path;
  418. };
  419. tool.viewImage = (path) => {
  420. // 非完整url地址在此处理
  421. return path;
  422. };
  423. tool.showFile = (path) => {
  424. // 非完整url地址在此处理
  425. return path;
  426. };
  427. /**
  428. * 获取token
  429. */
  430. tool.getToken = () => {
  431. return tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX);
  432. };
  433. /**
  434. * 转Unix时间戳
  435. */
  436. tool.toUnixTime = (date) => {
  437. return Math.floor(new Date(date).getTime() / 1000);
  438. };
  439. /**
  440. * 通过value获取颜色
  441. */
  442. tool.getColor = (value, data, colors = []) => {
  443. if (!data) {
  444. return "";
  445. }
  446. if (colors && colors.length > 0) {
  447. const index = data.findIndex((item) => item.value == value);
  448. return colors[index] ?? "";
  449. } else {
  450. const item = data.find((item) => item.value == value);
  451. return item?.color ?? "";
  452. }
  453. };
  454. /**
  455. * 通过value获取label
  456. */
  457. tool.getLabel = (value, data) => {
  458. if (!data) {
  459. return "";
  460. }
  461. const item = data.find((item) => item.value == value);
  462. return item?.label ?? "";
  463. };
  464. /**
  465. * 复制文本到剪贴板
  466. */
  467. tool.copy = (text) => {
  468. if (navigator.clipboard && window.isSecureContext) {
  469. // 现代浏览器支持 navigator.clipboard API
  470. return navigator.clipboard.writeText(text);
  471. } else {
  472. // 兼容旧浏览器
  473. const textArea = document.createElement("textarea");
  474. textArea.value = text;
  475. textArea.style.position = "fixed";
  476. textArea.style.left = "-999999px";
  477. textArea.style.top = "-999999px";
  478. document.body.appendChild(textArea);
  479. textArea.focus();
  480. textArea.select();
  481. return new Promise((resolve, reject) => {
  482. if (document.execCommand("copy")) {
  483. resolve();
  484. } else {
  485. reject();
  486. }
  487. document.body.removeChild(textArea);
  488. });
  489. }
  490. };
  491. export default tool;