华西海圻ELN前端工程
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

424 lines
9.7 KiB

  1. import { parseTime } from './ruoyi'
  2. import { encrypt, decrypt } from '@/utils/encryptUtil';
  3. import moment from 'moment';
  4. /**
  5. * 表格时间格式化
  6. */
  7. export function formatDate(cellValue) {
  8. if (cellValue == null || cellValue == "") return ""
  9. var date = new Date(cellValue)
  10. var year = date.getFullYear()
  11. var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  12. var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  13. var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  14. var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  15. var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  16. return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  17. }
  18. /**
  19. * @param {number} time
  20. * @param {string} option
  21. * @returns {string}
  22. */
  23. export function formatTime(time, option) {
  24. if (('' + time).length === 10) {
  25. time = parseInt(time) * 1000
  26. } else {
  27. time = +time
  28. }
  29. const d = new Date(time)
  30. const now = Date.now()
  31. const diff = (now - d) / 1000
  32. if (diff < 30) {
  33. return '刚刚'
  34. } else if (diff < 3600) {
  35. // less 1 hour
  36. return Math.ceil(diff / 60) + '分钟前'
  37. } else if (diff < 3600 * 24) {
  38. return Math.ceil(diff / 3600) + '小时前'
  39. } else if (diff < 3600 * 24 * 2) {
  40. return '1天前'
  41. }
  42. if (option) {
  43. return parseTime(time, option)
  44. } else {
  45. return (
  46. d.getMonth() +
  47. 1 +
  48. '月' +
  49. d.getDate() +
  50. '日' +
  51. d.getHours() +
  52. '时' +
  53. d.getMinutes() +
  54. '分'
  55. )
  56. }
  57. }
  58. /**
  59. * @param {string} url
  60. * @returns {Object}
  61. */
  62. export function getQueryObject(url) {
  63. url = url == null ? window.location.href : url
  64. const search = url.substring(url.lastIndexOf('?') + 1)
  65. const obj = {}
  66. const reg = /([^?&=]+)=([^?&=]*)/g
  67. search.replace(reg, (rs, $1, $2) => {
  68. const name = decodeURIComponent($1)
  69. let val = decodeURIComponent($2)
  70. val = String(val)
  71. obj[name] = val
  72. return rs
  73. })
  74. return obj
  75. }
  76. /**
  77. * @param {string} input value
  78. * @returns {number} output value
  79. */
  80. export function byteLength(str) {
  81. // returns the byte length of an utf8 string
  82. let s = str.length
  83. for (var i = str.length - 1; i >= 0; i--) {
  84. const code = str.charCodeAt(i)
  85. if (code > 0x7f && code <= 0x7ff) s++
  86. else if (code > 0x7ff && code <= 0xffff) s += 2
  87. if (code >= 0xDC00 && code <= 0xDFFF) i--
  88. }
  89. return s
  90. }
  91. /**
  92. * @param {Array} actual
  93. * @returns {Array}
  94. */
  95. export function cleanArray(actual) {
  96. const newArray = []
  97. for (let i = 0; i < actual.length; i++) {
  98. if (actual[i]) {
  99. newArray.push(actual[i])
  100. }
  101. }
  102. return newArray
  103. }
  104. /**
  105. * @param {Object} json
  106. * @returns {Array}
  107. */
  108. export function param(json) {
  109. if (!json) return ''
  110. return cleanArray(
  111. Object.keys(json).map(key => {
  112. if (json[key] === undefined) return ''
  113. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  114. })
  115. ).join('&')
  116. }
  117. /**
  118. * @param {string} url
  119. * @returns {Object}
  120. */
  121. export function param2Obj(url) {
  122. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  123. if (!search) {
  124. return {}
  125. }
  126. const obj = {}
  127. const searchArr = search.split('&')
  128. searchArr.forEach(v => {
  129. const index = v.indexOf('=')
  130. if (index !== -1) {
  131. const name = v.substring(0, index)
  132. const val = v.substring(index + 1, v.length)
  133. obj[name] = val
  134. }
  135. })
  136. return obj
  137. }
  138. /**
  139. * @param {string} val
  140. * @returns {string}
  141. */
  142. export function html2Text(val) {
  143. const div = document.createElement('div')
  144. div.innerHTML = val
  145. return div.textContent || div.innerText
  146. }
  147. /**
  148. * Merges two objects, giving the last one precedence
  149. * @param {Object} target
  150. * @param {(Object|Array)} source
  151. * @returns {Object}
  152. */
  153. export function objectMerge(target, source) {
  154. if (typeof target !== 'object') {
  155. target = {}
  156. }
  157. if (Array.isArray(source)) {
  158. return source.slice()
  159. }
  160. Object.keys(source).forEach(property => {
  161. const sourceProperty = source[property]
  162. if (typeof sourceProperty === 'object') {
  163. target[property] = objectMerge(target[property], sourceProperty)
  164. } else {
  165. target[property] = sourceProperty
  166. }
  167. })
  168. return target
  169. }
  170. /**
  171. * @param {HTMLElement} element
  172. * @param {string} className
  173. */
  174. export function toggleClass(element, className) {
  175. if (!element || !className) {
  176. return
  177. }
  178. let classString = element.className
  179. const nameIndex = classString.indexOf(className)
  180. if (nameIndex === -1) {
  181. classString += '' + className
  182. } else {
  183. classString =
  184. classString.substr(0, nameIndex) +
  185. classString.substr(nameIndex + className.length)
  186. }
  187. element.className = classString
  188. }
  189. /**
  190. * @param {string} type
  191. * @returns {Date}
  192. */
  193. export function getTime(type) {
  194. if (type === 'start') {
  195. return new Date().getTime() - 3600 * 1000 * 24 * 90
  196. } else {
  197. return new Date(new Date().toDateString())
  198. }
  199. }
  200. /**
  201. * @param {Function} func
  202. * @param {number} wait
  203. * @param {boolean} immediate
  204. * @return {*}
  205. */
  206. export function debounce(func, wait, immediate) {
  207. let timeout, args, context, timestamp, result
  208. const later = function () {
  209. // 据上一次触发时间间隔
  210. const last = +new Date() - timestamp
  211. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  212. if (last < wait && last > 0) {
  213. timeout = setTimeout(later, wait - last)
  214. } else {
  215. timeout = null
  216. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  217. if (!immediate) {
  218. result = func.apply(context, args)
  219. if (!timeout) context = args = null
  220. }
  221. }
  222. }
  223. return function (...args) {
  224. context = this
  225. timestamp = +new Date()
  226. const callNow = immediate && !timeout
  227. // 如果延时不存在,重新设定延时
  228. if (!timeout) timeout = setTimeout(later, wait)
  229. if (callNow) {
  230. result = func.apply(context, args)
  231. context = args = null
  232. }
  233. return result
  234. }
  235. }
  236. /**
  237. * This is just a simple version of deep copy
  238. * Has a lot of edge cases bug
  239. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  240. * @param {Object} source
  241. * @returns {Object}
  242. */
  243. export function deepClone(source) {
  244. if (!source && typeof source !== 'object') {
  245. throw new Error('error arguments', 'deepClone')
  246. }
  247. const targetObj = source.constructor === Array ? [] : {}
  248. Object.keys(source).forEach(keys => {
  249. if (source[keys] && typeof source[keys] === 'object') {
  250. targetObj[keys] = deepClone(source[keys])
  251. } else {
  252. targetObj[keys] = source[keys]
  253. }
  254. })
  255. return targetObj
  256. }
  257. /**
  258. * @param {Array} arr
  259. * @returns {Array}
  260. */
  261. export function uniqueArr(arr) {
  262. return Array.from(new Set(arr))
  263. }
  264. /**
  265. * @returns {string}
  266. */
  267. export function createUniqueString() {
  268. const timestamp = +new Date() + ''
  269. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  270. return (+(randomNum + timestamp)).toString(32)
  271. }
  272. /**
  273. * Check if an element has a class
  274. * @param {HTMLElement} elm
  275. * @param {string} cls
  276. * @returns {boolean}
  277. */
  278. export function hasClass(ele, cls) {
  279. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  280. }
  281. /**
  282. * Add class to element
  283. * @param {HTMLElement} elm
  284. * @param {string} cls
  285. */
  286. export function addClass(ele, cls) {
  287. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  288. }
  289. /**
  290. * Remove class from element
  291. * @param {HTMLElement} elm
  292. * @param {string} cls
  293. */
  294. export function removeClass(ele, cls) {
  295. if (hasClass(ele, cls)) {
  296. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  297. ele.className = ele.className.replace(reg, ' ')
  298. }
  299. }
  300. export function makeMap(str, expectsLowerCase) {
  301. const map = Object.create(null)
  302. const list = str.split(',')
  303. for (let i = 0; i < list.length; i++) {
  304. map[list[i]] = true
  305. }
  306. return expectsLowerCase
  307. ? val => map[val.toLowerCase()]
  308. : val => map[val]
  309. }
  310. export const exportDefault = 'export default '
  311. export const beautifierConf = {
  312. html: {
  313. indent_size: '2',
  314. indent_char: ' ',
  315. max_preserve_newlines: '-1',
  316. preserve_newlines: false,
  317. keep_array_indentation: false,
  318. break_chained_methods: false,
  319. indent_scripts: 'separate',
  320. brace_style: 'end-expand',
  321. space_before_conditional: true,
  322. unescape_strings: false,
  323. jslint_happy: false,
  324. end_with_newline: true,
  325. wrap_line_length: '110',
  326. indent_inner_html: true,
  327. comma_first: false,
  328. e4x: true,
  329. indent_empty_lines: true
  330. },
  331. js: {
  332. indent_size: '2',
  333. indent_char: ' ',
  334. max_preserve_newlines: '-1',
  335. preserve_newlines: false,
  336. keep_array_indentation: false,
  337. break_chained_methods: false,
  338. indent_scripts: 'normal',
  339. brace_style: 'end-expand',
  340. space_before_conditional: true,
  341. unescape_strings: false,
  342. jslint_happy: true,
  343. end_with_newline: true,
  344. wrap_line_length: '110',
  345. indent_inner_html: true,
  346. comma_first: false,
  347. e4x: true,
  348. indent_empty_lines: true
  349. }
  350. }
  351. // 首字母大小
  352. export function titleCase(str) {
  353. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  354. }
  355. // 下划转驼峰
  356. export function camelCase(str) {
  357. return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  358. }
  359. export function isNumberStr(str) {
  360. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  361. }
  362. // 编码
  363. export function caesarCipher(str) {
  364. return btoa(encrypt(str))
  365. }
  366. // 解码
  367. export function caesarDecipher(str) {
  368. return decrypt(atob(str));
  369. }
  370. //比较值是否相等,不需要比较类型
  371. export const isEqual = (oldValue, nowValue) => {
  372. if (oldValue === null || nowValue === null) {
  373. return oldValue === nowValue;
  374. }
  375. if (typeof oldValue === 'object' && typeof nowValue === 'object') {
  376. return JSON.stringify(oldValue) === JSON.stringify(nowValue);
  377. }
  378. return oldValue == nowValue;
  379. }
  380. //计算过期时间
  381. export const getExpireDate = (startDate, effectivePeriod, effectivePeriodUnit) => {
  382. const start = moment(startDate)
  383. const unit = effectivePeriodUnit === '天' ? 'days' : 'hours';
  384. const end = start
  385. .add(Number(effectivePeriod), unit)
  386. .format('YYYY-MM-DD HH:mm:ss');
  387. return end;
  388. }
  389. export function getuuid() {
  390. return Math.random().toString(36).substring(2) +
  391. Date.now().toString(36);
  392. }