utils.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import { message } from 'antd';
  2. import { parse } from 'querystring';
  3. import moment from 'moment';
  4. import { RcFile } from 'antd/lib/upload';
  5. /* eslint no-useless-escape:0 import/prefer-default-export:0 */
  6. const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
  7. export const isUrl = (path: string): boolean => reg.test(path);
  8. export const isAntDesignPro = (): boolean => {
  9. if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
  10. return true;
  11. }
  12. return window.location.hostname === 'preview.pro.ant.design';
  13. };
  14. // 给官方演示站点用,用于关闭真实开发环境不需要使用的特性
  15. export const isAntDesignProOrDev = (): boolean => {
  16. const { NODE_ENV } = process.env;
  17. if (NODE_ENV === 'development') {
  18. return true;
  19. }
  20. return isAntDesignPro();
  21. };
  22. export const getPageQuery = () => {
  23. const { href } = window.location;
  24. const qsIndex = href.indexOf('?');
  25. const sharpIndex = href.indexOf('#');
  26. if (qsIndex !== -1) {
  27. if (qsIndex > sharpIndex) {
  28. return parse(href.split('?')[1]);
  29. }
  30. return parse(href.slice(qsIndex + 1, sharpIndex));
  31. }
  32. return {};
  33. };
  34. // 排序这是比较函数
  35. export const compare = (field: string, order: 'descend' | 'ascend') => {
  36. // descend 降序 大到小 ascend 升序 小到大
  37. if (order === 'ascend') {
  38. return function (m: any, n: any) {
  39. var a = m[field];
  40. var b = n[field];
  41. return a - b; //升序
  42. }
  43. } else {
  44. return function (m: any, n: any) {
  45. var a = m[field];
  46. var b = n[field];
  47. return b - a; //降序
  48. }
  49. }
  50. }
  51. // 返回别名
  52. export const getChannelName = (name: string) => {
  53. let newName = name
  54. let abridgeServer: string[] = ['知定', '巨网', '广联', '太古', '云广', '傲星', '弘捷', '开域']
  55. let asName = abridgeServer.find((item: string) => name?.indexOf(item) !== -1)
  56. if (asName) {
  57. newName = asName
  58. } else if (newName?.length > 5) {
  59. newName = newName?.slice(2, 5) + '...'
  60. }
  61. return newName
  62. }
  63. // 输入文案时判断
  64. export const txtLength = (value?: string) => {
  65. if (value) {
  66. let length = value?.length
  67. let text = value?.replace(/[\x00-\xff]/g, '')
  68. return text?.length + Number(((length - text?.length) / 2).toFixed())
  69. } else {
  70. return 0
  71. }
  72. }
  73. // 点击复制
  74. export const copy = (str: string) => {
  75. let element = document.createElement("textarea");
  76. element.id = 'myTextarea'
  77. element.textContent = str
  78. document.body.append(element);
  79. (document.getElementById('myTextarea') as any).select();
  80. document.execCommand("Copy")
  81. document.body.removeChild(element);
  82. message.success(`复制成功:${str}`)
  83. }
  84. type Type = "day" | "week" | "month" | "year" | "years" | "y" | "months" | "M" | "weeks" | "w" | "days" | "d" | "hour" | "hours" | "h" | "minute"
  85. type Format = 'YYYY-MM-DD' | 'YYYY-MM-DD HH' | 'YYYY-MM-DD HH:mm' | 'YYYY-MM-DD HH:mm:ss'
  86. /**往后日期 */
  87. export function useAddTime(num: number, type: Type, format?: Format, date?: Date | string): string {
  88. return moment(date || new Date()).add(num, type).format(format || 'YYYY-MM-DD')
  89. }
  90. /**
  91. * 精度
  92. * @param num1 number
  93. * @param num2 number
  94. * @param operator '+' | '-' | '*' | '/'
  95. * @returns
  96. */
  97. export const getNumber = (num1: number, num2: number, operator: '+' | '-' | '*' | '/') => {
  98. if (!num1) {
  99. return '0.00'
  100. }
  101. return Number(eval(`${num1.toFixed(10)}${operator}${num2.toFixed(10)}`).toFixed(10))
  102. }
  103. /**
  104. * 拼接oss参数获取视频首针图
  105. * @param videoUrl t_0 0秒的视频截图 t_10000 10秒的视频截图帧
  106. */
  107. export const getVideoImgUrl = (videoUrl: string) => {
  108. if (['.mp4', '.swf', '.flv', '.rm', '.ram', '.mov', '.mpg', '.mpeg', '.wmv', '.avi'].some(item => videoUrl.includes(item))) {
  109. return videoUrl + "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto"
  110. }
  111. return videoUrl
  112. }
  113. /**
  114. * 秒数格式化
  115. * @param seconds 秒
  116. * @returns
  117. */
  118. export function formatSecondsToTime(seconds: number): string {
  119. const hours = Math.floor(seconds / 3600);
  120. const minutes = Math.floor((seconds % 3600) / 60);
  121. const secs = seconds % 60;
  122. // 使用 padStart 确保每个部分都是两位数
  123. return `${hours > 24 ? `${Math.floor(hours / 24)}天${hours % 24}` : String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  124. }
  125. /** 获取base64 */
  126. export const getBase64 = (file: RcFile, callback: (url: string) => void) => {
  127. const reader = new FileReader();
  128. reader.addEventListener('load', () => callback(reader.result as string));
  129. reader.readAsDataURL(file);
  130. };
  131. /** 获取图片上传宽高 */
  132. export const getImgSizeProper = (file: RcFile): Promise<void> => {
  133. return new Promise((resolve: (value: any | PromiseLike<void>) => void) => {
  134. let img: any = new Image();
  135. let _URL = window.URL || window.webkitURL;
  136. img.onload = function (e: any) {
  137. resolve({ width: this.width, height: this.height })
  138. }
  139. img.src = _URL.createObjectURL(file);
  140. })
  141. }
  142. // 数组分组
  143. export const groupBy = (array: any[], f: (item: any) => any[], isObject?: boolean) => {
  144. const groups: any = {};
  145. array.forEach(function (o) { //注意这里必须是forEach 大写
  146. const key = f(o)
  147. const group = typeof key === 'string' ? key : JSON.stringify(key);
  148. groups[group] = groups[group] || [];
  149. groups[group].push(o);
  150. });
  151. if (isObject) {
  152. return groups
  153. }
  154. return Object.keys(groups).map(function (group) {
  155. return groups[group];
  156. });
  157. }
  158. /**
  159. * 防抖
  160. * @param func
  161. * @param delay
  162. * @returns
  163. */
  164. export function debounce<T extends (...args: any[]) => any>(func: T, delay: number): (...args: Parameters<T>) => void {
  165. let timeoutId: NodeJS.Timeout | undefined;
  166. return function (...args: Parameters<T>) {
  167. // 清除之前的定时器
  168. if (timeoutId) {
  169. clearTimeout(timeoutId);
  170. }
  171. // 设置新的定时器
  172. timeoutId = setTimeout(() => {
  173. // @ts-ignore
  174. func.apply(this, args);
  175. }, delay);
  176. };
  177. }