util.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. const config = require('./config.js');
  2. let setIntervalKey;
  3. function formatNumber(n) {
  4. n = n.toString()
  5. return n[1] ? n : '0' + n
  6. }
  7. var util = {
  8. formatTime: function(date) {
  9. var year = date.getFullYear()
  10. var month = date.getMonth() + 1
  11. var day = date.getDate()
  12. var hour = date.getHours()
  13. var minute = date.getMinutes()
  14. var second = date.getSeconds()
  15. return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber)
  16. .join(
  17. ':')
  18. },
  19. formatCNTime: function(val) {
  20. const year = val.getFullYear();
  21. const month = val.getMonth() + 1;
  22. const day = val.getDate();
  23. const hour = val.getHours();
  24. const minute = val.getMinutes();
  25. const second = val.getSeconds();
  26. return year + '年' + (month > 9 ? month : '0' + month) + '月' + day + '日' + hour + '时' + (minute > 9 ?
  27. minute : '0' +
  28. minute) + '分' + second + '秒';
  29. },
  30. formatCNTime1: function(val) {
  31. const year = val.getFullYear();
  32. const month = val.getMonth() + 1;
  33. const day = val.getDate();
  34. const hour = val.getHours();
  35. const minute = val.getMinutes();
  36. const second = val.getSeconds();
  37. return year + '年' + (month > 9 ? month : '0' + month) + '月' + (day > 9 ? day : '0' + day) + '日';
  38. },
  39. buttonClicked(self, time) {
  40. self.buttonClicked = false;
  41. setTimeout(function() {
  42. self.buttonClicked = true;
  43. }, time)
  44. },
  45. formatTodayTime: function(val) {
  46. if (typeof val !== 'object') {
  47. console.log('时间格式不对,不予转换')
  48. return val
  49. }
  50. const year = val.getFullYear();
  51. const month = val.getMonth() + 1;
  52. const day = val.getDate();
  53. const hour = val.getHours();
  54. const minute = val.getMinutes();
  55. const second = val.getSeconds();
  56. if (month == new Date().getMonth() + 1 && day + 1 == new Date().getDate()) {
  57. return '昨天' + hour + ':' + (minute > 9 ? minute : '0' + minute);
  58. } else if (month == new Date().getMonth() + 1 && day == new Date().getDate()) {
  59. return hour + ':' + (minute > 9 ? minute : '0' + minute) + ':' + (second > 9 ? second : '0' +
  60. second);
  61. } else {
  62. return year + '-' + (month > 9 ? month : '0' + month) + '-' + (day > 9 ? day : '0' + day) + ' ' +
  63. hour + ':' + (
  64. minute > 9 ? minute : '0' + minute) + ':' + (second > 9 ? second : '0' + second);
  65. }
  66. },
  67. formatMinuteTime: function(val) {
  68. const year = val.getFullYear();
  69. const month = val.getMonth() + 1;
  70. const day = val.getDate();
  71. const hour = val.getHours();
  72. const minute = val.getMinutes();
  73. const second = val.getSeconds();
  74. return year + '.' + (month > 9 ? month : '0' + month) + '.' + (day > 9 ? day : '0' + day) + ' ' + hour +
  75. ':' + (
  76. minute > 9 ? minute : '0' + minute)
  77. },
  78. formatSucTime: function(val) {
  79. const year = val.getFullYear();
  80. const month = val.getMonth() + 1;
  81. const day = val.getDate();
  82. const hour = val.getHours();
  83. const minute = val.getMinutes();
  84. if (month == new Date().getMonth() + 1 && day + 1 == new Date().getDate()) {
  85. return '昨天' + hour + ':' + (minute > 9 ? minute : '0' + minute);
  86. } else if (month == new Date().getMonth() + 1 && day == new Date().getDate()) {
  87. return hour + ':' + (minute > 9 ? minute : '0' + minute);
  88. } else {
  89. return year + '-' + (month > 9 ? month : '0' + month) + '-' + day + ' ' + hour + ':' + (minute > 9 ?
  90. minute : '0' +
  91. minute);
  92. }
  93. },
  94. //此时此刻日期转化
  95. timesData: function(timestamp) {
  96. var date = new Date(timestamp);
  97. var Y = date.getFullYear() + '/';
  98. var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
  99. var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
  100. // var h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
  101. // var m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes());
  102. return Y + M + D;
  103. },
  104. //此时此刻日期转化格式
  105. dateFormat: function(timestamp) {
  106. var date = new Date(timestamp);
  107. var Y = date.getFullYear() + '年';
  108. var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
  109. var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日 ';
  110. var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
  111. var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
  112. var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
  113. return Y + M + D + h + m + s;
  114. },
  115. //此时此刻日期转化格式
  116. dateFormats: function(timestamp) {
  117. var date = new Date(timestamp);
  118. var Y = date.getFullYear() + '年';
  119. var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
  120. var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日 ';
  121. return Y + M + D;
  122. },
  123. //此时此刻时间转化
  124. timestampToTime: function(timestamp) {
  125. var date = new Date(timestamp);
  126. var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
  127. var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
  128. return h + m;
  129. },
  130. formatDate: function(date, fmt) {
  131. if (/(y+)/.test(fmt)) {
  132. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  133. }
  134. let o = {
  135. 'M+': date.getMonth() + 1,
  136. 'd+': date.getDate(),
  137. 'h+': date.getHours(),
  138. 'm+': date.getMinutes(),
  139. 's+': date.getSeconds()
  140. }
  141. for (let k in o) {
  142. if (new RegExp(`(${k})`).test(fmt)) {
  143. let str = o[k] + ''
  144. fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str))
  145. }
  146. }
  147. return fmt
  148. },
  149. padLeftZero: function(str) {
  150. return ('00' + str).substr(str.length)
  151. },
  152. hexToRgba(hex, opacity) {
  153. if (!hex || !opacity) {
  154. return hex
  155. }
  156. var values;
  157. let RGBA;
  158. if (hex.includes('#') && hex.length == 7) {
  159. RGBA = "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," +
  160. parseInt("0x" + hex.slice(5, 7)) + "," + opacity + ")";
  161. } else if (hex.includes('rgb(')) {
  162. values = hex
  163. .replace(/rgb?\(/, '')
  164. .replace(/\)/, '')
  165. .replace(/[\s+]/g, '')
  166. .split(',')
  167. return `rgba(${values[0]},${values[1]},${values[2]},${opacity})`
  168. } else if (hex.includes('rgba(')) {
  169. values = hex
  170. .replace(/rgba?\(/, '')
  171. .replace(/\)/, '')
  172. .replace(/[\s+]/g, '')
  173. .split(',')
  174. return `rgba(${values[0]},${values[1]},${values[2]},${opacity})`
  175. } else {
  176. return hex
  177. }
  178. return RGBA
  179. },
  180. deepEqual(obj1, obj2) {
  181. if (obj1 === obj2) {
  182. return true; // 引用相同或都为 null
  183. }
  184. if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
  185. return false; // 其中一个不是对象
  186. }
  187. const keys1 = Object.keys(obj1);
  188. const keys2 = Object.keys(obj2);
  189. if (keys1.length !== keys2.length) {
  190. return false; // 属性数量不同
  191. }
  192. for (const key of keys1) {
  193. if (!keys2.includes(key) || !this.deepEqual(obj1[key], obj2[key])) {
  194. return false; // 属性名或属性值不同
  195. }
  196. }
  197. return true;
  198. },
  199. getHexColor(color) {
  200. var values = color
  201. .replace(/rgba?\(/, '')
  202. .replace(/\)/, '')
  203. .replace(/[\s+]/g, '')
  204. .split(',')
  205. var a = parseFloat(values[3] || 1),
  206. r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
  207. g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
  208. b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
  209. return '#' +
  210. ('0' + r.toString(16)).slice(-2) +
  211. ('0' + g.toString(16)).slice(-2) +
  212. ('0' + b.toString(16)).slice(-2)
  213. },
  214. // websocket 返回的数据转义成object类型
  215. parseWSData(data) {
  216. if (data.startsWith("a[")) {
  217. let endLength = data.length - 6;
  218. let textData = data.substr(3, endLength);
  219. let request = textData.split("\\n\\n");
  220. let headerBody = request[0];
  221. let body = request[1];
  222. let headerArray = headerBody.split("\\n");
  223. let header = {};
  224. for (let i = 1; i < headerArray.length; i++) {
  225. let body = headerArray[i];
  226. let resultBody = body.split(":");
  227. header[resultBody[0]] = resultBody[1];
  228. }
  229. let result = {};
  230. result["command"] = headerArray[0];
  231. result["header"] = header;
  232. if (body) {
  233. try {
  234. // let bd = body.replaceAll(/\\+/ig, "");
  235. // let bd = body.replace(/\\"/g, '"') // 将 \\" 替换为 "
  236. // .replace(/\\n/g, '\n'); // 将 \\n 替换为实际的换行符
  237. // result["body"] = JSON.parse(bd);
  238. let cleanBody = body
  239. .replace(/\\\\/g, '\\')
  240. .replace(/\\"/g, '"');
  241. // 使用更精确的正则表达式匹配
  242. const eventMatch = cleanBody.match(/"event"\s*:\s*"([^"]+)"/);
  243. let dataMatch = cleanBody.replaceAll(/\\u([\dA-Fa-f]{4})/g, (_, p1) =>
  244. String.fromCharCode(parseInt(p1, 16))
  245. ).match(/"data"\s*:\s*"([\s\S]*?)(?="\s*})/);
  246. result["body"] = {
  247. event: eventMatch ? eventMatch[1] : '',
  248. data: dataMatch ? dataMatch[1]
  249. .replace(/\\n/g, '\n') // 处理换行符
  250. .replace(/\\"/g, '"') // 处理引号
  251. .replace(/\\\\/g, '\\') // 处理反斜杠
  252. .replace(/\\t/g, '\t') // 处理制表符
  253. .replace(/\\r/g, '') // 移除回车符
  254. .replace(/\\u000/g, '') // 移除 \u000
  255. .trim() : ''
  256. };
  257. } catch (e) {
  258. result["body"] = body;
  259. }
  260. }
  261. return result;
  262. }
  263. return data;
  264. },
  265. converToUrl(requestParams) {
  266. let params = [];
  267. Object.entries(requestParams).forEach(([key, value]) => {
  268. let param = key + '=' + value;
  269. params.push(param);
  270. });
  271. return '?' + params.join('&');
  272. },
  273. /**
  274. * 解析页面路由参数
  275. * @param name
  276. * @returns {null}
  277. */
  278. getQueryString(url, name) {
  279. let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  280. let arr = url.split('?');
  281. let result = null;
  282. arr.forEach((item, index) => {
  283. let res = item.match(reg);
  284. if (res != null) {
  285. result = unescape(res[2]);
  286. }
  287. })
  288. return result
  289. },
  290. /**
  291. * 数字取整
  292. * 例如:145返回100 452返回400
  293. * @param num
  294. * @returns {number}
  295. */
  296. getMaxNum(num) {
  297. let str = num.toString();
  298. let len = str.length;
  299. return Math.floor(num / Math.pow(10, len - 1)) * Math.pow(10, len - 1);
  300. },
  301. };
  302. module.exports = util;