47804a47cf5bef73ac1f47d0dfd9d4fbaf4b6058.svn-base 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /**
  2. * Created by PanJiaChen on 16/11/18.
  3. */
  4. /**
  5. * Parse the time to string
  6. * @param {(Object|string|number)} time
  7. * @param {string} cFormat
  8. * @returns {string}
  9. */
  10. export function parseTime(time, cFormat) {
  11. if (arguments.length === 0) {
  12. return null
  13. }
  14. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  15. let date
  16. if (typeof time === 'object') {
  17. date = time
  18. } else {
  19. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  20. time = parseInt(time)
  21. }
  22. if ((typeof time === 'number') && (time.toString().length === 10)) {
  23. time = time * 1000
  24. }
  25. date = new Date(time)
  26. }
  27. const formatObj = {
  28. y: date.getFullYear(),
  29. m: date.getMonth() + 1,
  30. d: date.getDate(),
  31. h: date.getHours(),
  32. i: date.getMinutes(),
  33. s: date.getSeconds(),
  34. a: date.getDay()
  35. }
  36. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  37. let value = formatObj[key]
  38. // Note: getDay() returns 0 on Sunday
  39. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
  40. if (result.length > 0 && value < 10) {
  41. value = '0' + value
  42. }
  43. return value || 0
  44. })
  45. return time_str
  46. }
  47. /**
  48. * @param {number} time
  49. * @param {string} 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. * @param {string} url
  89. * @returns {Object}
  90. */
  91. export function getQueryObject(url) {
  92. url = url == null ? window.location.href : url
  93. const search = url.substring(url.lastIndexOf('?') + 1)
  94. const obj = {}
  95. const reg = /([^?&=]+)=([^?&=]*)/g
  96. search.replace(reg, (rs, $1, $2) => {
  97. const name = decodeURIComponent($1)
  98. let val = decodeURIComponent($2)
  99. val = String(val)
  100. obj[name] = val
  101. return rs
  102. })
  103. return obj
  104. }
  105. /**
  106. * @param {string} input value
  107. * @returns {number} output value
  108. */
  109. export function byteLength(str) {
  110. // returns the byte length of an utf8 string
  111. let s = str.length
  112. for (var i = str.length - 1; i >= 0; i--) {
  113. const code = str.charCodeAt(i)
  114. if (code > 0x7f && code <= 0x7ff) s++
  115. else if (code > 0x7ff && code <= 0xffff) s += 2
  116. if (code >= 0xDC00 && code <= 0xDFFF) i--
  117. }
  118. return s
  119. }
  120. /**
  121. * @param {Array} actual
  122. * @returns {Array}
  123. */
  124. export function cleanArray(actual) {
  125. const newArray = []
  126. for (let i = 0; i < actual.length; i++) {
  127. if (actual[i]) {
  128. newArray.push(actual[i])
  129. }
  130. }
  131. return newArray
  132. }
  133. /**
  134. * @param {Object} json
  135. * @returns {Array}
  136. */
  137. export function param(json) {
  138. if (!json) return ''
  139. return cleanArray(
  140. Object.keys(json).map(key => {
  141. if (json[key] === undefined) return ''
  142. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  143. })
  144. ).join('&')
  145. }
  146. /**
  147. * @param {string} url
  148. * @returns {Object}
  149. */
  150. export function param2Obj(url) {
  151. const search = url.split('?')[1]
  152. if (!search) {
  153. return {}
  154. }
  155. return JSON.parse(
  156. '{"' +
  157. decodeURIComponent(search)
  158. .replace(/"/g, '\\"')
  159. .replace(/&/g, '","')
  160. .replace(/=/g, '":"')
  161. .replace(/\+/g, ' ') +
  162. '"}'
  163. )
  164. }
  165. /**
  166. * @param {string} val
  167. * @returns {string}
  168. */
  169. export function html2Text(val) {
  170. const div = document.createElement('div')
  171. div.innerHTML = val
  172. return div.textContent || div.innerText
  173. }
  174. /**
  175. * Merges two objects, giving the last one precedence
  176. * @param {Object} target
  177. * @param {(Object|Array)} source
  178. * @returns {Object}
  179. */
  180. export function objectMerge(target, source) {
  181. if (typeof target !== 'object') {
  182. target = {}
  183. }
  184. if (Array.isArray(source)) {
  185. return source.slice()
  186. }
  187. Object.keys(source).forEach(property => {
  188. const sourceProperty = source[property]
  189. if (typeof sourceProperty === 'object') {
  190. target[property] = objectMerge(target[property], sourceProperty)
  191. } else {
  192. target[property] = sourceProperty
  193. }
  194. })
  195. return target
  196. }
  197. /**
  198. * @param {HTMLElement} element
  199. * @param {string} className
  200. */
  201. export function toggleClass(element, className) {
  202. if (!element || !className) {
  203. return
  204. }
  205. let classString = element.className
  206. const nameIndex = classString.indexOf(className)
  207. if (nameIndex === -1) {
  208. classString += '' + className
  209. } else {
  210. classString =
  211. classString.substr(0, nameIndex) +
  212. classString.substr(nameIndex + className.length)
  213. }
  214. element.className = classString
  215. }
  216. /**
  217. * @param {string} type
  218. * @returns {Date}
  219. */
  220. export function getTime(type) {
  221. if (type === 'start') {
  222. return new Date().getTime() - 3600 * 1000 * 24 * 90
  223. } else {
  224. return new Date(new Date().toDateString())
  225. }
  226. }
  227. /**
  228. * @param {Function} func
  229. * @param {number} wait
  230. * @param {boolean} immediate
  231. * @return {*}
  232. */
  233. export function debounce(func, wait, immediate) {
  234. let timeout, args, context, timestamp, result
  235. const later = function() {
  236. // 据上一次触发时间间隔
  237. const last = +new Date() - timestamp
  238. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  239. if (last < wait && last > 0) {
  240. timeout = setTimeout(later, wait - last)
  241. } else {
  242. timeout = null
  243. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  244. if (!immediate) {
  245. result = func.apply(context, args)
  246. if (!timeout) context = args = null
  247. }
  248. }
  249. }
  250. return function(...args) {
  251. context = this
  252. timestamp = +new Date()
  253. const callNow = immediate && !timeout
  254. // 如果延时不存在,重新设定延时
  255. if (!timeout) timeout = setTimeout(later, wait)
  256. if (callNow) {
  257. result = func.apply(context, args)
  258. context = args = null
  259. }
  260. return result
  261. }
  262. }
  263. /**
  264. * This is just a simple version of deep copy
  265. * Has a lot of edge cases bug
  266. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  267. * @param {Object} source
  268. * @returns {Object}
  269. */
  270. export function deepClone(source) {
  271. if (!source && typeof source !== 'object') {
  272. throw new Error('error arguments', 'deepClone')
  273. }
  274. const targetObj = source.constructor === Array ? [] : {}
  275. Object.keys(source).forEach(keys => {
  276. if (source[keys] && typeof source[keys] === 'object') {
  277. targetObj[keys] = deepClone(source[keys])
  278. } else {
  279. targetObj[keys] = source[keys]
  280. }
  281. })
  282. return targetObj
  283. }
  284. /**
  285. * @param {Array} arr
  286. * @returns {Array}
  287. */
  288. export function uniqueArr(arr) {
  289. return Array.from(new Set(arr))
  290. }
  291. /**
  292. * @returns {string}
  293. */
  294. export function createUniqueString() {
  295. const timestamp = +new Date() + ''
  296. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  297. return (+(randomNum + timestamp)).toString(32)
  298. }
  299. /**
  300. * Check if an element has a class
  301. * @param {HTMLElement} elm
  302. * @param {string} cls
  303. * @returns {boolean}
  304. */
  305. export function hasClass(ele, cls) {
  306. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  307. }
  308. /**
  309. * Add class to element
  310. * @param {HTMLElement} elm
  311. * @param {string} cls
  312. */
  313. export function addClass(ele, cls) {
  314. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  315. }
  316. /**
  317. * Remove class from element
  318. * @param {HTMLElement} elm
  319. * @param {string} cls
  320. */
  321. export function removeClass(ele, cls) {
  322. if (hasClass(ele, cls)) {
  323. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  324. ele.className = ele.className.replace(reg, ' ')
  325. }
  326. }
  327. /**
  328. * Parse the json to excel
  329. * tableJson 导出数据 ; filenames导出表的名字; autowidth表格宽度自动 true or false; bookTypes xlsx & csv & txt
  330. * @param {(Object)} tableJson
  331. * @param {string} filenames
  332. * @param {boolean} autowidth
  333. * @param {string} bookTypes
  334. */
  335. export function json2excel(tableJson, filenames, autowidth, bookTypes) {
  336. import('@/vendor/Export2Excel').then(excel => {
  337. var tHeader = []
  338. var dataArr = []
  339. var sheetnames = []
  340. for (var i in tableJson) {
  341. tHeader.push(tableJson[i].tHeader)
  342. dataArr.push(formatJson(tableJson[i].filterVal, tableJson[i].tableDatas))
  343. sheetnames.push(tableJson[i].sheetName)
  344. }
  345. excel.export_json_to_excel2({
  346. header: tHeader,
  347. data: dataArr,
  348. sheetname: sheetnames,
  349. filename: filenames,
  350. autoWidth: autowidth,
  351. bookType: bookTypes
  352. })
  353. })
  354. }
  355. // 数据过滤,时间过滤
  356. function formatJson(filterVal, jsonData) {
  357. return jsonData.map(v =>
  358. filterVal.map(j => {
  359. if (j === 'timestamp') {
  360. return parseTime(v[j])
  361. } else {
  362. return v[j]
  363. }
  364. })
  365. )
  366. }