helpers.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. export const localStorageGet=(key,defaultValue="")=>{
  109. let value=localStorage.getItem(key);
  110. if (value==null)value=defaultValue;
  111. return value;
  112. }
  113. export const localStorageSet=(key,value)=>{
  114. localStorage.setItem(key,value);
  115. }
  116. export const getHttpMsg=(data)=>{
  117. if (data==null)return ""
  118. let result=data.result;
  119. if (result==null)result=data.msg;
  120. let msg="";
  121. if (result!=null){
  122. let key=result[0];
  123. let def=result[1];
  124. if (global.i18n.exists(key))msg=global.i18n.t(key);
  125. else msg=def;
  126. }
  127. return msg;
  128. }
  129. export const sleep=async (time)=>{
  130. return new Promise((resolve, reject) => {
  131. setTimeout(() => {
  132. resolve(true);
  133. }, time);
  134. });
  135. }
  136. export const stringFormat=(str,args)=>{
  137. if (str==null)return str;
  138. if (args==null)args=[];
  139. return str.replace(/{(\d+)}/g, function(match, number) {
  140. return typeof args[number] != 'undefined'
  141. ? args[number]
  142. : match
  143. ;
  144. });
  145. }
  146. export const formatDate=(timestamp,format=null)=>{
  147. let date=new Date(timestamp);
  148. let year = `${date.getFullYear()}`;
  149. let month = `${date.getMonth() + 1}`;
  150. if (month.length === 1) {
  151. month = `0${month}`;
  152. }
  153. let day = `${date.getDate()}`;
  154. if (day.length === 1) {
  155. day = `0${day}`;
  156. }
  157. let hours = `${date.getHours()}`;
  158. if (hours.length === 1) {
  159. hours = `0${hours}`;
  160. }
  161. let minutes = `${date.getMinutes()}`;
  162. if (minutes.length === 1) {
  163. minutes = `0${minutes}`;
  164. }
  165. let seconds = `${date.getSeconds()}`;
  166. if (seconds.length === 1) {
  167. seconds = `0${seconds}`;
  168. }
  169. return (format || "yyyy-MM-dd hh:mm:ss")
  170. .replace(/yyyy/g, year)
  171. .replace(/MM/g, month)
  172. .replace(/dd/g, day)
  173. .replace(/hh/g, hours)
  174. .replace(/mm/g, minutes)
  175. .replace(/ss/g, seconds);
  176. }
  177. export const formatTime=(time,isms=false)=>{
  178. if (time==null)return "";
  179. let seconds=time;
  180. //毫秒
  181. if(isms)seconds=Math.floor(time/1000);
  182. let hours = Math.floor(seconds / 3600);
  183. let minutes = Math.floor((seconds % 3600) / 60);
  184. let remainingSeconds = seconds % 60;
  185. let formattedTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  186. return formattedTime;
  187. }
  188. export const openFullScreen=()=>{
  189. var elem = document.documentElement; // 获取整个文档的根元素
  190. if (elem.requestFullscreen) {
  191. elem.requestFullscreen();
  192. } else if (elem.mozRequestFullScreen) {
  193. elem.mozRequestFullScreen();
  194. } else if (elem.webkitRequestFullscreen) {
  195. elem.webkitRequestFullscreen();
  196. } else if (elem.msRequestFullscreen) {
  197. elem.msRequestFullscreen();
  198. }
  199. }
  200. export const validateBRPhone=(t)=>{
  201. if (t && 11 === t.length) {
  202. var e = parseInt(t.substring(0, 2), 10)
  203. , i = parseInt(t.charAt(2), 10);
  204. return e >= 11 && e <= 99 && 9 == i
  205. }
  206. return false;
  207. }
  208. export const validateCountryPhone=(country,phone)=>{
  209. return validateBRPhone(phone);
  210. }
  211. export const formatCash=(cash,fixed=2,isIntIgnore=false)=>{
  212. cash=Number(cash);
  213. cash=cash/global.CASH_BASE;
  214. if (isIntIgnore){
  215. let temp=parseInt(cash);
  216. if (temp===cash){
  217. fixed=0;
  218. }
  219. }
  220. return cash.toFixed(fixed);
  221. }
  222. export const getUrlParam=(name)=>{
  223. if (window.location==null||window.location.href==null)return null;
  224. let url = window.location.href;
  225. return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
  226. }
  227. //简单加密
  228. export const encrypt=(str, pwd)=>{
  229. if(str == '') {
  230. return '';
  231. }
  232. str = encodeURIComponent(str);
  233. if(!pwd || pwd == '') {
  234. pwd = 'xbd4jl';
  235. }
  236. pwd = encodeURIComponent(pwd);
  237. if(pwd == '' || pwd.length <= 0) {
  238. return '';
  239. }
  240. var prand= '';
  241. for(var i = 0, len = pwd.length; i < len; i += 1) {
  242. prand += pwd.charCodeAt(i).toString();
  243. }
  244. var sPos = Math.floor(prand.length / 5);
  245. var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
  246. prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
  247. var incr = Math.ceil(pwd.length / 2);
  248. var modu = Math.pow(2, 31) - 1;
  249. if(mult < 2) {
  250. return '';
  251. }
  252. var salt = Math.round(Math.random() * 1000000000) % 100000000;
  253. prand += salt;
  254. while(prand.length > 10) {
  255. let left=prand;
  256. let num=0;
  257. while(left.length>0){
  258. let temp=parseInt(left.substring(0, 10));
  259. num=num+temp;
  260. left=left.substring(10,left.length);
  261. }
  262. prand=num.toString();
  263. }
  264. prand = (mult * prand + incr) % modu;
  265. var encChr= '';
  266. var encStr = '';
  267. for(var i = 0, len = str.length; i < len; i += 1) {
  268. encChr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
  269. if(encChr < 16) {
  270. encStr += '0' + encChr.toString(16);
  271. }else{
  272. encStr += encChr.toString(16);
  273. }
  274. prand = (mult * prand + incr) % modu;
  275. }
  276. salt = salt.toString(16);
  277. while(salt.length < 8) {
  278. salt = "0" + salt;
  279. }
  280. encStr += salt;
  281. return encStr;
  282. }
  283. //简单解密
  284. export const decrypt=(str, pwd)=>{
  285. if(str == ''){
  286. return '';
  287. }
  288. if(!pwd || pwd == ''){
  289. pwd = 'xbd4jl';
  290. }
  291. pwd = encodeURIComponent(pwd);
  292. if(str == undefined || str.length < 8) {
  293. return '';
  294. }
  295. if(pwd == undefined || pwd.length <= 0) {
  296. return '';
  297. }
  298. var prand = '';
  299. for(var i = 0, len = pwd.length; i < len; i += 1) {
  300. prand += pwd.charCodeAt(i).toString();
  301. }
  302. var sPos = Math.floor(prand.length / 5);
  303. // console.log(prand.length+"sPos____"+sPos+"prand"+prand);
  304. var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
  305. prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
  306. var incr = Math.round(pwd.length / 2);
  307. var modu = Math.pow(2, 31) - 1;
  308. var salt = parseInt(str.substring(str.length - 8, str.length), 16);
  309. str = str.substring(0, str.length - 8);
  310. // console.log("prand"+prand);
  311. prand += salt;
  312. // console.log("prand"+prand);
  313. while(prand.length > 10) {
  314. let left=prand;
  315. let num=0;
  316. while(left.length>0){
  317. let temp=parseInt(left.substring(0, 10));
  318. num=num+temp;
  319. left=left.substring(10,left.length);
  320. }
  321. prand=num.toString();
  322. }
  323. // console.log("prand"+prand);
  324. prand = (mult * prand + incr) % modu;
  325. var encChr= '';
  326. var encStr= '';
  327. for(var i = 0, len = str.length; i < len; i += 2) {
  328. encChr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
  329. encStr += String.fromCharCode(encChr);
  330. prand = (mult * prand + incr) % modu;
  331. }
  332. return decodeURIComponent(encStr);
  333. }
  334. export const format2LongChips=(num,isRetainDot=false)=>{
  335. num=Number(num);
  336. num=num/global.CASH_BASE;
  337. return formatLongChips(num,isRetainDot);
  338. }
  339. export const formatLongChips=(value,isfixed=false)=>{
  340. if(value==null)return "";
  341. let str = "";
  342. value=Number(value);
  343. let dotvalue=value-Math.floor(value);
  344. value=Math.floor(value);
  345. let fvalue=isfixed?".00":"";
  346. let dotstr=dotvalue==0?fvalue:dotvalue.toFixed(2).substring(1);
  347. let addsign = "";
  348. let result = "";
  349. str=value+"";
  350. let tmp=str.substring(0,1);
  351. if(tmp=="-"){
  352. addsign = "-";
  353. str=str.substring(1);
  354. }
  355. else if(tmp=="+"){
  356. addsign = "+";
  357. str=str.substring(1);
  358. }
  359. let arr=str.split("");
  360. let j=1;
  361. for (let i = arr.length-1; i >= 0; i--) {
  362. result=arr[i]+result;
  363. if(j%3==0&&j!=arr.length){
  364. result=","+result;
  365. }
  366. j=j+1;
  367. }
  368. return addsign+result+dotstr;
  369. }
  370. export const isAndroid = () =>{
  371. try {
  372. var e = /Android/.test(window.navigator.userAgent);
  373. return e
  374. } catch (t) {
  375. return false
  376. }
  377. }
  378. export const isIOS = () =>{
  379. try {
  380. var e = ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"];
  381. var t = e.includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend"in document;
  382. return t
  383. } catch (i) {
  384. return false
  385. }
  386. }
  387. export const checkIsStandalone = () =>{
  388. // return true;
  389. try {
  390. if (window.location.href.includes("launchedfrom=homescreen") || window.sessionStorage.getItem("launched-from-homescreen")) {
  391. window.sessionStorage.setItem("launched-from-homescreen", true);
  392. return true
  393. }
  394. } catch (e) {}
  395. 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
  396. }