Helper.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import { CASH_BASE } from '@scripts/constants/App';
  2. import { sys } from 'cc';
  3. import { ANDROID, IOS } from 'cc/env';
  4. const STORAGE_ENCRYPTION_HEAD = 'a6072637';
  5. const STORAGE_ENCRYPTION_PASSWORD = 'xbd4jl';
  6. const STORAGE_ENCRYPTION_ENABLED = true;
  7. /**
  8. * 将数字格式化为财务展示格式:使用千位分隔符并保留两位小数。
  9. * 例如:1234567.8 -> 1,234,567.80。
  10. */
  11. export function formatCurrency(value: number | string, decimal = 0): string {
  12. if (typeof value === 'string') value = Number(value);
  13. if (!Number.isFinite(value)) value = 0;
  14. return value.toLocaleString('en-US', {
  15. minimumFractionDigits: decimal,
  16. maximumFractionDigits: decimal,
  17. useGrouping: true,
  18. });
  19. }
  20. export function formatSCNum(value: number | string) {
  21. return formatCurrency(value, 2);
  22. }
  23. export function formatGCNum(value: number | string) {
  24. return formatCurrency(value, 0);
  25. }
  26. export function formatCash(value: number) {
  27. value = Math.floor(value / CASH_BASE);
  28. return formatCurrency(value, 2);
  29. }
  30. const SHORT_MONTH_NAMES = [
  31. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  32. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
  33. ];
  34. /** Converts `YYYY-MM-DD HH:mm:ss.SSS` into `Mon D, HH:mm`. */
  35. export function formatShortDateTime(value: string): string {
  36. const match = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{2})/);
  37. if (!match) return '';
  38. const month = Number(match[2]);
  39. const day = Number(match[3]);
  40. const hour = Number(match[4]);
  41. const minute = Number(match[5]);
  42. if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59) return '';
  43. return `${SHORT_MONTH_NAMES[month - 1]} ${day}, ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  44. }
  45. /**
  46. * 商品货币显示
  47. * 小于 10,000 时展示完整数值;小于 1,000,000 时向下取整为 K;
  48. * 其余数值向下截取到 0.01M,并固定展示两位小数。
  49. * @param value 商品数量
  50. */
  51. export function formatGoodsNum(value: number): string {
  52. if (!Number.isFinite(value)) value = 0;
  53. if (value < 10_000) {
  54. let decimal = value % 1 > 0 ? 2 : 0;
  55. return value.toLocaleString('en-US', {
  56. minimumFractionDigits: decimal,
  57. maximumFractionDigits: 20,
  58. useGrouping: true,
  59. });
  60. }
  61. if (value < 1_000_000) {
  62. return `${Math.floor(value / 1_000)}K`;
  63. }
  64. return `${(Math.floor(value / 10_000) / 100).toFixed(2)}M`;
  65. }
  66. /**
  67. * 通用数量格式化:支持缩放除数 + K/M/B/T缩写
  68. * @param rawStr 后端原始字符串,如 "120000.00"
  69. * @param max 触发缩写的【真实数值阈值】(除以divisor之后的值)
  70. * @param decimalPlaces 最多保留小数位数,默认2
  71. * @param divisor 除数,后端放大倍数,默认100;不需要缩放就传1
  72. * @returns 格式化后的展示文本
  73. */
  74. export function formatNumShort(
  75. rawStr: string | undefined,
  76. max: number,
  77. divisor = 100,
  78. decimalPlaces = 2,
  79. ): string {
  80. if (!rawStr) return "0";
  81. const rawNum = Number(rawStr);
  82. if (isNaN(rawNum)) return "0";
  83. const realNum = rawNum / divisor;
  84. const units = [
  85. { value: 1e12, suffix: "T" },
  86. { value: 1e9, suffix: "B" },
  87. { value: 1e6, suffix: "M" },
  88. { value: 1e3, suffix: "K" },
  89. ];
  90. // 没达到缩写阈值
  91. if (realNum < max) {
  92. const fixedStr = realNum.toFixed(decimalPlaces);
  93. // 去除末尾多余0,如 8.00 → "8",0.08 → "0.08"
  94. return parseFloat(fixedStr).toString();
  95. }
  96. for (const unit of units) {
  97. if (realNum >= unit.value) {
  98. const val = realNum / unit.value;
  99. const fixedStr = val.toFixed(decimalPlaces);
  100. const trimStr = parseFloat(fixedStr).toString();
  101. return `${trimStr}${unit.suffix}`;
  102. }
  103. }
  104. return realNum.toString();
  105. }
  106. /**
  107. * 读取本地数据,并兼容 game_web_us2 写入的加密格式。
  108. */
  109. export function localStorageGet<T = string>(key: string, defaultValue: T = '' as T): string | T {
  110. let value = sys.localStorage.getItem(key);
  111. if (value === null) return defaultValue;
  112. if (value.startsWith(STORAGE_ENCRYPTION_HEAD)) {
  113. try {
  114. value = decrypt(value.substring(STORAGE_ENCRYPTION_HEAD.length));
  115. } catch {
  116. // 与原项目保持一致:解密失败时返回空字符串。
  117. value = '';
  118. }
  119. }
  120. return value;
  121. }
  122. /**
  123. * 加密并保存本地数据。空字符串不加密,行为与 game_web_us2 保持一致。
  124. */
  125. export function localStorageSet(key: string, value: unknown): void {
  126. let storageValue = value;
  127. if (STORAGE_ENCRYPTION_ENABLED && storageValue !== null && storageValue !== '') {
  128. const plainValue = typeof storageValue === 'string' ? storageValue : String(storageValue);
  129. storageValue = plainValue;
  130. try {
  131. storageValue = STORAGE_ENCRYPTION_HEAD + encrypt(plainValue);
  132. } catch {
  133. // 加密失败时沿用原值保存,兼容原项目行为。
  134. }
  135. }
  136. sys.localStorage.setItem(key, String(storageValue));
  137. }
  138. export function localStorageRemove(key: string): void {
  139. sys.localStorage.removeItem(key);
  140. }
  141. function encrypt(value: string, password = STORAGE_ENCRYPTION_PASSWORD): string {
  142. if (value === '') return '';
  143. const source = encodeURIComponent(value);
  144. const encodedPassword = encodeURIComponent(password || STORAGE_ENCRYPTION_PASSWORD);
  145. if (encodedPassword.length === 0) return '';
  146. let randomSeed = '';
  147. for (let index = 0; index < encodedPassword.length; index += 1) {
  148. randomSeed += encodedPassword.charCodeAt(index).toString();
  149. }
  150. const seedPosition = Math.floor(randomSeed.length / 5);
  151. const multiplier = Number.parseInt(
  152. randomSeed.charAt(seedPosition)
  153. + randomSeed.charAt(seedPosition * 2)
  154. + randomSeed.charAt(seedPosition * 3)
  155. + randomSeed.charAt(seedPosition * 4)
  156. + randomSeed.charAt(seedPosition * 5),
  157. 10,
  158. );
  159. const increment = Math.ceil(encodedPassword.length / 2);
  160. const modulus = Math.pow(2, 31) - 1;
  161. if (multiplier < 2) return '';
  162. let salt = Math.round(Math.random() * 1_000_000_000) % 100_000_000;
  163. randomSeed += salt;
  164. randomSeed = reduceSeed(randomSeed);
  165. let pseudoRandom = (multiplier * Number(randomSeed) + increment) % modulus;
  166. let encrypted = '';
  167. for (let index = 0; index < source.length; index += 1) {
  168. const encryptedChar = source.charCodeAt(index) ^ Math.floor((pseudoRandom / modulus) * 255);
  169. encrypted += encryptedChar < 16
  170. ? `0${encryptedChar.toString(16)}`
  171. : encryptedChar.toString(16);
  172. pseudoRandom = (multiplier * pseudoRandom + increment) % modulus;
  173. }
  174. let saltHex = salt.toString(16);
  175. while (saltHex.length < 8) saltHex = `0${saltHex}`;
  176. return encrypted + saltHex;
  177. }
  178. function decrypt(value: string, password = STORAGE_ENCRYPTION_PASSWORD): string {
  179. if (value === '') return '';
  180. const encodedPassword = encodeURIComponent(password || STORAGE_ENCRYPTION_PASSWORD);
  181. if (value.length < 8 || encodedPassword.length === 0) return '';
  182. let randomSeed = '';
  183. for (let index = 0; index < encodedPassword.length; index += 1) {
  184. randomSeed += encodedPassword.charCodeAt(index).toString();
  185. }
  186. const seedPosition = Math.floor(randomSeed.length / 5);
  187. const multiplier = Number.parseInt(
  188. randomSeed.charAt(seedPosition)
  189. + randomSeed.charAt(seedPosition * 2)
  190. + randomSeed.charAt(seedPosition * 3)
  191. + randomSeed.charAt(seedPosition * 4)
  192. + randomSeed.charAt(seedPosition * 5),
  193. 10,
  194. );
  195. const increment = Math.round(encodedPassword.length / 2);
  196. const modulus = Math.pow(2, 31) - 1;
  197. const salt = Number.parseInt(value.substring(value.length - 8), 16);
  198. const encrypted = value.substring(0, value.length - 8);
  199. randomSeed += salt;
  200. randomSeed = reduceSeed(randomSeed);
  201. let pseudoRandom = (multiplier * Number(randomSeed) + increment) % modulus;
  202. let decrypted = '';
  203. for (let index = 0; index < encrypted.length; index += 2) {
  204. const decryptedChar = Number.parseInt(encrypted.substring(index, index + 2), 16)
  205. ^ Math.floor((pseudoRandom / modulus) * 255);
  206. decrypted += String.fromCharCode(decryptedChar);
  207. pseudoRandom = (multiplier * pseudoRandom + increment) % modulus;
  208. }
  209. return decodeURIComponent(decrypted);
  210. }
  211. function reduceSeed(seed: string): string {
  212. let result = seed;
  213. while (result.length > 10) {
  214. let remaining = result;
  215. let total = 0;
  216. while (remaining.length > 0) {
  217. total += Number.parseInt(remaining.substring(0, 10), 10);
  218. remaining = remaining.substring(10);
  219. }
  220. result = total.toString();
  221. }
  222. return result;
  223. }
  224. /**
  225. * 进入平台判定:0=普通浏览器 1=iOS壳包 2=Android壳包 3=PWA(桌面图标/TWA 进入)
  226. * 用于按来源差异化展示(如提现页官网引流提示:桌面图标进入的玩家不显示)。
  227. * 壳包判定优先于 PWA;TWA 判定内联实现,避免 helpers→UAUtils 循环依赖。
  228. */
  229. export function getEnterPlatform(): 0 | 1 | 2 | 3 {
  230. if (ANDROID) return 2;
  231. if (IOS) return 1;
  232. return 0;
  233. }
  234. export function createUUID() {
  235. const chars: string[] = [];
  236. const hexDigits = '0123456789abcdef';
  237. for (let index = 0; index < 36; index += 1) {
  238. chars[index] = hexDigits.charAt(
  239. Math.floor(Math.random() * 16),
  240. );
  241. }
  242. // UUID version 4:0100
  243. chars[14] = '4';
  244. // RFC variant:10xx
  245. const variant = (Number.parseInt(chars[19], 16) & 0x3) | 0x8;
  246. chars[19] = hexDigits.charAt(variant);
  247. chars[8] = '-';
  248. chars[13] = '-';
  249. chars[18] = '-';
  250. chars[23] = '-';
  251. return chars.join('');
  252. }
  253. export function getUrlParams(url: string) {
  254. const queryIndex = url.indexOf('?');
  255. const params = {};
  256. if (queryIndex >= 0) {
  257. url.slice(queryIndex + 1).split('&').forEach((entry) => {
  258. if (!entry) return;
  259. const separatorIndex = entry.indexOf('=');
  260. const rawKey = separatorIndex >= 0 ? entry.slice(0, separatorIndex) : entry;
  261. const rawValue = separatorIndex >= 0 ? entry.slice(separatorIndex + 1) : '';
  262. try {
  263. const key = decodeURIComponent(rawKey.replace(/\+/g, ' '));
  264. params[key] = decodeURIComponent(rawValue.replace(/\+/g, ' '));
  265. } catch {
  266. // Preserve malformed values instead of crashing the native callback.
  267. params[rawKey] = rawValue;
  268. }
  269. });
  270. }
  271. return params;
  272. }
  273. export function waitForSeconds(duration: number) {
  274. return new Promise((resolve, reject) => {
  275. setTimeout(resolve, duration * 1000)
  276. })
  277. }
  278. export function formatMaskContent(content: string, prefix: number, suffix: number) {
  279. const startIdx = Math.min(prefix, content.length);
  280. const endIdx = content.length - suffix;
  281. const first = content.substring(0, startIdx);
  282. const last = content.substring(endIdx, content.length)
  283. return `${first}***${last}`
  284. }
  285. export function formatMaskNickName(nickName: string) {
  286. return formatMaskContent(nickName, 2, 1);
  287. }
  288. export function formatMaskEmail(email: string) {
  289. if (!email || email.length === 0) return '';
  290. let index = email.indexOf('@');
  291. if (index === -1) return formatMaskContent(email, 2, 3);
  292. return formatMaskContent(email, 2, email.length - index);
  293. }
  294. export function checkIsEmail(str: string): boolean {
  295. const s = str.trim();
  296. if (!s) return false;
  297. const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  298. return reg.test(s);
  299. }
  300. export function safeFloor(num: number, decimal = 2) {
  301. let unit = Math.pow(10, decimal);
  302. return Math.floor(num * unit) / unit
  303. }
  304. export function formatMailTimeToMMDDYYYY(timeStr: string): string {
  305. const date = new Date(timeStr);
  306. if (isNaN(date.getTime())) {
  307. return ""; // 无效时间返回空
  308. }
  309. const month = String(date.getMonth() + 1).padStart(2, "0");
  310. const day = String(date.getDate()).padStart(2, "0");
  311. const year = date.getFullYear();
  312. return `${month}-${day}-${year}`;
  313. }
  314. export function parseMailRewardStr(str: string) {
  315. const result = [];
  316. const itemStrList = str.split(";").filter(Boolean);
  317. for (const itemStr of itemStrList) {
  318. const parts = itemStr.split(",");
  319. if (parts.length !== 2) continue;
  320. const type = parts[0]; // 直接字符串,不转数字!
  321. const rawRewardStr = parts[1];
  322. const rawReward = Number(rawRewardStr);
  323. if (isNaN(rawReward)) continue;
  324. if (rawReward == 0) continue;
  325. result.push({
  326. type,
  327. reward: rawReward / 100,
  328. rawReward: rawRewardStr
  329. });
  330. }
  331. return result;
  332. }