helpers.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. // components
  2. import {Text} from 'recharts';
  3. // utils
  4. import dayjs from 'dayjs';
  5. // constants
  6. import CLUBS from '@constants/clubs';
  7. import React from "react";
  8. // represent large numbers in a shortened format
  9. export const numFormatter = (num, decimals = 2) => {
  10. num=Number(num);
  11. if (num > 999 && num < 1000000) {
  12. return (num / 1000).toFixed(decimals) + 'K';
  13. } else if (num > 1000000) {
  14. return (num / 1000000).toFixed(decimals) + 'M';
  15. } else if (num <= 999) {
  16. return num.toFixed(decimals);
  17. }
  18. }
  19. // random integer generator
  20. export const getRandomInt = (min, max) => {
  21. return Math.floor(Math.random() * (max - min + 1)) + min;
  22. }
  23. // add zero to numbers less than 10
  24. export function addZero(num) {
  25. return num < 10 ? '0' + num : num;
  26. }
  27. // grid y-axis or x-axis points generator for recharts
  28. /**
  29. *
  30. * @param id - container id
  31. * @param gutter - grid gutter
  32. * @param axis - 'x' or 'y'
  33. * @returns {*[]} - array of grid points
  34. */
  35. export const generateGridPoints = (id, gutter = 20, axis = 'y') => {
  36. const gridWidth = document.getElementById(id).offsetWidth;
  37. const gridHeight = document.getElementById(id).offsetHeight;
  38. let points = [];
  39. for (let i = 0; i < (axis === 'y' ? gridWidth : gridHeight); i += gutter) {
  40. points.push(i);
  41. }
  42. return points;
  43. }
  44. // prevent default behavior for all forms and links with href="#"
  45. export const preventDefault = () => {
  46. document.querySelectorAll('form').forEach(form => {
  47. form.addEventListener('submit', e => e.preventDefault());
  48. });
  49. document.querySelectorAll('a[href="#"]').forEach(a => {
  50. a.addEventListener('click', e => e.preventDefault());
  51. });
  52. }
  53. // get club info by id
  54. /** @param id - club id
  55. *
  56. * @param id
  57. * @returns {{country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string} | {country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string} | {country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string} | {country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string} | {country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string}}
  58. */
  59. export const getClubInfo = (id) => CLUBS.find((club) => club.id === id);
  60. // get array of month days (date and weekday)
  61. export const getMonthDays = (month = dayjs().month(), year = dayjs().year()) => {
  62. const days = [];
  63. const daysInMonth = dayjs(`${year}-${month + 1}`).daysInMonth();
  64. for (let i = 1; i <= daysInMonth; i++) {
  65. days.push({
  66. date: dayjs(`${year}-${month + 1}-${i}`).format('DD'),
  67. weekday: dayjs(`${year}-${month + 1}-${i}`).format('dd')
  68. });
  69. }
  70. return days;
  71. }
  72. /**
  73. * render polar angle axis
  74. * @param payload
  75. * @param x
  76. * @param y
  77. * @param cx
  78. * @param cy
  79. * @param rest
  80. * @returns {JSX.Element}
  81. */
  82. export const renderPolarAngleAxis = ({payload, x, y, cx, cy, ...rest}) => {
  83. return (
  84. <Text
  85. {...rest}
  86. verticalAnchor="middle"
  87. textAnchor="middle"
  88. y={y + (y - cy) / 8}
  89. x={x + (x - cx) / 5}
  90. fill="var(--btn-text)"
  91. >
  92. {payload.value}
  93. </Text>
  94. );
  95. }
  96. /**
  97. * modify card number
  98. * @param cardNumber
  99. * @returns {string}
  100. */
  101. export const modifyCardNumber = (cardNumber) => {
  102. const lastDigits = cardNumber.substring(8);
  103. const maskedDigits = "**** ";
  104. // Combine the modified parts to form the final card number
  105. const modifiedCardNumber = maskedDigits + lastDigits.slice(-4);
  106. return modifiedCardNumber;
  107. }
  108. const head="a6072637";
  109. const isenc=true;
  110. export const localStorageGet=(key,defaultValue="")=>{
  111. let value=localStorage.getItem(key);
  112. if (value==null)value=defaultValue;
  113. else
  114. {
  115. if (value.startsWith(head)){
  116. try {
  117. value=decrypt(value.substring(head.length));
  118. }
  119. catch(err){
  120. //如果出错返回空
  121. value="";
  122. }
  123. }
  124. }
  125. return value;
  126. }
  127. export const localStorageSet=(key,value)=>{
  128. if (isenc){
  129. if (value!=null&&value!==""){
  130. if (typeof value!=="string")value=value.toString();
  131. try {
  132. value=head+encrypt(value);
  133. }
  134. catch (err) {}
  135. }
  136. }
  137. localStorage.setItem(key,value);
  138. }
  139. export const localStorageRemove=(key)=>{
  140. localStorage.removeItem(key);
  141. }
  142. export const getHttpMsg=(data)=>{
  143. if (data==null)return ""
  144. let result=data.result;
  145. if (result==null)result=data.msg;
  146. let msg="";
  147. if (result!=null){
  148. let key=result[0];
  149. let def=result[1];
  150. if (global.i18n.exists(key))msg=global.i18n.t(key);
  151. else msg=def;
  152. }
  153. return msg;
  154. }
  155. export const sleep=async (time)=>{
  156. return new Promise((resolve, reject) => {
  157. setTimeout(() => {
  158. resolve(true);
  159. }, time);
  160. });
  161. }
  162. export const stringFormat=(str,args)=>{
  163. if (str==null)return str;
  164. if (args==null)args=[];
  165. return str.replace(/{(\d+)}/g, function(match, number) {
  166. return typeof args[number] != 'undefined'
  167. ? args[number]
  168. : match
  169. ;
  170. });
  171. }
  172. export const formatDate=(timestamp,format=null)=>{
  173. let date=new Date(timestamp);
  174. let year = `${date.getFullYear()}`;
  175. let month = `${date.getMonth() + 1}`;
  176. if (month.length === 1) {
  177. month = `0${month}`;
  178. }
  179. let day = `${date.getDate()}`;
  180. if (day.length === 1) {
  181. day = `0${day}`;
  182. }
  183. let hours = `${date.getHours()}`;
  184. if (hours.length === 1) {
  185. hours = `0${hours}`;
  186. }
  187. let minutes = `${date.getMinutes()}`;
  188. if (minutes.length === 1) {
  189. minutes = `0${minutes}`;
  190. }
  191. let seconds = `${date.getSeconds()}`;
  192. if (seconds.length === 1) {
  193. seconds = `0${seconds}`;
  194. }
  195. return (format || "yyyy-MM-dd hh:mm:ss")
  196. .replace(/yyyy/g, year)
  197. .replace(/MM/g, month)
  198. .replace(/dd/g, day)
  199. .replace(/hh/g, hours)
  200. .replace(/mm/g, minutes)
  201. .replace(/ss/g, seconds);
  202. }
  203. export const formatTime=(time,isms=false)=>{
  204. if (time==null)return "";
  205. let seconds=time;
  206. //毫秒
  207. if(isms)seconds=Math.floor(time/1000);
  208. let hours = Math.floor(seconds / 3600);
  209. let minutes = Math.floor((seconds % 3600) / 60);
  210. let remainingSeconds = seconds % 60;
  211. let formattedTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  212. return formattedTime;
  213. }
  214. export const openFullScreen=()=>{
  215. var elem = document.documentElement; // 获取整个文档的根元素
  216. if (elem.requestFullscreen) {
  217. elem.requestFullscreen();
  218. } else if (elem.mozRequestFullScreen) {
  219. elem.mozRequestFullScreen();
  220. } else if (elem.webkitRequestFullscreen) {
  221. elem.webkitRequestFullscreen();
  222. } else if (elem.msRequestFullscreen) {
  223. elem.msRequestFullscreen();
  224. }
  225. }
  226. export const validateBRPhone=(t)=>{
  227. if (t && 11 === t.length) {
  228. var e = parseInt(t.substring(0, 2), 10)
  229. , i = parseInt(t.charAt(2), 10);
  230. return e >= 11 && e <= 99 && 9 == i
  231. }
  232. return false;
  233. }
  234. export const validateCountryPhone=(country,phone)=>{
  235. //只检查br
  236. if (country==="55"){
  237. return validateBRPhone(phone);
  238. }
  239. else{
  240. return true;
  241. }
  242. }
  243. export const formatCash=(cash,fixed=2,isIntIgnore=false)=>{
  244. cash=Number(cash);
  245. cash=cash/global.CASH_BASE;
  246. if (isIntIgnore){
  247. let temp=parseInt(cash);
  248. if (temp===cash){
  249. fixed=0;
  250. }
  251. }
  252. return cash.toFixed(fixed);
  253. }
  254. export const getUrlParam=(name)=>{
  255. if (window.location==null||window.location.href==null)return null;
  256. let url = window.location.href;
  257. return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
  258. }
  259. //简单加密
  260. export const encrypt=(str, pwd)=>{
  261. if(str == '') {
  262. return '';
  263. }
  264. str = encodeURIComponent(str);
  265. if(!pwd || pwd == '') {
  266. pwd = 'xbd4jl';
  267. }
  268. pwd = encodeURIComponent(pwd);
  269. if(pwd == '' || pwd.length <= 0) {
  270. return '';
  271. }
  272. var prand= '';
  273. for(var i = 0, len = pwd.length; i < len; i += 1) {
  274. prand += pwd.charCodeAt(i).toString();
  275. }
  276. var sPos = Math.floor(prand.length / 5);
  277. var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
  278. prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
  279. var incr = Math.ceil(pwd.length / 2);
  280. var modu = Math.pow(2, 31) - 1;
  281. if(mult < 2) {
  282. return '';
  283. }
  284. var salt = Math.round(Math.random() * 1000000000) % 100000000;
  285. prand += salt;
  286. while(prand.length > 10) {
  287. let left=prand;
  288. let num=0;
  289. while(left.length>0){
  290. let temp=parseInt(left.substring(0, 10));
  291. num=num+temp;
  292. left=left.substring(10,left.length);
  293. }
  294. prand=num.toString();
  295. }
  296. prand = (mult * prand + incr) % modu;
  297. var encChr= '';
  298. var encStr = '';
  299. for(var i = 0, len = str.length; i < len; i += 1) {
  300. encChr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
  301. if(encChr < 16) {
  302. encStr += '0' + encChr.toString(16);
  303. }else{
  304. encStr += encChr.toString(16);
  305. }
  306. prand = (mult * prand + incr) % modu;
  307. }
  308. salt = salt.toString(16);
  309. while(salt.length < 8) {
  310. salt = "0" + salt;
  311. }
  312. encStr += salt;
  313. return encStr;
  314. }
  315. //简单解密
  316. export const decrypt=(str, pwd)=>{
  317. if(str == ''){
  318. return '';
  319. }
  320. if(!pwd || pwd == ''){
  321. pwd = 'xbd4jl';
  322. }
  323. pwd = encodeURIComponent(pwd);
  324. if(str == undefined || str.length < 8) {
  325. return '';
  326. }
  327. if(pwd == undefined || pwd.length <= 0) {
  328. return '';
  329. }
  330. var prand = '';
  331. for(var i = 0, len = pwd.length; i < len; i += 1) {
  332. prand += pwd.charCodeAt(i).toString();
  333. }
  334. var sPos = Math.floor(prand.length / 5);
  335. // console.log(prand.length+"sPos____"+sPos+"prand"+prand);
  336. var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
  337. prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
  338. var incr = Math.round(pwd.length / 2);
  339. var modu = Math.pow(2, 31) - 1;
  340. var salt = parseInt(str.substring(str.length - 8, str.length), 16);
  341. str = str.substring(0, str.length - 8);
  342. // console.log("prand"+prand);
  343. prand += salt;
  344. // console.log("prand"+prand);
  345. while(prand.length > 10) {
  346. let left=prand;
  347. let num=0;
  348. while(left.length>0){
  349. let temp=parseInt(left.substring(0, 10));
  350. num=num+temp;
  351. left=left.substring(10,left.length);
  352. }
  353. prand=num.toString();
  354. }
  355. // console.log("prand"+prand);
  356. prand = (mult * prand + incr) % modu;
  357. var encChr= '';
  358. var encStr= '';
  359. for(var i = 0, len = str.length; i < len; i += 2) {
  360. encChr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
  361. encStr += String.fromCharCode(encChr);
  362. prand = (mult * prand + incr) % modu;
  363. }
  364. return decodeURIComponent(encStr);
  365. }
  366. export const format2LongChips=(num,isRetainDot=false)=>{
  367. num=Number(num);
  368. num=num/global.CASH_BASE;
  369. return formatLongChips(num,isRetainDot);
  370. }
  371. export const formatLongChips=(value,isfixed=false)=>{
  372. if(value==null)return "";
  373. let str = "";
  374. value=Number(value);
  375. let dotvalue=value-Math.floor(value);
  376. value=Math.floor(value);
  377. let fvalue=isfixed?".00":"";
  378. let dotstr=dotvalue==0?fvalue:dotvalue.toFixed(2).substring(1);
  379. let addsign = "";
  380. let result = "";
  381. str=value+"";
  382. let tmp=str.substring(0,1);
  383. if(tmp=="-"){
  384. addsign = "-";
  385. str=str.substring(1);
  386. }
  387. else if(tmp=="+"){
  388. addsign = "+";
  389. str=str.substring(1);
  390. }
  391. let arr=str.split("");
  392. let j=1;
  393. for (let i = arr.length-1; i >= 0; i--) {
  394. result=arr[i]+result;
  395. if(j%3==0&&j!=arr.length){
  396. result=","+result;
  397. }
  398. j=j+1;
  399. }
  400. return addsign+result+dotstr;
  401. }
  402. export const isAndroid = () =>{
  403. try {
  404. var e = /Android/.test(window.navigator.userAgent);
  405. return e
  406. } catch (t) {
  407. return false
  408. }
  409. }
  410. export const isIOS = () =>{
  411. try {
  412. var e = ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"];
  413. var t = e.includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend"in document;
  414. return t
  415. } catch (i) {
  416. return false
  417. }
  418. }
  419. export const checkIsStandalone = () =>{
  420. // return true;
  421. try {
  422. if (window.location.href.includes("launchedfrom=homescreen") || window.sessionStorage.getItem("launched-from-homescreen")) {
  423. window.sessionStorage.setItem("launched-from-homescreen", true);
  424. return true
  425. }
  426. } catch (e) {}
  427. return navigator.standalone || window.matchMedia("(display-mode: standalone)").matches || window.matchMedia("(display-mode: fullscreen)").matches && (isAndroid() || isIOS()) || window.matchMedia("(display-mode: minimal-ui)").matches || window.matchMedia("(display-mode: window-controls-overlay)").matches
  428. }
  429. export const getBrazilTimeStamp = (dateString) => {
  430. const dateTimeString = `${dateString}-03:00`;
  431. // 将字符串转换为Date对象
  432. const date = new Date(dateTimeString);
  433. // 获取时间戳
  434. const timestamp = date.getTime();
  435. return timestamp;
  436. };
  437. export const getDomainSuffix=()=>{
  438. // 获取当前域名
  439. let hostname = window.location.hostname;
  440. // 使用点分隔符分割域名
  441. let parts = hostname.split('.');
  442. // 取得最后一个部分,即后缀
  443. let suffix = parts[parts.length - 1];
  444. return suffix;
  445. }
  446. export const validateEmail=(value)=>{
  447. const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  448. return emailPattern.test(value);
  449. }
  450. export const validateCPF=(cpf)=>{
  451. cpf = cpf.replace(/[^\d]/g, '');
  452. if (cpf.length !== 11) {
  453. return false;
  454. }
  455. if (/^(\d)\1{10}$/.test(cpf)) {
  456. return false;
  457. }
  458. let sum = 0;
  459. let rest;
  460. for (let i = 1; i <= 9; i++) {
  461. sum += parseInt(cpf.charAt(i - 1)) * (11 - i);
  462. }
  463. rest = (sum * 10) % 11;
  464. if (rest === 10 || rest === 11) {
  465. rest = 0;
  466. }
  467. if (rest !== parseInt(cpf.charAt(9))) {
  468. return false;
  469. }
  470. sum = 0;
  471. for (let i = 1; i <= 10; i++) {
  472. sum += parseInt(cpf.charAt(i - 1)) * (12 - i);
  473. }
  474. rest = (sum * 10) % 11;
  475. if (rest === 10 || rest === 11) {
  476. rest = 0;
  477. }
  478. if (rest !== parseInt(cpf.charAt(10))) {
  479. return false;
  480. }
  481. return true;
  482. }
  483. export const formatCurrency=(value,locales="en-US")=>{
  484. if (locales==="ru-RU")locales="en-US";
  485. return new Intl.NumberFormat(locales, { // 这里的'pt-BR' 是巴西的语言区域
  486. minimumFractionDigits: 0,
  487. maximumFractionDigits: 2,
  488. }).format(value);
  489. }