index.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import { toNumber } from 'lodash-es'
  2. /**
  3. *
  4. * @param component 需要注册的组件
  5. * @param alias 组件别名
  6. * @returns any
  7. */
  8. export const withInstall = <T>(component: T, alias?: string) => {
  9. const comp = component as any
  10. comp.install = (app: any) => {
  11. app.component(comp.name || comp.displayName, component)
  12. if (alias) {
  13. app.config.globalProperties[alias] = component
  14. }
  15. }
  16. return component as T & Plugin
  17. }
  18. /**
  19. * @param str 需要转下划线的驼峰字符串
  20. * @returns 字符串下划线
  21. */
  22. export const humpToUnderline = (str: string): string => {
  23. return str.replace(/([A-Z])/g, '-$1').toLowerCase()
  24. }
  25. /**
  26. * @param str 需要转驼峰的下划线字符串
  27. * @returns 字符串驼峰
  28. */
  29. export const underlineToHump = (str: string): string => {
  30. if (!str) return ''
  31. return str.replace(/\-(\w)/g, (_, letter: string) => {
  32. return letter.toUpperCase()
  33. })
  34. }
  35. /**
  36. * 驼峰转横杠
  37. */
  38. export const humpToDash = (str: string): string => {
  39. return str.replace(/([A-Z])/g, '-$1').toLowerCase()
  40. }
  41. export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
  42. dom.style.setProperty(prop, val)
  43. }
  44. /**
  45. * 查找数组对象的某个下标
  46. * @param {Array} ary 查找的数组
  47. * @param {Functon} fn 判断的方法
  48. */
  49. // eslint-disable-next-line
  50. export const findIndex = <T = Recordable>(ary: Array<T>, fn: Fn): number => {
  51. if (ary.findIndex) {
  52. return ary.findIndex(fn)
  53. }
  54. let index = -1
  55. ary.some((item: T, i: number, ary: Array<T>) => {
  56. const ret: T = fn(item, i, ary)
  57. if (ret) {
  58. index = i
  59. return ret
  60. }
  61. })
  62. return index
  63. }
  64. export const trim = (str: string) => {
  65. return str.replace(/(^\s*)|(\s*$)/g, '')
  66. }
  67. /**
  68. * @param {Date | number | string} time 需要转换的时间
  69. * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
  70. */
  71. export function formatTime(time: Date | number | string, fmt: string) {
  72. if (!time) return ''
  73. else {
  74. const date = new Date(time)
  75. const o = {
  76. 'M+': date.getMonth() + 1,
  77. 'd+': date.getDate(),
  78. 'H+': date.getHours(),
  79. 'm+': date.getMinutes(),
  80. 's+': date.getSeconds(),
  81. 'q+': Math.floor((date.getMonth() + 3) / 3),
  82. S: date.getMilliseconds()
  83. }
  84. if (/(y+)/.test(fmt)) {
  85. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  86. }
  87. for (const k in o) {
  88. if (new RegExp('(' + k + ')').test(fmt)) {
  89. fmt = fmt.replace(
  90. RegExp.$1,
  91. RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
  92. )
  93. }
  94. }
  95. return fmt
  96. }
  97. }
  98. /**
  99. * 生成随机字符串
  100. */
  101. export function toAnyString() {
  102. const str: string = 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'.replace(/[xy]/g, (c: string) => {
  103. const r: number = (Math.random() * 16) | 0
  104. const v: number = c === 'x' ? r : (r & 0x3) | 0x8
  105. return v.toString()
  106. })
  107. return str
  108. }
  109. /**
  110. * 生成指定长度的随机字符串
  111. *
  112. * @param length 字符串长度
  113. */
  114. export function generateRandomStr(length: number): string {
  115. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  116. let result = ''
  117. for (let i = 0; i < length; i++) {
  118. result += chars.charAt(Math.floor(Math.random() * chars.length))
  119. }
  120. return result
  121. }
  122. /**
  123. * 根据支持的文件类型生成 accept 属性值
  124. *
  125. * @param supportedFileTypes 支持的文件类型数组,如 ['PDF', 'DOC', 'DOCX']
  126. * @returns 用于文件上传组件 accept 属性的字符串
  127. */
  128. export const generateAcceptedFileTypes = (supportedFileTypes: string[]): string => {
  129. const allowedExtensions = supportedFileTypes.map((ext) => ext.toLowerCase())
  130. const mimeTypes: string[] = []
  131. // 添加常见的 MIME 类型映射
  132. if (allowedExtensions.includes('txt')) {
  133. mimeTypes.push('text/plain')
  134. }
  135. if (allowedExtensions.includes('pdf')) {
  136. mimeTypes.push('application/pdf')
  137. }
  138. if (allowedExtensions.includes('html') || allowedExtensions.includes('htm')) {
  139. mimeTypes.push('text/html')
  140. }
  141. if (allowedExtensions.includes('csv')) {
  142. mimeTypes.push('text/csv')
  143. }
  144. if (allowedExtensions.includes('xlsx') || allowedExtensions.includes('xls')) {
  145. mimeTypes.push('application/vnd.ms-excel')
  146. mimeTypes.push('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  147. }
  148. if (allowedExtensions.includes('docx') || allowedExtensions.includes('doc')) {
  149. mimeTypes.push('application/msword')
  150. mimeTypes.push('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  151. }
  152. if (allowedExtensions.includes('pptx') || allowedExtensions.includes('ppt')) {
  153. mimeTypes.push('application/vnd.ms-powerpoint')
  154. mimeTypes.push('application/vnd.openxmlformats-officedocument.presentationml.presentation')
  155. }
  156. if (allowedExtensions.includes('xml')) {
  157. mimeTypes.push('application/xml')
  158. mimeTypes.push('text/xml')
  159. }
  160. if (allowedExtensions.includes('md') || allowedExtensions.includes('markdown')) {
  161. mimeTypes.push('text/markdown')
  162. }
  163. if (allowedExtensions.includes('epub')) {
  164. mimeTypes.push('application/epub+zip')
  165. }
  166. if (allowedExtensions.includes('eml')) {
  167. mimeTypes.push('message/rfc822')
  168. }
  169. if (allowedExtensions.includes('msg')) {
  170. mimeTypes.push('application/vnd.ms-outlook')
  171. }
  172. // 添加文件扩展名
  173. const extensions = allowedExtensions.map((ext) => `.${ext}`)
  174. return [...mimeTypes, ...extensions].join(',')
  175. }
  176. /**
  177. * 首字母大写
  178. */
  179. export function firstUpperCase(str: string) {
  180. return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
  181. }
  182. export const generateUUID = () => {
  183. if (typeof crypto === 'object') {
  184. if (typeof crypto.randomUUID === 'function') {
  185. return crypto.randomUUID()
  186. }
  187. if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
  188. const callback = (c: any) => {
  189. const num = Number(c)
  190. return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(
  191. 16
  192. )
  193. }
  194. return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback)
  195. }
  196. }
  197. let timestamp = new Date().getTime()
  198. let performanceNow =
  199. (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0
  200. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  201. let random = Math.random() * 16
  202. if (timestamp > 0) {
  203. random = (timestamp + random) % 16 | 0
  204. timestamp = Math.floor(timestamp / 16)
  205. } else {
  206. random = (performanceNow + random) % 16 | 0
  207. performanceNow = Math.floor(performanceNow / 16)
  208. }
  209. return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16)
  210. })
  211. }
  212. /**
  213. * element plus 的文件大小 Formatter 实现
  214. *
  215. * @param row 行数据
  216. * @param column 字段
  217. * @param cellValue 字段值
  218. */
  219. // @ts-ignore
  220. export const fileSizeFormatter = (row, column, cellValue) => {
  221. const fileSize = cellValue
  222. const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  223. const srcSize = parseFloat(fileSize)
  224. const index = Math.floor(Math.log(srcSize) / Math.log(1024))
  225. const size = srcSize / Math.pow(1024, index)
  226. const sizeStr = size.toFixed(2) //保留的小数位数
  227. return sizeStr + ' ' + unitArr[index]
  228. }
  229. /**
  230. * 将值复制到目标对象,且以目标对象属性为准,例:target: {a:1} source:{a:2,b:3} 结果为:{a:2}
  231. * @param target 目标对象
  232. * @param source 源对象
  233. */
  234. export const copyValueToTarget = (target: any, source: any) => {
  235. const newObj = Object.assign({}, target, source)
  236. // 删除多余属性
  237. Object.keys(newObj).forEach((key) => {
  238. // 如果不是target中的属性则删除
  239. if (Object.keys(target).indexOf(key) === -1) {
  240. delete newObj[key]
  241. }
  242. })
  243. // 更新目标对象值
  244. Object.assign(target, newObj)
  245. }
  246. /**
  247. * 获取链接的参数值
  248. * @param key 参数键名
  249. * @param urlStr 链接地址,默认为当前浏览器的地址
  250. */
  251. export const getUrlValue = (key: string, urlStr: string = location.href): string => {
  252. if (!urlStr || !key) return ''
  253. const url = new URL(decodeURIComponent(urlStr))
  254. return url.searchParams.get(key) ?? ''
  255. }
  256. /**
  257. * 获取链接的参数值(值类型)
  258. * @param key 参数键名
  259. * @param urlStr 链接地址,默认为当前浏览器的地址
  260. */
  261. export const getUrlNumberValue = (key: string, urlStr: string = location.href): number => {
  262. return toNumber(getUrlValue(key, urlStr))
  263. }
  264. /**
  265. * 构建排序字段
  266. * @param prop 字段名称
  267. * @param order 顺序
  268. */
  269. export const buildSortingField = ({ prop, order }) => {
  270. return { field: prop, order: order === 'ascending' ? 'asc' : 'desc' }
  271. }
  272. // ========== NumberUtils 数字方法 ==========
  273. /**
  274. * 数组求和
  275. *
  276. * @param values 数字数组
  277. * @return 求和结果,默认为 0
  278. */
  279. export const getSumValue = (values: number[]): number => {
  280. return values.reduce((prev, curr) => {
  281. const value = Number(curr)
  282. if (!Number.isNaN(value)) {
  283. return prev + curr
  284. } else {
  285. return prev
  286. }
  287. }, 0)
  288. }
  289. // ========== 通用金额方法 ==========
  290. /**
  291. * 将一个整数转换为分数保留两位小数
  292. * @param num
  293. */
  294. export const formatToFraction = (num: number | string | undefined): string => {
  295. if (typeof num === 'undefined') return '0.00'
  296. const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
  297. return (parsedNumber / 100.0).toFixed(2)
  298. }
  299. /**
  300. * 将一个数转换为 1.00 这样
  301. * 数据呈现的时候使用
  302. *
  303. * @param num 整数
  304. */
  305. // TODO @芋艿:看看怎么融合掉
  306. export const floatToFixed2 = (num: number | string | undefined): string => {
  307. let str = '0.00'
  308. if (typeof num === 'undefined') {
  309. return str
  310. }
  311. const f = formatToFraction(num)
  312. const decimalPart = f.toString().split('.')[1]
  313. const len = decimalPart ? decimalPart.length : 0
  314. switch (len) {
  315. case 0:
  316. str = f.toString() + '.00'
  317. break
  318. case 1:
  319. str = f.toString() + '0'
  320. break
  321. case 2:
  322. str = f.toString()
  323. break
  324. }
  325. return str
  326. }
  327. /**
  328. * 将一个分数转换为整数
  329. * @param num
  330. */
  331. // TODO @芋艿:看看怎么融合掉
  332. export const convertToInteger = (num: number | string | undefined): number => {
  333. if (typeof num === 'undefined') return 0
  334. const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
  335. // TODO 分转元后还有小数则四舍五入
  336. return Math.round(parsedNumber * 100)
  337. }
  338. /**
  339. * 元转分
  340. */
  341. export const yuanToFen = (amount: string | number): number => {
  342. return convertToInteger(amount)
  343. }
  344. /**
  345. * 分转元
  346. */
  347. export const fenToYuan = (price: string | number): string => {
  348. return formatToFraction(price)
  349. }
  350. /**
  351. * 计算环比
  352. *
  353. * @param value 当前数值
  354. * @param reference 对比数值
  355. */
  356. export const calculateRelativeRate = (value?: number, reference?: number) => {
  357. // 防止除0
  358. if (!reference || reference == 0) return 0
  359. return ((100 * ((value || 0) - reference)) / reference).toFixed(0)
  360. }
  361. // ========== ERP 专属方法 ==========
  362. const ERP_COUNT_DIGIT = 3
  363. const ERP_PRICE_DIGIT = 2
  364. /**
  365. * 【ERP】格式化 Input 数字
  366. *
  367. * 例如说:库存数量
  368. *
  369. * @param num 数量
  370. * @package digit 保留的小数位数
  371. * @return 格式化后的数量
  372. */
  373. export const erpNumberFormatter = (num: number | string | undefined, digit: number) => {
  374. if (num == null) {
  375. return ''
  376. }
  377. if (typeof num === 'string') {
  378. num = parseFloat(num)
  379. }
  380. // 如果非 number,则直接返回空串
  381. if (isNaN(num)) {
  382. return ''
  383. }
  384. return num.toFixed(digit)
  385. }
  386. /**
  387. * 【ERP】格式化数量,保留三位小数
  388. *
  389. * 例如说:库存数量
  390. *
  391. * @param num 数量
  392. * @return 格式化后的数量
  393. */
  394. export const erpCountInputFormatter = (num: number | string | undefined) => {
  395. return erpNumberFormatter(num, ERP_COUNT_DIGIT)
  396. }
  397. // noinspection JSCommentMatchesSignature
  398. /**
  399. * 【ERP】格式化数量,保留三位小数
  400. *
  401. * @param cellValue 数量
  402. * @return 格式化后的数量
  403. */
  404. export const erpCountTableColumnFormatter = (_, __, cellValue: any, ___) => {
  405. return erpNumberFormatter(cellValue, ERP_COUNT_DIGIT)
  406. }
  407. /**
  408. * 【ERP】格式化金额,保留二位小数
  409. *
  410. * 例如说:库存数量
  411. *
  412. * @param num 数量
  413. * @return 格式化后的数量
  414. */
  415. export const erpPriceInputFormatter = (num: number | string | undefined) => {
  416. return erpNumberFormatter(num, ERP_PRICE_DIGIT)
  417. }
  418. // noinspection JSCommentMatchesSignature
  419. /**
  420. * 【ERP】格式化金额,保留二位小数
  421. *
  422. * @param cellValue 数量
  423. * @return 格式化后的数量
  424. */
  425. export const erpPriceTableColumnFormatter = (_, __, cellValue: any, ___) => {
  426. return erpNumberFormatter(cellValue, ERP_PRICE_DIGIT)
  427. }
  428. /**
  429. * 【ERP】价格计算,四舍五入保留两位小数
  430. *
  431. * @param price 价格
  432. * @param count 数量
  433. * @return 总价格。如果有任一为空,则返回 undefined
  434. */
  435. export const erpPriceMultiply = (price: number, count: number) => {
  436. if (price == null || count == null) {
  437. return undefined
  438. }
  439. return parseFloat((price * count).toFixed(ERP_PRICE_DIGIT))
  440. }
  441. /**
  442. * 【ERP】百分比计算,四舍五入保留两位小数
  443. *
  444. * 如果 total 为 0,则返回 0
  445. *
  446. * @param value 当前值
  447. * @param total 总值
  448. */
  449. export const erpCalculatePercentage = (value: number, total: number) => {
  450. if (total === 0) return 0
  451. return ((value / total) * 100).toFixed(2)
  452. }
  453. /**
  454. * 适配 echarts map 的地名
  455. *
  456. * @param areaName 地区名称
  457. */
  458. export const areaReplace = (areaName: string) => {
  459. if (!areaName) {
  460. return areaName
  461. }
  462. return areaName
  463. .replace('维吾尔自治区', '')
  464. .replace('壮族自治区', '')
  465. .replace('回族自治区', '')
  466. .replace('自治区', '')
  467. .replace('省', '')
  468. }
  469. /**
  470. * 解析 JSON 字符串
  471. *
  472. * @param str
  473. */
  474. export function jsonParse(str: string) {
  475. try {
  476. return JSON.parse(str)
  477. } catch (e) {
  478. console.log(`str[${str}] 不是一个 JSON 字符串`)
  479. return ''
  480. }
  481. }
  482. /**
  483. * 截取字符串
  484. *
  485. * @param str 字符串
  486. * @param start 开始位置
  487. * @param end 结束位置
  488. */
  489. export const subString = (str: string, start: number, end: number) => {
  490. if (str.length > end) {
  491. return str.slice(start, end)
  492. }
  493. return str
  494. }