1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import { isIdCard } from "./validate"
/**
* @copyright chuzhixin 1204505056@qq.com
* @description 格式化时间
* @param time
* @param cFormat
* @returns {string|null}
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"
let date
if (typeof time === "object") {
date = time
} else {
if (typeof time === "string" && /^[0-9]+$/.test(time)) {
time = parseInt(time)
}
if (typeof time === "number" && time.toString().length === 10) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay(),
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
if (key === "a") {
return ["日", "一", "二", "三", "四", "五", "六"][value]
}
if (result.length > 0 && value < 10) {
value = "0" + value
}
return value || 0
})
return time_str
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description 格式化时间
* @param time
* @param option
* @returns {string}
*/
export function formatTime(time, option) {
if (("" + time).length === 10) {
time = parseInt(time) * 1000
} else {
time = +time
}
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000
if (diff < 30) {
return "刚刚"
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + "分钟前"
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + "小时前"
} else if (diff < 3600 * 24 * 2) {
return "1天前"
}
if (option) {
return parseTime(time, option)
} else {
return (
d.getMonth() +
1 +
"月" +
d.getDate() +
"日" +
d.getHours() +
"时" +
d.getMinutes() +
"分"
)
}
}
/**
* @description 计算时间差
* @param startTime
* @param endTime
* @returns {string} xx天xx小时xx分xx秒
*/
export function getTimePoor(startTime, endTime) {
if (!startTime || !endTime) {
return ""
}
let result = ""
let date = new Date(endTime).getTime() - new Date(startTime).getTime() //时间差的毫秒数
//------------------------------
//计算出相差天数
let days = Math.floor(date / (24 * 3600 * 1000))
if (days > 0) result += days + "天 "
//计算出小时数
let leave1 = date % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
let hours = Math.floor(leave1 / (3600 * 1000))
if (hours > 0) result += hours + "小时 "
//计算相差分钟数
let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
let minutes = Math.floor(leave2 / (60 * 1000))
if (minutes > 0) result += minutes + "分 "
//计算相差秒数
let leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
let seconds = Math.round(leave3 / 1000)
if (seconds > 0) result += seconds + "秒"
return result
}
/**
* @description 根据身份证获取出生日期 年龄 性别
* @param idCard
* @param type birthDate age gender
* @returns {string}
*/
export function getInfoByIdCard(idCard, type = "birthDate") {
if (!isIdCard(idCard)) return
let birthDate
let age
let gender
const orgBirthDate = idCard.substring(6, 14)
const orgGender = idCard.substring(16, 17)
gender = orgGender % 2 == 1 ? "1" : "2"
birthDate =
orgBirthDate.substring(0, 4) +
"-" +
orgBirthDate.substring(4, 6) +
"-" +
orgBirthDate.substring(6, 8)
const birthdays = new Date(birthDate.replace(/-/g, "/"))
let d = new Date()
age =
d.getFullYear() -
birthdays.getFullYear() -
(d.getMonth() < birthdays.getMonth() ||
(d.getMonth() == birthdays.getMonth() && d.getDate() < birthdays.getDate())
? 1
: 0)
switch (type) {
case "birthDate":
return birthDate
case "age":
return age
case "gender":
return gender
default:
return
}
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description 将url请求参数转为json格式
* @param url
* @returns {{}|any}
*/
export function paramObj(url) {
const search = url.split("?")[1]
if (!search) {
return {}
}
return JSON.parse(
'{"' +
decodeURIComponent(search)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')
.replace(/\+/g, " ") +
'"}'
)
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description 父子关系的数组转换成树形结构数据
* @param data
* @returns {*}
*/
export function translateDataToTree(data) {
const parent = data.filter(
(value) => value.parentId === "undefined" || value.parentId == null
)
const children = data.filter(
(value) => value.parentId !== "undefined" && value.parentId != null
)
const translator = (parent, children) => {
parent.forEach((parent) => {
children.forEach((current, index) => {
if (current.parentId === parent.id) {
const temp = JSON.parse(JSON.stringify(children))
temp.splice(index, 1)
translator([current], temp)
typeof parent.children !== "undefined"
? parent.children.push(current)
: (parent.children = [current])
}
})
})
}
translator(parent, children)
return parent
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description 树形结构数据转换成父子关系的数组
* @param data
* @returns {[]}
*/
export function translateTreeToData(data) {
const result = []
data.forEach((item) => {
const loop = (data) => {
result.push({
id: data.id,
name: data.name,
parentId: data.parentId,
})
const child = data.children
if (child) {
for (let i = 0; i < child.length; i++) {
loop(child[i])
}
}
}
loop(item)
})
return result
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description 10位时间戳转换
* @param time
* @returns {string}
*/
export function tenBitTimestamp(time) {
const date = new Date(time * 1000)
const y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? "" + m : m
let d = date.getDate()
d = d < 10 ? "" + d : d
let h = date.getHours()
h = h < 10 ? "0" + h : h
let minute = date.getMinutes()
let second = date.getSeconds()
minute = minute < 10 ? "0" + minute : minute
second = second < 10 ? "0" + second : second
return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second //组合
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description 13位时间戳转换
* @param time
* @returns {string}
*/
export function thirteenBitTimestamp(time) {
const date = new Date(time / 1)
const y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? "" + m : m
let d = date.getDate()
d = d < 10 ? "" + d : d
let h = date.getHours()
h = h < 10 ? "0" + h : h
let minute = date.getMinutes()
let second = date.getSeconds()
minute = minute < 10 ? "0" + minute : minute
second = second < 10 ? "0" + second : second
return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second //组合
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description 获取随机id
* @param length
* @returns {string}
*/
export function uuid(length = 32) {
const num = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
let str = ""
for (let i = 0; i < length; i++) {
str += num.charAt(Math.floor(Math.random() * num.length))
}
return str
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description m到n的随机数
* @param m
* @param n
* @returns {number}
*/
export function random(m, n) {
return Math.floor(Math.random() * (m - n) + n)
}
/**
* @copyright chuzhixin 1204505056@qq.com
* @description addEventListener
* @type {function(...[*]=)}
*/
export const on = (function () {
return function (element, event, handler, useCapture = false) {
if (element && event && handler) {
element.addEventListener(event, handler, useCapture)
}
}
})()
/**
* @copyright chuzhixin 1204505056@qq.com
* @description removeEventListener
* @type {function(...[*]=)}
*/
export const off = (function () {
return function (element, event, handler, useCapture = false) {
if (element && event) {
element.removeEventListener(event, handler, useCapture)
}
}
})()
/**
* @description 防抖
* @param func
* @param wait
* @param immediate
* @returns {Function}
*
*/
export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result
const later = function () {
// 据上一次触发时间间隔
const last = +new Date() - timestamp
// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
// 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
if (!immediate) {
result = func.apply(context, args)
if (!timeout) context = args = null
}
}
}
return function (...args) {
context = this
timestamp = +new Date()
const callNow = immediate && !timeout
// 如果延时不存在,重新设定延时
if (!timeout) timeout = setTimeout(later, wait)
if (callNow) {
result = func.apply(context, args)
context = args = null
}
return result
}
}
/**
* @description 节流
* @param fn
* @param delay
* @param immediate
* @returns {Function}
*/
export function throttle(fn, delay = 500, immediate = false) {
let timer = null,
immediateTimer = null,
immediateRunning = !immediate
return function () {
let context = this,
args = arguments
if (immediate && !immediateRunning) {
fn.apply(context, args)
immediateRunning = true
// // 重置首次执行标识
immediateTimer = setTimeout(() => {
immediateRunning = false
}, delay)
return
}
if (!timer) {
// 如果有后续触发,在定时器中取消immediateTimer
if (immediateTimer) {
clearTimeout(immediateTimer)
immediateTimer = null
}
timer = setTimeout(() => {
fn.apply(context, args)
timer = null
immediateTimer = setTimeout(() => {
immediateRunning = false
}, delay)
}, delay)
}
}
}
/**
* @description excel导出
* @param data
* @param title
*
*/
export function excelExport(data, title = "结果") {
if ("msSaveOrOpenBlob" in navigator) {
//兼容ie
let blob = new Blob([data], {
type: "application/vnd.ms-excel",
})
window.navigator.msSaveOrOpenBlob(blob, `${title}.xlsx`)
return
} else {
const link = document.createElement("a")
let blob = new Blob([data], {
type: "application/vnd.ms-excel",
})
link.style.display = "none"
link.href = URL.createObjectURL(blob)
link.setAttribute("download", `${title}.xlsx`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
/**
* 根据list、value 得出 label
* @export
* @param {*} list 数据list
* @param {*} value 对应值
* @returns
*/
export function formatDicList(list, value, connector = ",") {
if (!list) return ""
if (list.constructor !== Array) return ""
// if (!value && value != 0) return ""
let result = "--"
let multiple = Array.isArray(value) ? true : false
if (multiple) {
const resultList = []
value.forEach((val) => {
let obj = list.find((item) => item.value == val)
if (obj) {
resultList.push(obj.label)
}
})
result = resultList.join(connector)
} else {
list.some((item) => {
if (item.value === value) {
result = item.label
}
})
}
return result
}
/**
* base64编码转换成pdf
* @export
* @param {*} code base64字符串
* @returns url pdf地址
*/
export function base64ToPdf(code) {
code = res.data.replace(/\\r|\\n/g, "")
let raw = window.atob(code)
let rawLen = raw.length
let arr = new Uint8Array(rawLen)
for (let i = 0; i < rawLen; ++i) {
arr[i] = raw.charCodeAt(i)
}
let bold = new Blob([arr], { type: "application/pdf" })
return URL.createObjectURL(bold)
}
/**
* 秒转换成天时分秒
* @export
* @param time
* @returns {string}
*/
export function changeTime(time) {
let day = Math.floor(time / 86400) //天
let hours = Math.floor((time % 86400) / 3600) //时
let minutes = Math.floor((time % 3600) / 60) //分
let seconds = Math.floor(time % 60) //秒
return `${day ? day + "天" : ""} ${hours ? hours + "小时" : ""}${
minutes ? minutes + "分" : ""
}${seconds}秒`
}
export default { formatDicList, excelExport }