阅行客电子档案
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.

502 lines
12 KiB

3 years ago
3 years ago
1 year ago
3 years ago
2 years ago
3 years ago
  1. /**
  2. * Created by PanJiaChen on 16/11/18.
  3. */
  4. import { getToken } from '@/utils/auth'
  5. /**
  6. * Parse the time to string
  7. * @param {(Object|string|number)} time
  8. * @param {string} cFormat
  9. * @returns {string}
  10. */
  11. export function parseTime(time, cFormat) {
  12. if (arguments.length === 0) {
  13. return null
  14. }
  15. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  16. let date
  17. if (typeof time === 'undefined' || time === null || time === 'null') {
  18. return ''
  19. } else if (typeof time === 'object') {
  20. date = time
  21. } else {
  22. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  23. time = parseInt(time)
  24. }
  25. if ((typeof time === 'number') && (time.toString().length === 10)) {
  26. time = time * 1000
  27. }
  28. date = new Date(time)
  29. }
  30. const formatObj = {
  31. y: date.getFullYear(),
  32. m: date.getMonth() + 1,
  33. d: date.getDate(),
  34. h: date.getHours(),
  35. i: date.getMinutes(),
  36. s: date.getSeconds(),
  37. a: date.getDay()
  38. }
  39. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  40. let value = formatObj[key]
  41. // Note: getDay() returns 0 on Sunday
  42. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
  43. if (result.length > 0 && value < 10) {
  44. value = '0' + value
  45. }
  46. return value || 0
  47. })
  48. return time_str
  49. }
  50. /**
  51. * @param {number} time
  52. * @param {string} option
  53. * @returns {string}
  54. */
  55. export function formatTime(time, option) {
  56. if (('' + time).length === 10) {
  57. time = parseInt(time) * 1000
  58. } else {
  59. time = +time
  60. }
  61. const d = new Date(time)
  62. const now = Date.now()
  63. const diff = (now - d) / 1000
  64. if (diff < 30) {
  65. return '刚刚'
  66. } else if (diff < 3600) {
  67. // less 1 hour
  68. return Math.ceil(diff / 60) + '分钟前'
  69. } else if (diff < 3600 * 24) {
  70. return Math.ceil(diff / 3600) + '小时前'
  71. } else if (diff < 3600 * 24 * 2) {
  72. return '1天前'
  73. }
  74. if (option) {
  75. return parseTime(time, option)
  76. } else {
  77. return (
  78. d.getMonth() +
  79. 1 +
  80. '月' +
  81. d.getDate() +
  82. '日' +
  83. d.getHours() +
  84. '时' +
  85. d.getMinutes() +
  86. '分'
  87. )
  88. }
  89. }
  90. /**
  91. * @param {string} url
  92. * @returns {Object}
  93. */
  94. export function getQueryObject(url) {
  95. url = url == null ? window.location.href : url
  96. const search = url.substring(url.lastIndexOf('?') + 1)
  97. const obj = {}
  98. const reg = /([^?&=]+)=([^?&=]*)/g
  99. search.replace(reg, (rs, $1, $2) => {
  100. const name = decodeURIComponent($1)
  101. let val = decodeURIComponent($2)
  102. val = String(val)
  103. obj[name] = val
  104. return rs
  105. })
  106. return obj
  107. }
  108. /**
  109. * @param {string} input value
  110. * @returns {number} output value
  111. */
  112. export function byteLength(str) {
  113. // returns the byte length of an utf8 string
  114. let s = str.length
  115. for (var i = str.length - 1; i >= 0; i--) {
  116. const code = str.charCodeAt(i)
  117. if (code > 0x7f && code <= 0x7ff) s++
  118. else if (code > 0x7ff && code <= 0xffff) s += 2
  119. if (code >= 0xDC00 && code <= 0xDFFF) i--
  120. }
  121. return s
  122. }
  123. /**
  124. * @param {Array} actual
  125. * @returns {Array}
  126. */
  127. export function cleanArray(actual) {
  128. const newArray = []
  129. for (let i = 0; i < actual.length; i++) {
  130. if (actual[i]) {
  131. newArray.push(actual[i])
  132. }
  133. }
  134. return newArray
  135. }
  136. /**
  137. * @param {Object} json
  138. * @returns {Array}
  139. */
  140. export function param(json) {
  141. if (!json) return ''
  142. return cleanArray(
  143. Object.keys(json).map(key => {
  144. if (json[key] === undefined) return ''
  145. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  146. })
  147. ).join('&')
  148. }
  149. /**
  150. * @param {string} url
  151. * @returns {Object}
  152. */
  153. export function param2Obj(url) {
  154. const search = url.split('?')[1]
  155. if (!search) {
  156. return {}
  157. }
  158. return JSON.parse(
  159. '{"' +
  160. decodeURIComponent(search)
  161. .replace(/"/g, '\\"')
  162. .replace(/&/g, '","')
  163. .replace(/=/g, '":"')
  164. .replace(/\+/g, ' ') +
  165. '"}'
  166. )
  167. }
  168. /**
  169. * @param {string} val
  170. * @returns {string}
  171. */
  172. export function html2Text(val) {
  173. const div = document.createElement('div')
  174. div.innerHTML = val
  175. return div.textContent || div.innerText
  176. }
  177. /**
  178. * Merges two objects, giving the last one precedence
  179. * @param {Object} target
  180. * @param {(Object|Array)} source
  181. * @returns {Object}
  182. */
  183. export function objectMerge(target, source) {
  184. if (typeof target !== 'object') {
  185. target = {}
  186. }
  187. if (Array.isArray(source)) {
  188. return source.slice()
  189. }
  190. Object.keys(source).forEach(property => {
  191. const sourceProperty = source[property]
  192. if (typeof sourceProperty === 'object') {
  193. target[property] = objectMerge(target[property], sourceProperty)
  194. } else {
  195. target[property] = sourceProperty
  196. }
  197. })
  198. return target
  199. }
  200. /**
  201. * @param {HTMLElement} element
  202. * @param {string} className
  203. */
  204. export function toggleClass(element, className) {
  205. if (!element || !className) {
  206. return
  207. }
  208. let classString = element.className
  209. const nameIndex = classString.indexOf(className)
  210. if (nameIndex === -1) {
  211. classString += '' + className
  212. } else {
  213. classString =
  214. classString.substr(0, nameIndex) +
  215. classString.substr(nameIndex + className.length)
  216. }
  217. element.className = classString
  218. }
  219. /**
  220. * @param {string} type
  221. * @returns {Date}
  222. */
  223. export function getTime(type) {
  224. if (type === 'start') {
  225. return new Date().getTime() - 3600 * 1000 * 24 * 90
  226. } else {
  227. return new Date(new Date().toDateString())
  228. }
  229. }
  230. /**
  231. * @param {Function} func
  232. * @param {number} wait
  233. * @param {boolean} immediate
  234. * @return {*}
  235. */
  236. export function debounce(func, wait, immediate) {
  237. let timeout, args, context, timestamp, result
  238. const later = function() {
  239. // 据上一次触发时间间隔
  240. const last = +new Date() - timestamp
  241. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  242. if (last < wait && last > 0) {
  243. timeout = setTimeout(later, wait - last)
  244. } else {
  245. timeout = null
  246. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  247. if (!immediate) {
  248. result = func.apply(context, args)
  249. if (!timeout) context = args = null
  250. }
  251. }
  252. }
  253. return function(...args) {
  254. context = this
  255. timestamp = +new Date()
  256. const callNow = immediate && !timeout
  257. // 如果延时不存在,重新设定延时
  258. if (!timeout) timeout = setTimeout(later, wait)
  259. if (callNow) {
  260. result = func.apply(context, args)
  261. context = args = null
  262. }
  263. return result
  264. }
  265. }
  266. /**
  267. * This is just a simple version of deep copy
  268. * Has a lot of edge cases bug
  269. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  270. * @param {Object} source
  271. * @returns {Object}
  272. */
  273. export function deepClone(source) {
  274. if (!source && typeof source !== 'object') {
  275. throw new Error('error arguments', 'deepClone')
  276. }
  277. const targetObj = source.constructor === Array ? [] : {}
  278. Object.keys(source).forEach(keys => {
  279. if (source[keys] && typeof source[keys] === 'object') {
  280. targetObj[keys] = deepClone(source[keys])
  281. } else {
  282. targetObj[keys] = source[keys]
  283. }
  284. })
  285. return targetObj
  286. }
  287. /**
  288. * @param {Array} arr
  289. * @returns {Array}
  290. */
  291. export function uniqueArr(arr) {
  292. return Array.from(new Set(arr))
  293. }
  294. /**
  295. * @returns {string}
  296. */
  297. export function createUniqueString() {
  298. const timestamp = +new Date() + ''
  299. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  300. return (+(randomNum + timestamp)).toString(32)
  301. }
  302. /**
  303. * Check if an element has a class
  304. * @param {HTMLElement} elm
  305. * @param {string} cls
  306. * @returns {boolean}
  307. */
  308. export function hasClass(ele, cls) {
  309. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  310. }
  311. /**
  312. * Add class to element
  313. * @param {HTMLElement} elm
  314. * @param {string} cls
  315. */
  316. export function addClass(ele, cls) {
  317. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  318. }
  319. /**
  320. * Remove class from element
  321. * @param {HTMLElement} elm
  322. * @param {string} cls
  323. */
  324. export function removeClass(ele, cls) {
  325. if (hasClass(ele, cls)) {
  326. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  327. ele.className = ele.className.replace(reg, ' ')
  328. }
  329. }
  330. // 替换邮箱字符
  331. export function regEmail(email) {
  332. if (String(email).indexOf('@') > 0) {
  333. const str = email.split('@')
  334. let _s = ''
  335. if (str[0].length > 3) {
  336. for (var i = 0; i < str[0].length - 3; i++) {
  337. _s += '*'
  338. }
  339. }
  340. var new_email = str[0].substr(0, 3) + _s + '@' + str[1]
  341. }
  342. return new_email
  343. }
  344. // 替换手机字符
  345. export function regMobile(mobile) {
  346. if (mobile.length > 7) {
  347. var new_mobile = mobile.substr(0, 3) + '****' + mobile.substr(7)
  348. }
  349. return new_mobile
  350. }
  351. // 下载文件
  352. export function downloadFile(obj, name, suffix) {
  353. const url = window.URL.createObjectURL(new Blob([obj]))
  354. const link = document.createElement('a')
  355. link.style.display = 'none'
  356. link.href = url
  357. const fileName = name + '.' + suffix
  358. link.setAttribute('download', fileName)
  359. document.body.appendChild(link)
  360. link.click()
  361. document.body.removeChild(link)
  362. }
  363. // 下载文件
  364. export function downloadDataBase(obj, name, suffix) {
  365. const url = window.URL.createObjectURL(new Blob([obj]))
  366. const link = document.createElement('a')
  367. link.style.display = 'none'
  368. link.href = url
  369. const fileName = name + '.' + suffix
  370. link.setAttribute('download', fileName)
  371. document.body.appendChild(link)
  372. link.click()
  373. document.body.removeChild(link)
  374. }
  375. // new - 导出
  376. export function exportFile(url, fileName) {
  377. const link = document.createElement('a')
  378. link.style.display = 'none'
  379. link.href = url
  380. link.setAttribute('target', '_blank')
  381. link.setAttribute('download', fileName)
  382. document.body.appendChild(link)
  383. link.click()
  384. document.body.removeChild(link)
  385. }
  386. // 获取当前日期时间
  387. export function getCurrentTime() {
  388. const yy = new Date().getFullYear()
  389. const mm = new Date().getMonth() + 1
  390. const dd = new Date().getDate()
  391. const hh = new Date().getHours()
  392. const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
  393. const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
  394. const time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
  395. return time
  396. }
  397. // 导出
  398. export function getBlob(url, cb) {
  399. var xhr = new XMLHttpRequest()
  400. xhr.open('GET', url, true)
  401. xhr.responseType = 'blob'
  402. xhr.onload = function() {
  403. if (xhr.status === 200) {
  404. cb(xhr.response)
  405. }
  406. }
  407. xhr.send()
  408. }
  409. export function saveAs(blob, filename) {
  410. if (window.navigator.msSaveOrOpenBlob) {
  411. navigator.msSaveBlob(blob, filename)
  412. } else {
  413. var link = document.createElement('a')
  414. var body = document.querySelector('body')
  415. link.href = window.URL.createObjectURL(blob)
  416. link.download = filename
  417. link.style.display = 'none'
  418. body.appendChild(link)
  419. link.click()
  420. body.removeChild(link)
  421. window.URL.revokeObjectURL(link.href)
  422. }
  423. }
  424. // 定义时间
  425. export function timeFormate() {
  426. const date = new Date()
  427. const Y = date.getFullYear()
  428. const M =
  429. date.getMonth() + 1 < 10
  430. ? '0' + (date.getMonth() + 1)
  431. : date.getMonth() + 1
  432. const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  433. return Y + M + D
  434. }
  435. // 下载文件
  436. export function saveByteArray(fileName, byte) {
  437. var blob = new Blob([byte], { type: 'application/pdf' })
  438. var link = document.createElement('a')
  439. link.href = window.URL.createObjectURL(blob)
  440. // var fileName = reportName;
  441. link.download = fileName
  442. link.click()
  443. }
  444. export function exportFileToken(url, fileName) {
  445. const link = document.createElement('a')
  446. link.style.display = 'none'
  447. const xhr = new XMLHttpRequest()
  448. xhr.open('GET', url, true)
  449. xhr.setRequestHeader('Authorization', getToken())
  450. xhr.responseType = 'blob'
  451. xhr.onload = function() {
  452. if (xhr.status === 200) {
  453. const blob = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') })
  454. const url = window.URL.createObjectURL(blob)
  455. link.href = url
  456. link.setAttribute('download', fileName || 'export.xlsx')
  457. document.body.appendChild(link)
  458. link.click()
  459. document.body.removeChild(link)
  460. window.URL.revokeObjectURL(url)
  461. }
  462. }
  463. xhr.send()
  464. }