index.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import api from '../http/api/settings'
  2. import provider from '../http/api/provider'
  3. /**
  4. * 格式化时间为指定的格式
  5. * @param {(Object|string|number)} time 指定时间
  6. * @param {string} cFormat 指定格式,如:{y}-{m}-{d} {h}:{i}:{s}
  7. * @returns {string | null}
  8. */
  9. export function parseTime(time, cFormat) {
  10. if (arguments.length === 0 || !time) {
  11. return null
  12. }
  13. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  14. let date
  15. if (typeof time === 'object') {
  16. date = time
  17. } else {
  18. if ((typeof time === 'string')) {
  19. if ((/^[0-9]+$/.test(time))) {
  20. // support "1548221490638"
  21. time = parseInt(time)
  22. } else {
  23. // support safari
  24. // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
  25. time = time.replace(new RegExp(/-/gm), '/')
  26. }
  27. }
  28. if ((typeof time === 'number') && (time.toString().length === 10)) {
  29. time = time * 1000
  30. }
  31. date = new Date(time)
  32. }
  33. const formatObj = {
  34. y: date.getFullYear(),
  35. m: date.getMonth() + 1,
  36. d: date.getDate(),
  37. h: date.getHours(),
  38. i: date.getMinutes(),
  39. s: date.getSeconds(),
  40. a: date.getDay()
  41. }
  42. const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
  43. const value = formatObj[key]
  44. // Note: getDay() returns 0 on Sunday
  45. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
  46. return value.toString().padStart(2, '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 = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  155. if (!search) {
  156. return {}
  157. }
  158. const obj = {}
  159. const searchArr = search.split('&')
  160. searchArr.forEach(v => {
  161. const index = v.indexOf('=')
  162. if (index !== -1) {
  163. const name = v.substring(0, index)
  164. const val = v.substring(index + 1, v.length)
  165. obj[name] = val
  166. }
  167. })
  168. return obj
  169. }
  170. /**
  171. * @param {string} val
  172. * @returns {string}
  173. */
  174. export function html2Text(val) {
  175. const div = document.createElement('div')
  176. div.innerHTML = val
  177. return div.textContent || div.innerText
  178. }
  179. /**
  180. * Merges two objects, giving the last one precedence
  181. * @param {Object} target
  182. * @param {(Object|Array)} source
  183. * @returns {Object}
  184. */
  185. export function objectMerge(target, source) {
  186. if (typeof target !== 'object') {
  187. target = {}
  188. }
  189. if (Array.isArray(source)) {
  190. return source.slice()
  191. }
  192. Object.keys(source).forEach(property => {
  193. const sourceProperty = source[property]
  194. if (typeof sourceProperty === 'object') {
  195. target[property] = objectMerge(target[property], sourceProperty)
  196. } else {
  197. target[property] = sourceProperty
  198. }
  199. })
  200. return target
  201. }
  202. /**
  203. * @param {HTMLElement} element
  204. * @param {string} className
  205. */
  206. export function toggleClass(element, className) {
  207. if (!element || !className) {
  208. return
  209. }
  210. let classString = element.className
  211. const nameIndex = classString.indexOf(className)
  212. if (nameIndex === -1) {
  213. classString += '' + className
  214. } else {
  215. classString =
  216. classString.substr(0, nameIndex) +
  217. classString.substr(nameIndex + className.length)
  218. }
  219. element.className = classString
  220. }
  221. /**
  222. * @param {string} type
  223. * @returns {Date}
  224. */
  225. export function getTime(type) {
  226. if (type === 'start') {
  227. return new Date().getTime() - 3600 * 1000 * 24 * 90
  228. } else {
  229. return new Date(new Date().toDateString())
  230. }
  231. }
  232. /**
  233. * @param {Function} func
  234. * @param {number} wait
  235. * @param {boolean} immediate
  236. * @return {*}
  237. */
  238. export function debounce(func, wait, immediate) {
  239. let timeout, args, context, timestamp, result
  240. const later = function() {
  241. // 据上一次触发时间间隔
  242. const last = +new Date() - timestamp
  243. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  244. if (last < wait && last > 0) {
  245. timeout = setTimeout(later, wait - last)
  246. } else {
  247. timeout = null
  248. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  249. if (!immediate) {
  250. result = func.apply(context, args)
  251. if (!timeout) context = args = null
  252. }
  253. }
  254. }
  255. return function(...args) {
  256. context = this
  257. timestamp = +new Date()
  258. const callNow = immediate && !timeout
  259. // 如果延时不存在,重新设定延时
  260. if (!timeout) timeout = setTimeout(later, wait)
  261. if (callNow) {
  262. result = func.apply(context, args)
  263. context = args = null
  264. }
  265. return result
  266. }
  267. }
  268. /**
  269. * This is just a simple version of deep copy
  270. * Has a lot of edge cases bug
  271. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  272. * @param {Object} source
  273. * @returns {Object}
  274. */
  275. export function deepClone(source) {
  276. if (!source && typeof source !== 'object') {
  277. throw new Error('error arguments', 'deepClone')
  278. }
  279. const targetObj = source.constructor === Array ? [] : {}
  280. Object.keys(source).forEach(keys => {
  281. if (source[keys] && typeof source[keys] === 'object') {
  282. targetObj[keys] = deepClone(source[keys])
  283. } else {
  284. targetObj[keys] = source[keys]
  285. }
  286. })
  287. return targetObj
  288. }
  289. /**
  290. * @param {Array} arr
  291. * @returns {Array}
  292. */
  293. export function uniqueArr(arr) {
  294. return Array.from(new Set(arr))
  295. }
  296. /**
  297. * @returns {string}
  298. */
  299. export function createUniqueString() {
  300. const timestamp = +new Date() + ''
  301. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  302. return (+(randomNum + timestamp)).toString(32)
  303. }
  304. /**
  305. * Check if an element has a class
  306. * @param {HTMLElement} elm
  307. * @param {string} cls
  308. * @returns {boolean}
  309. */
  310. export function hasClass(ele, cls) {
  311. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  312. }
  313. /**
  314. * Add class to element
  315. * @param {HTMLElement} elm
  316. * @param {string} cls
  317. */
  318. export function addClass(ele, cls) {
  319. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  320. }
  321. /**
  322. * Remove class from element
  323. * @param {HTMLElement} elm
  324. * @param {string} cls
  325. */
  326. export function removeClass(ele, cls) {
  327. if (hasClass(ele, cls)) {
  328. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  329. ele.className = ele.className.replace(reg, ' ')
  330. }
  331. }
  332. export function getCountryList(back) {
  333. var list = sessionStorage.getItem("COUNTRY-CALLING-DATA");
  334. if (list) {
  335. list = JSON.parse(list)
  336. if (list && list.length) {
  337. back(list);
  338. return;
  339. }
  340. }
  341. api.getCountryList().then(res => {
  342. if (res.data && res.data.length) {
  343. res.data.forEach(item => {
  344. const code = item.callingCode;
  345. item.callingCode = "" + code;
  346. })
  347. sessionStorage.setItem("COUNTRY-CALLING-DATA", JSON.stringify(res.data))
  348. back(res.data)
  349. }
  350. }).catch(err => {
  351. })
  352. }
  353. export function getServiceProviderOptions(back) {
  354. if (!back) return;
  355. provider.getAllServiceProvider().then(res => {
  356. if (res.data && res.data.length > 0) {
  357. const list = []
  358. res.data.forEach(item => {
  359. if (item.providerName) {
  360. list.push({
  361. providerPk: item.providerPk,
  362. providerName: item.providerName
  363. })
  364. } else if (item.key) {
  365. list.push({
  366. tenantId: item.tenantId,
  367. providerPk: item.value,
  368. providerName: item.key
  369. })
  370. }
  371. });
  372. back(list);
  373. } else {
  374. back([]);
  375. }
  376. }).catch(err => {
  377. this.$message.error(err);
  378. back([]);
  379. })
  380. }