helpers.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. // components
  2. import {Text} from 'recharts';
  3. // utils
  4. import dayjs from 'dayjs';
  5. // constants
  6. import CLUBS from '@constants/clubs';
  7. // represent large numbers in a shortened format
  8. export const numFormatter = (num, decimals = 2) => {
  9. num=Number(num);
  10. if (num > 999 && num < 1000000) {
  11. return (num / 1000).toFixed(decimals) + 'K';
  12. } else if (num > 1000000) {
  13. return (num / 1000000).toFixed(decimals) + 'M';
  14. } else if (num <= 999) {
  15. return num.toFixed(decimals);
  16. }
  17. }
  18. // random integer generator
  19. export const getRandomInt = (min, max) => {
  20. return Math.floor(Math.random() * (max - min + 1)) + min;
  21. }
  22. // add zero to numbers less than 10
  23. export function addZero(num) {
  24. return num < 10 ? '0' + num : num;
  25. }
  26. // grid y-axis or x-axis points generator for recharts
  27. /**
  28. *
  29. * @param id - container id
  30. * @param gutter - grid gutter
  31. * @param axis - 'x' or 'y'
  32. * @returns {*[]} - array of grid points
  33. */
  34. export const generateGridPoints = (id, gutter = 20, axis = 'y') => {
  35. const gridWidth = document.getElementById(id).offsetWidth;
  36. const gridHeight = document.getElementById(id).offsetHeight;
  37. let points = [];
  38. for (let i = 0; i < (axis === 'y' ? gridWidth : gridHeight); i += gutter) {
  39. points.push(i);
  40. }
  41. return points;
  42. }
  43. // prevent default behavior for all forms and links with href="#"
  44. export const preventDefault = () => {
  45. document.querySelectorAll('form').forEach(form => {
  46. form.addEventListener('submit', e => e.preventDefault());
  47. });
  48. document.querySelectorAll('a[href="#"]').forEach(a => {
  49. a.addEventListener('click', e => e.preventDefault());
  50. });
  51. }
  52. // get club info by id
  53. /** @param id - club id
  54. *
  55. * @param id
  56. * @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}}
  57. */
  58. export const getClubInfo = (id) => CLUBS.find((club) => club.id === id);
  59. // get array of month days (date and weekday)
  60. export const getMonthDays = (month = dayjs().month(), year = dayjs().year()) => {
  61. const days = [];
  62. const daysInMonth = dayjs(`${year}-${month + 1}`).daysInMonth();
  63. for (let i = 1; i <= daysInMonth; i++) {
  64. days.push({
  65. date: dayjs(`${year}-${month + 1}-${i}`).format('DD'),
  66. weekday: dayjs(`${year}-${month + 1}-${i}`).format('dd')
  67. });
  68. }
  69. return days;
  70. }
  71. /**
  72. * render polar angle axis
  73. * @param payload
  74. * @param x
  75. * @param y
  76. * @param cx
  77. * @param cy
  78. * @param rest
  79. * @returns {JSX.Element}
  80. */
  81. export const renderPolarAngleAxis = ({payload, x, y, cx, cy, ...rest}) => {
  82. return (
  83. <Text
  84. {...rest}
  85. verticalAnchor="middle"
  86. textAnchor="middle"
  87. y={y + (y - cy) / 8}
  88. x={x + (x - cx) / 5}
  89. fill="var(--btn-text)"
  90. >
  91. {payload.value}
  92. </Text>
  93. );
  94. }
  95. /**
  96. * modify card number
  97. * @param cardNumber
  98. * @returns {string}
  99. */
  100. export const modifyCardNumber = (cardNumber) => {
  101. const lastDigits = cardNumber.substring(8);
  102. const maskedDigits = "**** ";
  103. // Combine the modified parts to form the final card number
  104. const modifiedCardNumber = maskedDigits + lastDigits.slice(-4);
  105. return modifiedCardNumber;
  106. }
  107. export const localStorageGet=(key,defaultValue="")=>{
  108. let value=localStorage.getItem(key);
  109. if (value==null)value=defaultValue;
  110. return value;
  111. }
  112. export const localStorageSet=(key,value)=>{
  113. localStorage.setItem(key,value);
  114. }
  115. export const getHttpMsg=(data)=>{
  116. if (data==null)return ""
  117. let result=data.result;
  118. if (result==null)result=data.msg;
  119. let msg="";
  120. if (result!=null){
  121. let key=result[0];
  122. let def=result[1];
  123. if (global.i18n.exists(key))msg=global.i18n.t(key);
  124. else msg=def;
  125. }
  126. return msg;
  127. }
  128. export const sleep=async (time)=>{
  129. return new Promise((resolve, reject) => {
  130. setTimeout(() => {
  131. resolve(true);
  132. }, time);
  133. });
  134. }
  135. export const stringFormat=(str,args)=>{
  136. if (str==null)return str;
  137. if (args==null)args=[];
  138. return str.replace(/{(\d+)}/g, function(match, number) {
  139. return typeof args[number] != 'undefined'
  140. ? args[number]
  141. : match
  142. ;
  143. });
  144. }
  145. export const formatDate=(timestamp,format=null)=>{
  146. let date=new Date(timestamp);
  147. let year = `${date.getFullYear()}`;
  148. let month = `${date.getMonth() + 1}`;
  149. if (month.length === 1) {
  150. month = `0${month}`;
  151. }
  152. let day = `${date.getDate()}`;
  153. if (day.length === 1) {
  154. day = `0${day}`;
  155. }
  156. let hours = `${date.getHours()}`;
  157. if (hours.length === 1) {
  158. hours = `0${hours}`;
  159. }
  160. let minutes = `${date.getMinutes()}`;
  161. if (minutes.length === 1) {
  162. minutes = `0${minutes}`;
  163. }
  164. let seconds = `${date.getSeconds()}`;
  165. if (seconds.length === 1) {
  166. seconds = `0${seconds}`;
  167. }
  168. return (format || "yyyy-MM-dd hh:mm:ss")
  169. .replace(/yyyy/g, year)
  170. .replace(/MM/g, month)
  171. .replace(/dd/g, day)
  172. .replace(/hh/g, hours)
  173. .replace(/mm/g, minutes)
  174. .replace(/ss/g, seconds);
  175. }
  176. export const formatTime=(time,isms=false)=>{
  177. if (time==null)return "";
  178. let seconds=time;
  179. //毫秒
  180. if(isms)seconds=Math.floor(time/1000);
  181. let hours = Math.floor(seconds / 3600);
  182. let minutes = Math.floor((seconds % 3600) / 60);
  183. let remainingSeconds = seconds % 60;
  184. let formattedTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  185. return formattedTime;
  186. }
  187. export const openFullScreen=()=>{
  188. var elem = document.documentElement; // 获取整个文档的根元素
  189. if (elem.requestFullscreen) {
  190. elem.requestFullscreen();
  191. } else if (elem.mozRequestFullScreen) {
  192. elem.mozRequestFullScreen();
  193. } else if (elem.webkitRequestFullscreen) {
  194. elem.webkitRequestFullscreen();
  195. } else if (elem.msRequestFullscreen) {
  196. elem.msRequestFullscreen();
  197. }
  198. }
  199. export const validateBRPhone=(t)=>{
  200. if (t && 11 === t.length) {
  201. var e = parseInt(t.substring(0, 2), 10)
  202. , i = parseInt(t.charAt(2), 10);
  203. return e >= 11 && e <= 99 && 9 == i
  204. }
  205. return false;
  206. }
  207. export const validateCountryPhone=(country,phone)=>{
  208. return validateBRPhone(phone);
  209. }
  210. export const formatCash=(cash,fixed=2,isIntIgnore=false)=>{
  211. cash=Number(cash);
  212. cash=cash/global.CASH_BASE;
  213. if (isIntIgnore){
  214. let temp=parseInt(cash);
  215. if (temp===cash){
  216. fixed=0;
  217. }
  218. }
  219. return cash.toFixed(fixed);
  220. }
  221. export const getUrlParam=(name)=>{
  222. if (window.location==null||window.location.href==null)return null;
  223. let url = window.location.href;
  224. return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
  225. }
  226. //简单加密
  227. export const encrypt=(str, pwd)=>{
  228. if(str == '') {
  229. return '';
  230. }
  231. str = encodeURIComponent(str);
  232. if(!pwd || pwd == '') {
  233. pwd = 'xbd4jl';
  234. }
  235. pwd = encodeURIComponent(pwd);
  236. if(pwd == '' || pwd.length <= 0) {
  237. return '';
  238. }
  239. var prand= '';
  240. for(var i = 0, len = pwd.length; i < len; i += 1) {
  241. prand += pwd.charCodeAt(i).toString();
  242. }
  243. var sPos = Math.floor(prand.length / 5);
  244. var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
  245. prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
  246. var incr = Math.ceil(pwd.length / 2);
  247. var modu = Math.pow(2, 31) - 1;
  248. if(mult < 2) {
  249. return '';
  250. }
  251. var salt = Math.round(Math.random() * 1000000000) % 100000000;
  252. prand += salt;
  253. while(prand.length > 10) {
  254. let left=prand;
  255. let num=0;
  256. while(left.length>0){
  257. let temp=parseInt(left.substring(0, 10));
  258. num=num+temp;
  259. left=left.substring(10,left.length);
  260. }
  261. prand=num.toString();
  262. }
  263. prand = (mult * prand + incr) % modu;
  264. var encChr= '';
  265. var encStr = '';
  266. for(var i = 0, len = str.length; i < len; i += 1) {
  267. encChr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
  268. if(encChr < 16) {
  269. encStr += '0' + encChr.toString(16);
  270. }else{
  271. encStr += encChr.toString(16);
  272. }
  273. prand = (mult * prand + incr) % modu;
  274. }
  275. salt = salt.toString(16);
  276. while(salt.length < 8) {
  277. salt = "0" + salt;
  278. }
  279. encStr += salt;
  280. return encStr;
  281. }
  282. //简单解密
  283. export const decrypt=(str, pwd)=>{
  284. if(str == ''){
  285. return '';
  286. }
  287. if(!pwd || pwd == ''){
  288. pwd = 'xbd4jl';
  289. }
  290. pwd = encodeURIComponent(pwd);
  291. if(str == undefined || str.length < 8) {
  292. return '';
  293. }
  294. if(pwd == undefined || pwd.length <= 0) {
  295. return '';
  296. }
  297. var prand = '';
  298. for(var i = 0, len = pwd.length; i < len; i += 1) {
  299. prand += pwd.charCodeAt(i).toString();
  300. }
  301. var sPos = Math.floor(prand.length / 5);
  302. // console.log(prand.length+"sPos____"+sPos+"prand"+prand);
  303. var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
  304. prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
  305. var incr = Math.round(pwd.length / 2);
  306. var modu = Math.pow(2, 31) - 1;
  307. var salt = parseInt(str.substring(str.length - 8, str.length), 16);
  308. str = str.substring(0, str.length - 8);
  309. // console.log("prand"+prand);
  310. prand += salt;
  311. // console.log("prand"+prand);
  312. while(prand.length > 10) {
  313. let left=prand;
  314. let num=0;
  315. while(left.length>0){
  316. let temp=parseInt(left.substring(0, 10));
  317. num=num+temp;
  318. left=left.substring(10,left.length);
  319. }
  320. prand=num.toString();
  321. }
  322. // console.log("prand"+prand);
  323. prand = (mult * prand + incr) % modu;
  324. var encChr= '';
  325. var encStr= '';
  326. for(var i = 0, len = str.length; i < len; i += 2) {
  327. encChr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
  328. encStr += String.fromCharCode(encChr);
  329. prand = (mult * prand + incr) % modu;
  330. }
  331. return decodeURIComponent(encStr);
  332. }