index.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /**
  2. * 格式化时间
  3. * @param time
  4. * @param cFormat
  5. * @returns {string|null}
  6. */
  7. import { JSEncrypt } from 'jsencrypt'
  8. export function parseTime(time, cFormat) {
  9. if (arguments.length === 0) {
  10. return null
  11. }
  12. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  13. let date
  14. if (typeof time === 'object') {
  15. date = time
  16. } else {
  17. if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
  18. time = parseInt(time)
  19. }
  20. if (typeof time === 'number' && time.toString().length === 10) {
  21. time = time * 1000
  22. }
  23. date = new Date(time)
  24. }
  25. const formatObj = {
  26. y: date.getFullYear(),
  27. m: date.getMonth() + 1,
  28. d: date.getDate(),
  29. h: date.getHours(),
  30. i: date.getMinutes(),
  31. s: date.getSeconds(),
  32. a: date.getDay(),
  33. }
  34. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  35. let value = formatObj[key]
  36. if (key === 'a') {
  37. return ['日', '一', '二', '三', '四', '五', '六'][value]
  38. }
  39. if (result.length > 0 && value < 10) {
  40. value = '0' + value
  41. }
  42. return value || 0
  43. })
  44. return time_str
  45. }
  46. /**
  47. * 格式化时间
  48. * @param time
  49. * @param option
  50. * @returns {string}
  51. */
  52. export function formatTime(time, option) {
  53. if (('' + time).length === 10) {
  54. time = parseInt(time) * 1000
  55. } else {
  56. time = +time
  57. }
  58. const d = new Date(time)
  59. const now = Date.now()
  60. const diff = (now - d) / 1000
  61. if (diff < 30) {
  62. return '刚刚'
  63. } else if (diff < 3600) {
  64. // less 1 hour
  65. return Math.ceil(diff / 60) + '分钟前'
  66. } else if (diff < 3600 * 24) {
  67. return Math.ceil(diff / 3600) + '小时前'
  68. } else if (diff < 3600 * 24 * 2) {
  69. return '1天前'
  70. }
  71. if (option) {
  72. return parseTime(time, option)
  73. } else {
  74. return (
  75. d.getMonth() +
  76. 1 +
  77. '月' +
  78. d.getDate() +
  79. '日' +
  80. d.getHours() +
  81. '时' +
  82. d.getMinutes() +
  83. '分'
  84. )
  85. }
  86. }
  87. /**
  88. * 将url请求参数转为json格式
  89. * @param url
  90. * @returns {{}|any}
  91. */
  92. export function paramObj(url) {
  93. const search = url.split('?')[1]
  94. if (!search) {
  95. return {}
  96. }
  97. const replacedSearch = decodeURIComponent(search)
  98. .replace(/"/g, '\\"')
  99. .replace(/&/g, '","')
  100. .replace(/=/g, '":"')
  101. .replace(/\+/g, ' ')
  102. return JSON.parse(`{${replacedSearch}}`)
  103. }
  104. /**
  105. * 父子关系的数组转换成树形结构数据
  106. * @param data
  107. * @returns {*}
  108. */
  109. export function translateDataToTree(data) {
  110. const parent = data.filter(
  111. (value) => value.parentId === 'undefined' || value.parentId == null
  112. )
  113. const children = data.filter(
  114. (value) => value.parentId !== 'undefined' && value.parentId != null
  115. )
  116. const translator = (parent, children) => {
  117. parent.forEach((parent) => {
  118. children.forEach((current, index) => {
  119. if (current.parentId === parent.id) {
  120. const temp = JSON.parse(JSON.stringify(children))
  121. temp.splice(index, 1)
  122. translator([current], temp)
  123. typeof parent.children !== 'undefined'
  124. ? parent.children.push(current)
  125. : (parent.children = [current])
  126. }
  127. })
  128. })
  129. }
  130. translator(parent, children)
  131. return parent
  132. }
  133. /**
  134. * 树形结构数据转换成父子关系的数组
  135. * @param data
  136. * @returns {[]}
  137. */
  138. export function translateTreeToData(data) {
  139. const result = []
  140. data.forEach((item) => {
  141. const loop = (data) => {
  142. result.push({
  143. id: data.id,
  144. name: data.name,
  145. parentId: data.parentId,
  146. })
  147. const child = data.children
  148. if (child) {
  149. for (let i = 0; i < child.length; i++) {
  150. loop(child[i])
  151. }
  152. }
  153. }
  154. loop(item)
  155. })
  156. return result
  157. }
  158. /**
  159. * 10位时间戳转换
  160. * @param time
  161. * @returns {string}
  162. */
  163. export function tenBitTimestamp(time) {
  164. const date = new Date(time * 1000)
  165. const y = date.getFullYear()
  166. let m = date.getMonth() + 1
  167. m = m < 10 ? '' + m : m
  168. let d = date.getDate()
  169. d = d < 10 ? '' + d : d
  170. let h = date.getHours()
  171. h = h < 10 ? '0' + h : h
  172. let minute = date.getMinutes()
  173. let second = date.getSeconds()
  174. minute = minute < 10 ? '0' + minute : minute
  175. second = second < 10 ? '0' + second : second
  176. return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
  177. }
  178. /**
  179. * 13位时间戳转换
  180. * @param time
  181. * @returns {string}
  182. */
  183. export function thirteenBitTimestamp(time) {
  184. const date = new Date(time / 1)
  185. const y = date.getFullYear()
  186. let m = date.getMonth() + 1
  187. m = m < 10 ? '' + m : m
  188. let d = date.getDate()
  189. d = d < 10 ? '' + d : d
  190. let h = date.getHours()
  191. h = h < 10 ? '0' + h : h
  192. let minute = date.getMinutes()
  193. let second = date.getSeconds()
  194. minute = minute < 10 ? '0' + minute : minute
  195. second = second < 10 ? '0' + second : second
  196. return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
  197. }
  198. /**
  199. * 获取随机id
  200. * @param length
  201. * @returns {string}
  202. */
  203. export function uuid(length = 32) {
  204. const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  205. let str = ''
  206. for (let i = 0; i < length; i++) {
  207. str += num.charAt(Math.floor(Math.random() * num.length))
  208. }
  209. return str
  210. }
  211. /**
  212. * m到n的随机数
  213. * @param m
  214. * @param n
  215. * @returns {number}
  216. */
  217. export function random(m, n) {
  218. return Math.floor(Math.random() * (m - n) + n)
  219. }
  220. /**
  221. * addEventListener
  222. * @type {function(...[*]=)}
  223. */
  224. export const on = (function () {
  225. return function (element, event, handler, useCapture = false) {
  226. if (element && event && handler) {
  227. element.addEventListener(event, handler, useCapture)
  228. }
  229. }
  230. })()
  231. /**
  232. * removeEventListener
  233. * @type {function(...[*]=)}
  234. */
  235. export const off = (function () {
  236. return function (element, event, handler, useCapture = false) {
  237. if (element && event) {
  238. element.removeEventListener(event, handler, useCapture)
  239. }
  240. }
  241. })()
  242. /**
  243. * 删除URL中指定search参数,会将参数值一起删除
  244. * @param {string} url 地址字符串
  245. * @param {array} aParam 要删除的参数key数组,如['name','age']
  246. * @return {string} 返回新URL字符串
  247. */
  248. export function ridUrlParam(url, aParam) {
  249. aParam.forEach((item) => {
  250. const fromindex = url.indexOf(`${item}=`) //必须加=号,避免参数值中包含item字符串
  251. if (fromindex !== -1) {
  252. // 通过url特殊符号,计算出=号后面的的字符数,用于生成replace正则
  253. const startIndex = url.indexOf('=', fromindex)
  254. const endIndex = url.indexOf('&', fromindex)
  255. const hashIndex = url.indexOf('#', fromindex)
  256. let reg
  257. if (endIndex !== -1) {
  258. // 后面还有search参数的情况
  259. const num = endIndex - startIndex
  260. reg = new RegExp(`${item}=.{${num}}`)
  261. url = url.replace(reg, '')
  262. } else if (hashIndex !== -1) {
  263. // 有hash参数的情况
  264. const num = hashIndex - startIndex - 1
  265. reg = new RegExp(`&?${item}=.{${num}}`)
  266. url = url.replace(reg, '')
  267. } else {
  268. // search参数在最后或只有一个参数的情况
  269. reg = new RegExp(`&?${item}=.+`)
  270. url = url.replace(reg, '')
  271. }
  272. }
  273. })
  274. const noSearchParam = url.indexOf('=')
  275. if (noSearchParam === -1) {
  276. url = url.replace(/\?/, '') // 如果已经没有参数,删除?号
  277. }
  278. return url
  279. }
  280. /**
  281. *
  282. *获取value的类型
  283. * @export
  284. * @param {*} value
  285. * @return {*} {String}
  286. */
  287. export function getType(value) {
  288. const type = Object.prototype.toString.call(value)
  289. return type.match(/\[object (.*)\]/)[1].toLowerCase()
  290. }
  291. /**
  292. *
  293. *是否无效值
  294. * @param {*} value
  295. */
  296. export const isVoid = (value) =>
  297. value === undefined || value === null || value === ''
  298. /**
  299. *
  300. *去除对象中的无效值
  301. * @param {*} object
  302. * @return {*}
  303. */
  304. export const validObject = (object) => {
  305. if (!object) {
  306. return {}
  307. }
  308. const result = { ...object }
  309. Object.keys(result).forEach((key) => {
  310. const value = result[key]
  311. if (isVoid(value)) {
  312. delete result[key]
  313. }
  314. })
  315. return result
  316. }
  317. export const encryptWithRsa = (string) => {
  318. let encrypt = new JSEncrypt()
  319. let key = window.eipRSAPublicKey
  320. if (!key) {
  321. key =
  322. 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMnhQ99yP-eEU2jXdQWc6j-wWbqNLqOLinEGBY11WJUCmzHiEycDXPc6-3YMOvrdAiHZcjkMCzU_eRnBLUqkcNw9nhQrCak-sTpEVlAV21LskD6KMf-6PsfttUvpXeCO5g3Hg48F_vbLKxb8s_lcvQgCpKBIpsUdYRcp_PgSg8BQIDAQAB'
  323. }
  324. encrypt.setPublicKey(key)
  325. return encrypt.encrypt(string)
  326. }