helpers.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. return validateBRPhone(phone);
  236. }
  237. export const formatCash=(cash,fixed=2,isIntIgnore=false)=>{
  238. cash=Number(cash);
  239. cash=cash/global.CASH_BASE;
  240. if (isIntIgnore){
  241. let temp=parseInt(cash);
  242. if (temp===cash){
  243. fixed=0;
  244. }
  245. }
  246. return cash.toFixed(fixed);
  247. }
  248. export const getUrlParam=(name)=>{
  249. if (window.location==null||window.location.href==null)return null;
  250. let url = window.location.href;
  251. return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
  252. }
  253. //简单加密
  254. export const encrypt=(str, pwd)=>{
  255. if(str == '') {
  256. return '';
  257. }
  258. str = encodeURIComponent(str);
  259. if(!pwd || pwd == '') {
  260. pwd = 'xbd4jl';
  261. }
  262. pwd = encodeURIComponent(pwd);
  263. if(pwd == '' || pwd.length <= 0) {
  264. return '';
  265. }
  266. var prand= '';
  267. for(var i = 0, len = pwd.length; i < len; i += 1) {
  268. prand += pwd.charCodeAt(i).toString();
  269. }
  270. var sPos = Math.floor(prand.length / 5);
  271. var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
  272. prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
  273. var incr = Math.ceil(pwd.length / 2);
  274. var modu = Math.pow(2, 31) - 1;
  275. if(mult < 2) {
  276. return '';
  277. }
  278. var salt = Math.round(Math.random() * 1000000000) % 100000000;
  279. prand += salt;
  280. while(prand.length > 10) {
  281. let left=prand;
  282. let num=0;
  283. while(left.length>0){
  284. let temp=parseInt(left.substring(0, 10));
  285. num=num+temp;
  286. left=left.substring(10,left.length);
  287. }
  288. prand=num.toString();
  289. }
  290. prand = (mult * prand + incr) % modu;
  291. var encChr= '';
  292. var encStr = '';
  293. for(var i = 0, len = str.length; i < len; i += 1) {
  294. encChr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
  295. if(encChr < 16) {
  296. encStr += '0' + encChr.toString(16);
  297. }else{
  298. encStr += encChr.toString(16);
  299. }
  300. prand = (mult * prand + incr) % modu;
  301. }
  302. salt = salt.toString(16);
  303. while(salt.length < 8) {
  304. salt = "0" + salt;
  305. }
  306. encStr += salt;
  307. return encStr;
  308. }
  309. //简单解密
  310. export const decrypt=(str, pwd)=>{
  311. if(str == ''){
  312. return '';
  313. }
  314. if(!pwd || pwd == ''){
  315. pwd = 'xbd4jl';
  316. }
  317. pwd = encodeURIComponent(pwd);
  318. if(str == undefined || str.length < 8) {
  319. return '';
  320. }
  321. if(pwd == undefined || pwd.length <= 0) {
  322. return '';
  323. }
  324. var prand = '';
  325. for(var i = 0, len = pwd.length; i < len; i += 1) {
  326. prand += pwd.charCodeAt(i).toString();
  327. }
  328. var sPos = Math.floor(prand.length / 5);
  329. // console.log(prand.length+"sPos____"+sPos+"prand"+prand);
  330. var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
  331. prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
  332. var incr = Math.round(pwd.length / 2);
  333. var modu = Math.pow(2, 31) - 1;
  334. var salt = parseInt(str.substring(str.length - 8, str.length), 16);
  335. str = str.substring(0, str.length - 8);
  336. // console.log("prand"+prand);
  337. prand += salt;
  338. // console.log("prand"+prand);
  339. while(prand.length > 10) {
  340. let left=prand;
  341. let num=0;
  342. while(left.length>0){
  343. let temp=parseInt(left.substring(0, 10));
  344. num=num+temp;
  345. left=left.substring(10,left.length);
  346. }
  347. prand=num.toString();
  348. }
  349. // console.log("prand"+prand);
  350. prand = (mult * prand + incr) % modu;
  351. var encChr= '';
  352. var encStr= '';
  353. for(var i = 0, len = str.length; i < len; i += 2) {
  354. encChr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
  355. encStr += String.fromCharCode(encChr);
  356. prand = (mult * prand + incr) % modu;
  357. }
  358. return decodeURIComponent(encStr);
  359. }
  360. export const format2LongChips=(num,isRetainDot=false)=>{
  361. num=Number(num);
  362. num=num/global.CASH_BASE;
  363. return formatLongChips(num,isRetainDot);
  364. }
  365. export const formatLongChips=(value,isfixed=false)=>{
  366. if(value==null)return "";
  367. let str = "";
  368. value=Number(value);
  369. let dotvalue=value-Math.floor(value);
  370. value=Math.floor(value);
  371. let fvalue=isfixed?".00":"";
  372. let dotstr=dotvalue==0?fvalue:dotvalue.toFixed(2).substring(1);
  373. let addsign = "";
  374. let result = "";
  375. str=value+"";
  376. let tmp=str.substring(0,1);
  377. if(tmp=="-"){
  378. addsign = "-";
  379. str=str.substring(1);
  380. }
  381. else if(tmp=="+"){
  382. addsign = "+";
  383. str=str.substring(1);
  384. }
  385. let arr=str.split("");
  386. let j=1;
  387. for (let i = arr.length-1; i >= 0; i--) {
  388. result=arr[i]+result;
  389. if(j%3==0&&j!=arr.length){
  390. result=","+result;
  391. }
  392. j=j+1;
  393. }
  394. return addsign+result+dotstr;
  395. }
  396. export const isAndroid = () =>{
  397. try {
  398. var e = /Android/.test(window.navigator.userAgent);
  399. return e
  400. } catch (t) {
  401. return false
  402. }
  403. }
  404. export const isIOS = () =>{
  405. try {
  406. var e = ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"];
  407. var t = e.includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend"in document;
  408. return t
  409. } catch (i) {
  410. return false
  411. }
  412. }
  413. export const checkIsStandalone = () =>{
  414. // return true;
  415. try {
  416. if (window.location.href.includes("launchedfrom=homescreen") || window.sessionStorage.getItem("launched-from-homescreen")) {
  417. window.sessionStorage.setItem("launched-from-homescreen", true);
  418. return true
  419. }
  420. } catch (e) {}
  421. 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
  422. }