utils.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. import chinaMapJSON from '@/assets/js/china_area'
  2. import { NotURLPrefixRegExp } from '@/utils/constant'
  3. import { env, androidOrIOS } from '@/utils/prototype/modules/platform'
  4. import qs from 'qs'
  5. /*
  6. * 时间格式化函数(将时间格式化为,2019年08月12日,2019-08-12,2019/08/12的形式)
  7. * pattern参数(想要什么格式的数据就传入什么格式的数据)
  8. * · 'yyyy-MM-dd' ---> 输出如2019-09-20
  9. * · 'yyyy-MM-dd HH:mm' ---> 输出如2019-09-20 18:20
  10. * · 'yyyy-MM-dd HH:mm:ss' ---> 输出如2019-09-20 06:20:23
  11. * · 'yyyy/MM/dd' ---> 输出如2019/09/20
  12. * · 'yyyy年MM月dd日' ---> 输出如2019年09月20日
  13. * · 'yyyy年MM月dd日 HH时mm分' ---> 输出如2019年09月20日 18时20分
  14. * · 'yyyy年MM月dd日 HH时mm分ss秒' ---> 输出如2019年09月20日 18时20分23秒
  15. * · 'yyyy年MM月dd日 HH时mm分ss秒 EE' ---> 输出如2019年09月20日 18时20分23秒 周二
  16. * · 'yyyy年MM月dd日 HH时mm分ss秒 EEE' ---> 输出如2019年09月20日 18时20分23秒 星期二
  17. * 参考: https://www.cnblogs.com/mr-wuxiansheng/p/6296646.html
  18. */
  19. export function dateFormatter(date = '', fmt = 'yyyy-MM-dd HH:mm:ss') {
  20. // 将传入的date转为时间对象
  21. if (!date) return ''
  22. // 处理ios不兼容'2022-6-6'类似的'-'问题
  23. if (typeof data === 'string') {
  24. date = date.replace(/-/g, '/')
  25. }
  26. date = new Date(date)
  27. const o = {
  28. 'y+': date.getFullYear(),
  29. 'M+': date.getMonth() + 1, // 月份
  30. 'd+': date.getDate(), // 日
  31. // 12小时制
  32. 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
  33. // 24小时制
  34. 'H+': date.getHours(), // 小时
  35. 'm+': date.getMinutes(), // 分
  36. 's+': date.getSeconds(), // 秒
  37. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  38. S: date.getMilliseconds(), // 毫秒
  39. 'E+': date.getDay() // 周
  40. }
  41. const week = ['日', '一', '二', '三', '四', '五', '六']
  42. if (/(y+)/.test(fmt)) {
  43. fmt = fmt.replace(
  44. RegExp.$1,
  45. (date.getFullYear() + '').substr(4 - RegExp.$1.length)
  46. )
  47. }
  48. if (/(E+)/.test(fmt)) {
  49. fmt = fmt.replace(
  50. RegExp.$1,
  51. (RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '星期' : '周') : '') +
  52. week[date.getDay()]
  53. )
  54. }
  55. for (const k in o) {
  56. if (new RegExp('(' + k + ')').test(fmt)) {
  57. fmt = fmt.replace(
  58. RegExp.$1,
  59. RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
  60. )
  61. }
  62. }
  63. return fmt
  64. }
  65. // 金额处理
  66. // 分转元
  67. export function fen2Yuan(v) {
  68. if (!v) return 0
  69. return v / 100
  70. }
  71. // 元转分
  72. export function yuan2Fen(v) {
  73. return (v * 10000) / 100
  74. }
  75. // 金额大写,链接:https://juejin.im/post/5a2a7a5051882535cd4abfce
  76. // upDigit(1682) result:"人民币壹仟陆佰捌拾贰元整"
  77. // upDigit(-1693) result:"欠壹仟陆佰玖拾叁元整"
  78. export function upPrice(n) {
  79. const fraction = ['角', '分', '厘']
  80. const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  81. const unit = [
  82. ['元', '万', '亿'],
  83. ['', '拾', '佰', '仟']
  84. ]
  85. // const head = n < 0 ? '欠人民币' : '人民币'
  86. const head = ''
  87. n = Math.abs(n)
  88. let s = ''
  89. for (let i = 0; i < fraction.length; i++) {
  90. s += (
  91. digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]
  92. ).replace(/零./, '')
  93. }
  94. s = s || '整'
  95. n = Math.floor(n)
  96. for (let i = 0; i < unit[0].length && n > 0; i++) {
  97. let p = ''
  98. for (let j = 0; j < unit[1].length && n > 0; j++) {
  99. p = digit[n % 10] + unit[1][j] + p
  100. n = Math.floor(n / 10)
  101. }
  102. s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  103. // s = p + unit[0][i] + s;
  104. }
  105. return (
  106. head +
  107. s
  108. .replace(/(零.)*零元/, '元')
  109. .replace(/(零.)+/g, '零')
  110. .replace(/^整$/, '零元整')
  111. )
  112. }
  113. // 金额3位逗号分隔 ------------>
  114. /**
  115. * @param s 要格式化的数字(四舍五入)
  116. * @param n 保留几位小数(不传或者传-1 --> 如果为整数,则不保留小数。如果为浮点数,则保留两位小数)
  117. * @param comma 是否小数点前每3位添加逗号
  118. */
  119. export function newFormat(s = 0, n = -1, comma = false) {
  120. n = n === -1 ? 0 : n
  121. if (n > 20 || n < -1) {
  122. n = 2
  123. }
  124. s = Number(s)
  125. return s.toLocaleString('zh-CN', {
  126. style: 'decimal',
  127. useGrouping: comma,
  128. minimumFractionDigits: n,
  129. maximumFractionDigits: n
  130. })
  131. }
  132. export function formatPrice(s, n = -1, comma = false) {
  133. // 如果不传s或者s为空,则直接返回0
  134. if (!s) return 0
  135. if (n !== -1) n = n > 0 && n <= 20 ? n : 2
  136. const intS = parseInt(String(s))
  137. let point = '.'
  138. let left = []
  139. let right = ''
  140. s = parseFloat((s + '').replace(/[^\d.-]/g, ''))
  141. // 没传n或者n为-1,默认(如果为整数,则不保留小数。如果为浮点数,则保留两位小数)
  142. if (n === -1) {
  143. if (s === intS) {
  144. n = 0
  145. right = ''
  146. point = ''
  147. } else {
  148. n = 2
  149. s = s.toFixed(n)
  150. right = s.split('.')[1]
  151. }
  152. s = s + ''
  153. left = s.split('.')[0].split('').reverse()
  154. } else {
  155. s = parseFloat((s + '').replace(/[^\d.-]/g, '')).toFixed(n) + ''
  156. left = s.split('.')[0].split('').reverse()
  157. right = s.split('.')[1]
  158. }
  159. if (comma) {
  160. let t = ''
  161. for (let i = 0; i < left.length; i++) {
  162. t += left[i] + ((i + 1) % 3 === 0 && i + 1 !== left.length ? ',' : '')
  163. }
  164. return t.split('').reverse().join('') + point + right
  165. }
  166. return left.reverse().join('') + point + right
  167. }
  168. export const debounce = (func, delay = 200, immediate) => {
  169. let timer = null
  170. return function () {
  171. const context = this
  172. const args = arguments
  173. if (timer) clearTimeout(timer)
  174. if (immediate) {
  175. const doNow = !timer
  176. timer = setTimeout(function () {
  177. timer = null
  178. }, delay)
  179. if (doNow) {
  180. func.apply(context, args)
  181. }
  182. } else {
  183. timer = setTimeout(function () {
  184. func.apply(context, args)
  185. }, delay)
  186. }
  187. }
  188. }
  189. // 时间戳转换 多少秒、多少分、多少小时前、多少天前 超出10天显示年月日
  190. // 传入一个时间戳
  191. export function dateFromNow(originTime, useOld = false) {
  192. if (!originTime) return
  193. // 原始时间 - 传入的时间戳
  194. const originTimeStamp = +new Date(originTime)
  195. // 当前时间戳
  196. const nowTimeStamp = +new Date()
  197. // 时间戳相差多少
  198. const diffTimeStamp = nowTimeStamp - originTimeStamp
  199. const postfix = diffTimeStamp > 0 ? '前' : '后'
  200. // 求绝对值 ms(毫秒)
  201. const diffTimeStampAbsMs = Math.abs(diffTimeStamp)
  202. const diffTimeStampAbsS = Math.round(diffTimeStampAbsMs / 1000)
  203. // 10天的秒数
  204. const days11 = 11 * 24 * 60 * 60
  205. const dataMap = {
  206. zh: ['天', '小时', '分钟', '秒'],
  207. number: [24 * 60 * 60, 60 * 60, 60, 1]
  208. }
  209. let timeString = ''
  210. // 10天前
  211. const tenDaysAgo = diffTimeStampAbsS > days11
  212. // 是否是当天
  213. const isCurrentDay =
  214. dateFormatter(originTimeStamp, 'yyyy.MM.dd') ===
  215. dateFormatter(nowTimeStamp, 'yyyy.MM.dd')
  216. let condition = !isCurrentDay
  217. if (useOld) {
  218. condition = tenDaysAgo
  219. }
  220. if (condition) {
  221. // 不是当天,则使用正常日期显示
  222. const originDate = new Date(originTimeStamp)
  223. const nowDate = new Date()
  224. // 是否同年
  225. const sameYear = originDate.getFullYear() === nowDate.getFullYear()
  226. // 如果是当年,则不显示年
  227. const patternString = sameYear ? 'MM-dd' : 'yyyy-MM-dd'
  228. timeString = dateFormatter(originDate, patternString)
  229. } else {
  230. for (let i = 0; i < dataMap.number.length; i++) {
  231. const inm = Math.floor(diffTimeStampAbsS / dataMap.number[i])
  232. if (inm !== 0) {
  233. timeString = inm + dataMap.zh[i] + postfix
  234. break
  235. }
  236. }
  237. }
  238. return timeString
  239. }
  240. // 金额类型转换
  241. export function moneyUnit(m, type = 'string', lv = 0) {
  242. const mUnit = {
  243. levelArr: ['元', '万', '亿', '万亿'],
  244. test(num, type, lv) {
  245. if (num === 0) {
  246. if (type === 'string') {
  247. return '0元'
  248. }
  249. if (type === 'lv') {
  250. return this.levelArr[lv]
  251. }
  252. if (type === 'number') {
  253. return 0
  254. }
  255. if (type === 'index') {
  256. return lv
  257. }
  258. if (type === 'transfer') {
  259. return 0
  260. }
  261. }
  262. const result = num / Math.pow(10000, lv)
  263. if (result > 10000 && lv < 2) {
  264. return this.test(num, type, lv + 1)
  265. } else {
  266. if (type === 'string') {
  267. return (
  268. String(Math.floor(result * 100) / 100).replace('.00', '') +
  269. this.levelArr[lv]
  270. )
  271. }
  272. if (type === 'lv') {
  273. return this.levelArr[lv]
  274. }
  275. if (type === 'number') {
  276. return String(Math.floor(result * 100) / 100).replace('.00', '')
  277. }
  278. if (type === 'index') {
  279. return lv
  280. }
  281. }
  282. },
  283. // 需要传入固定的lv(此时lv为 levelArr 中的一个)
  284. transfer(num, lvString) {
  285. const index = this.levelArr.indexOf(lvString)
  286. if (index === -1 || index === 0) {
  287. return num
  288. } else {
  289. return (num / Math.pow(10000, index)).toFixed(2) + lvString
  290. }
  291. }
  292. }
  293. if (m === undefined || m === null) {
  294. return ''
  295. } else {
  296. if (type === 'transfer') {
  297. return mUnit.transfer(m, lv)
  298. } else {
  299. return mUnit.test(m, type, lv)
  300. }
  301. }
  302. }
  303. /**
  304. * 通用关键字高亮替换
  305. * @param {String} value 要高亮的字符串
  306. * @param {String|Array} oldChar 要被替换的字符串(或数组)
  307. * @param {String|Array} newChar 要替换成的字符串(或数组)
  308. *
  309. * 比如:要将 - `剑鱼标讯工具函数` 字符串中的 `工具` 高亮
  310. * 则此时 value -> `剑鱼标讯工具函数`
  311. * oldChar -> `工具`
  312. * newChar -> `<span class="highlight-text">工具</span>`
  313. *
  314. * 批量高亮-----
  315. * 比如:要将 - `剑鱼标讯工具函数` 字符串中的 `工具` `剑鱼` 高亮
  316. * 则此时 value -> `剑鱼标讯工具函数`批量高亮
  317. * oldChar -> ['工具', '剑鱼']
  318. * newChar -> ['<span class="highlight-text">', '</span>']
  319. *
  320. * 注意:此时newChar为一个长度为2的数组,数组中为高亮标签的起始标签和结束标签
  321. *
  322. */
  323. export function replaceKeyword(
  324. value,
  325. oldChar,
  326. newChar = ['<span class="highlight-text">', '</span>']
  327. ) {
  328. if (!oldChar || !newChar) return value
  329. // oldChar的字符串数组
  330. let oldCharArr = []
  331. if (Array.isArray(oldChar)) {
  332. oldCharArr = oldChar.concat()
  333. } else {
  334. oldCharArr.push(oldChar)
  335. }
  336. // 数组去重
  337. oldCharArr = Array.from(new Set(oldCharArr))
  338. for (let i = 0; i < oldCharArr.length; i++) {
  339. if (!oldCharArr[i]) {
  340. continue
  341. } else {
  342. oldCharArr[i] = oldCharArr[i]
  343. .replace(/([$()*+.[\]?/\\^{}|])/g, '\\$1')
  344. .replace(/\s+/g, '')
  345. }
  346. }
  347. // 数组去空
  348. const lastArr = oldCharArr
  349. .filter((item) => !!item)
  350. .sort((a, b) => b.length - a.length)
  351. const regExp = new RegExp(`(${lastArr.join('|')})`, 'gmi')
  352. if (lastArr.length === 0) {
  353. return value
  354. }
  355. if (Array.isArray(newChar)) {
  356. // 批量高亮
  357. return value.replace(regExp, newChar.join('$1'))
  358. } else {
  359. // 普通单个高亮
  360. return value.replace(regExp, newChar)
  361. }
  362. }
  363. // 获取随机字符串
  364. // 不传参数则获取长度不固定的字符串
  365. export const getRandomString = (len) => {
  366. let randomString = ''
  367. if (len) {
  368. /** 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1 **/
  369. const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  370. const maxPos = $chars.length
  371. for (let i = 0; i < len; i++) {
  372. randomString += $chars.charAt(Math.floor(Math.random() * maxPos))
  373. }
  374. } else {
  375. // Math.random() 生成随机数字, eg: 0.123456
  376. // .toString(36) 转化成36进制 : "0.4fzyo82mvyr"
  377. // .substring(2) 去掉前面两位 : "yo82mvyr"
  378. // .slice(-8) 截取最后八位 : "yo82mvyr"
  379. randomString = Math.random().toString(36).substring(2)
  380. }
  381. return randomString
  382. }
  383. // 随机整数 min <= X <= max
  384. export const getRandomNumber = (min, max) => {
  385. return Math.round(Math.random() * (max - min)) + min
  386. }
  387. export const copyText = async function (text) {
  388. try {
  389. await navigator.clipboard.writeText(text)
  390. } catch (error) {
  391. const input = document.createElement('input') // js创建一个input输入框
  392. input.value = text // 将需要复制的文本赋值到创建的input输入框中
  393. document.body.appendChild(input) // 将输入框暂时创建到实例里面
  394. input.select() // 选中输入框中的内容
  395. document.execCommand('copy') // 执行复制操作
  396. document.body.removeChild(input) // 最后删除实例中临时创建的input输入框,完成复制操作
  397. }
  398. }
  399. // FROM: https://www.jianshu.com/p/90ed8b728975
  400. // 比较两个对象是否相等
  401. // 返回true为相等,返回false为不相等
  402. /* eslint-disable */
  403. export const deepCompare = function (x, y) {
  404. let i, l, leftChain, rightChain
  405. function compare2Objects(x, y) {
  406. let p
  407. // remember that NaN === NaN returns false
  408. // and isNaN(undefined) returns true
  409. if (
  410. isNaN(x) &&
  411. isNaN(y) &&
  412. typeof x === 'number' &&
  413. typeof y === 'number'
  414. ) {
  415. return true
  416. }
  417. // Compare primitives and functions.
  418. // Check if both arguments link to the same object.
  419. // Especially useful on the step where we compare prototypes
  420. if (x === y) {
  421. return true
  422. }
  423. // Works in case when functions are created in constructor.
  424. // Comparing dates is a common scenario. Another built-ins?
  425. // We can even handle functions passed across iframes
  426. if (
  427. (typeof x === 'function' && typeof y === 'function') ||
  428. (x instanceof Date && y instanceof Date) ||
  429. (x instanceof RegExp && y instanceof RegExp) ||
  430. (x instanceof String && y instanceof String) ||
  431. (x instanceof Number && y instanceof Number)
  432. ) {
  433. return x.toString() === y.toString()
  434. }
  435. // At last checking prototypes as good as we can
  436. if (!(x instanceof Object && y instanceof Object)) {
  437. return false
  438. }
  439. // eslint-disable-next-line no-prototype-builtins
  440. if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
  441. return false
  442. }
  443. if (x.constructor !== y.constructor) {
  444. return false
  445. }
  446. if (x.prototype !== y.prototype) {
  447. return false
  448. }
  449. // Check for infinitive linking loops
  450. if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
  451. return false
  452. }
  453. // Quick checking of one object being a subset of another.
  454. // todo: cache the structure of arguments[0] for performance
  455. for (p in y) {
  456. // eslint-disable-next-line no-prototype-builtins
  457. if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
  458. return false
  459. } else if (typeof y[p] !== typeof x[p]) {
  460. return false
  461. }
  462. }
  463. for (p in x) {
  464. // eslint-disable-next-line no-prototype-builtins
  465. if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
  466. return false
  467. } else if (typeof y[p] !== typeof x[p]) {
  468. return false
  469. }
  470. switch (typeof x[p]) {
  471. case 'object':
  472. case 'function':
  473. leftChain.push(x)
  474. rightChain.push(y)
  475. if (!compare2Objects(x[p], y[p])) {
  476. return false
  477. }
  478. leftChain.pop()
  479. rightChain.pop()
  480. break
  481. default:
  482. if (x[p] !== y[p]) {
  483. return false
  484. }
  485. break
  486. }
  487. }
  488. return true
  489. }
  490. if (arguments.length < 1) {
  491. return true // Die silently? Don't know how to handle such case, please help...
  492. // throw "Need two or more arguments to compare";
  493. }
  494. for (i = 1, l = arguments.length; i < l; i++) {
  495. leftChain = [] // Todo: this can be cached
  496. rightChain = []
  497. if (!compare2Objects(arguments[0], arguments[i])) {
  498. return false
  499. }
  500. }
  501. return true
  502. }
  503. /* eslint-disable */
  504. // 保留几位小数
  505. /* eslint-disable */
  506. Number.prototype.fixed = function (len) {
  507. len = isNaN(len) ? 0 : len
  508. const num = Math.pow(10, len)
  509. return Math.round(this * num) / num
  510. }
  511. /* eslint-disable */
  512. // 计算时间间隔差函数 [年个数, 月个数]
  513. export const getDateSub = function (start, end) {
  514. let startTime = new Date(start * 1000)
  515. let endTime = new Date(end * 1000)
  516. let startYear = startTime.getFullYear()
  517. let startMonth = startTime.getMonth()
  518. let startDay = startTime.getDate()
  519. let endYear = endTime.getFullYear()
  520. let endMonth = endTime.getMonth()
  521. let endDay = endTime.getDate()
  522. let finalMonthNum = 0
  523. let finalYearNum = 0
  524. if (startYear === endYear) {
  525. if (startMonth === endMonth) {
  526. finalMonthNum = 1
  527. } else {
  528. if (endDay > startDay) {
  529. finalMonthNum = endMonth - startMonth + 1
  530. } else {
  531. finalMonthNum = endMonth - startMonth
  532. }
  533. }
  534. } else {
  535. if (startMonth === endMonth) {
  536. if (endDay <= startDay) {
  537. finalMonthNum = (endYear - startYear) * 12
  538. } else {
  539. finalMonthNum = (endYear - startYear) * 12 + 1
  540. }
  541. } else if (endMonth > startMonth) {
  542. if (endDay <= startDay) {
  543. finalMonthNum = (endYear - startYear) * 12 + (endMonth - startMonth)
  544. } else {
  545. finalMonthNum = (endYear - startYear) * 12 + (endMonth - startMonth) + 1
  546. }
  547. } else {
  548. if (endDay <= startDay) {
  549. finalMonthNum =
  550. (endYear - startYear - 1) * 12 + (12 - startMonth + endMonth)
  551. } else {
  552. finalMonthNum =
  553. (endYear - startYear - 1) * 12 + (12 - startMonth + endMonth) + 1
  554. }
  555. }
  556. finalYearNum = Math.floor(finalMonthNum / 12)
  557. if (finalYearNum > 0) {
  558. finalMonthNum = finalMonthNum - finalYearNum * 12
  559. }
  560. }
  561. return [finalYearNum, finalMonthNum]
  562. }
  563. export function recoveryPageData(key, defaultValues = {}) {
  564. return JSON.parse(localStorage.getItem(key) || JSON.stringify(defaultValues))
  565. }
  566. export function defaultLocalPageData(key, defaultValues = {}) {
  567. return JSON.parse(localStorage.getItem(key) || JSON.stringify(defaultValues))
  568. }
  569. export function getPic(link) {
  570. if (NotURLPrefixRegExp.test(link)) {
  571. return import.meta.env.VITE_APP_IMAGE_BASE + link
  572. }
  573. return link
  574. }
  575. // 通过公司全称截取短名称
  576. export function getShortName(comName) {
  577. const areaMap = chinaMapJSON || []
  578. let shortName = comName
  579. // 1. 循环省份城市进行替换
  580. areaMap.forEach(function (item) {
  581. const p = item.name.replace(/[省市]/, '')
  582. if (shortName.indexOf(p) !== -1) {
  583. shortName = shortName.replace(item.name, '').replace(p, '')
  584. }
  585. item.city.forEach(function (iitem) {
  586. const c = iitem.name.replace(/[省市]/, '')
  587. if (shortName.indexOf(c) !== -1) {
  588. shortName = shortName.replace(iitem.name, '').replace(c, '')
  589. }
  590. iitem.area.forEach(function (iiitem) {
  591. if (shortName.indexOf(iiitem) !== -1) {
  592. shortName = shortName.replace(iiitem, '')
  593. }
  594. })
  595. })
  596. })
  597. const matchRes = shortName.match(/[\u4e00-\u9fa5]{4}/gm)
  598. let name = matchRes ? matchRes[0] : shortName.slice(0, 4)
  599. if (name.length < 4) {
  600. name = name.slice(0, 4)
  601. }
  602. return name
  603. }
  604. /**
  605. * 分发函数到$refs子组件
  606. * @param fnName 函数名称
  607. * @param config 配置
  608. * @param config.params 参数或获取参数的函数
  609. * @param config.default 找不到子组件函数时默认函数
  610. */
  611. export function transferMethodsOfRefs(fnName, config) {
  612. const defaultConfig = Object.assign(
  613. {
  614. default: () => {}
  615. },
  616. config
  617. )
  618. let params = defaultConfig?.params
  619. if (typeof params !== 'undefined') {
  620. params =
  621. typeof defaultConfig?.params === 'function'
  622. ? defaultConfig?.params()
  623. : defaultConfig?.params
  624. }
  625. Object.keys(this.$refs).forEach((v) => {
  626. if (!this.$refs[v]) {
  627. console.warn(`Error: 分发${fnName}事件到子组件错误 没有找到组件实例`)
  628. return defaultConfig.default(params)
  629. }
  630. const tempFn = this.$refs[v][fnName]
  631. if (typeof tempFn === 'function') {
  632. try {
  633. tempFn(params)
  634. } catch (e) {
  635. console.warn(`Error: 分发${fnName}事件到子组件错误`, e)
  636. defaultConfig.default(params)
  637. }
  638. } else {
  639. defaultConfig.default(params)
  640. }
  641. })
  642. }
  643. /**
  644. * 获取 URL + Query 拼接后的链接
  645. * @param link
  646. * @param query
  647. * @returns {string}
  648. */
  649. export function getFormatURL(link, query = {}) {
  650. const queryStr = qs.stringify(query) || ''
  651. const queryArr = [link]
  652. if (queryStr) {
  653. queryArr.push(queryStr)
  654. }
  655. return queryArr.join('?')
  656. }
  657. /**
  658. * 返回对象指定的keys
  659. * @param obj
  660. * @param keys 需要匹配的Key
  661. * @param exclude 是否使用排除模式,默认采用 include 匹配
  662. * @returns {{}}
  663. */
  664. export function filterObjOfKeys(obj, keys = [], exclude = false) {
  665. const result = {}
  666. let needKeys = Object.keys(obj)
  667. if (exclude) {
  668. needKeys = needKeys.filter((v) => !keys.includes(v))
  669. } else if (keys.length) {
  670. needKeys = [].concat(keys)
  671. }
  672. needKeys.forEach((v) => (result[v] = obj[v]))
  673. return result
  674. }
  675. /**
  676. * 获取IOS版本号
  677. * @returns {number}
  678. * @constructor
  679. */
  680. export function IosVersion() {
  681. let result = 0
  682. try {
  683. result = navigator.userAgent
  684. .toLowerCase()
  685. .match(/cpu iphone os (.*?) like mac os/)[1]
  686. .replace(/_/g, '.')
  687. } catch (e) {
  688. console.warn(e)
  689. }
  690. return result
  691. }
  692. /**
  693. * 获取url中的参数
  694. * @returns {String} url
  695. */
  696. export function resolveUrlQueryParams(url) {
  697. const map = {}
  698. if (!url) return map
  699. const query = url.split('?')[1]
  700. if (!query) return map
  701. return qs.parse(query)
  702. }
  703. /**
  704. * ios版本是否小于14
  705. * 即ios13以及ios13以下版本
  706. * @returns {boolean}
  707. */
  708. export function iOSVersionLt14() {
  709. return androidOrIOS() === 'ios' && String(IosVersion()).split('.')[0] < 14
  710. }
  711. /**
  712. * 上报荟聚埋点数据
  713. * @param trackInfo
  714. * @param trackInfo.id - 事件ID (必须提前在荟聚后台定义ID)
  715. * @param trackInfo.date - 事件时间
  716. * @param trackInfo.data - 事件自定义属性
  717. */
  718. export function setTrack(trackInfo) {
  719. const { id = 'c_jyclick', data = {} } = trackInfo
  720. try {
  721. clab_tracker.track(
  722. id,
  723. Object.assign(
  724. {},
  725. {
  726. c_platform: env.platform,
  727. date: new Date()
  728. },
  729. data
  730. )
  731. )
  732. } catch (e) {
  733. console.warn(e)
  734. }
  735. }
  736. // ios或者h5返回回调
  737. export function iosBackInvoke(callback) {
  738. let isPageHide = false
  739. window.addEventListener('pageshow', function () {
  740. if (isPageHide) {
  741. callback && callback()
  742. }
  743. })
  744. window.addEventListener('pagehide', function () {
  745. isPageHide = true
  746. })
  747. }
  748. // ios或者h5返回刷新
  749. export function iosBackRefresh() {
  750. iosBackInvoke(() => {
  751. location.reload()
  752. })
  753. }
  754. // 此函数仅仅在h5下会被执行
  755. export function fixH5BackRefresh() {
  756. const ua = navigator.userAgent.toLowerCase()
  757. // 判断是不是华为/荣耀浏览器
  758. const huawei = ua.includes('huawei') || ua.includes('honor')
  759. if (huawei) {
  760. window.addEventListener('visibilitychange', function () {
  761. const v = document.visibilityState
  762. if (v === 'hidden') {
  763. // do something
  764. } else if (v === 'visible') {
  765. location.reload()
  766. }
  767. })
  768. } else {
  769. iosBackRefresh()
  770. }
  771. }
  772. // vite动态获取图片
  773. export function getAssetsFile(url) {
  774. return new URL(`../assets/image/${url}`, import.meta.url).href
  775. }