util.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. import { TOKENNAME, HTTP_REQUEST_URL } from "../config/app.js";
  2. import { HTTP_ADMIN_URL, BASE_OSS_URL } from "@/config/app.js";
  3. import { useAppStore } from "@/stores/app.js";
  4. import { addJoinTeamUserRole } from "@/api/api.js";
  5. import { getJoinRolesAPI } from "@/api/joinus";
  6. import { footprintScan } from "@/api/merchant.js";
  7. import { pathToBase64 } from "@/plugin/image-tools/index.js";
  8. import { useToast } from "@/hooks/useToast";
  9. import pageJson from "@/pages.json";
  10. const appStore = useAppStore(); // 调用函数获取实例
  11. export default {
  12. /**
  13. * 移除数组中的某个数组并组成新的数组返回
  14. * @param array array 需要移除的数组
  15. * @param int index 需要移除的数组的键值
  16. * @param string | int 值
  17. * @return array
  18. *
  19. */
  20. ArrayRemove: function (array, index, value) {
  21. const valueArray = [];
  22. if (array instanceof Array) {
  23. for (let i = 0; i < array.length; i++) {
  24. if (typeof index == "number" && array[index] != i) {
  25. valueArray.push(array[i]);
  26. } else if (typeof index == "string" && array[i][index] != value) {
  27. valueArray.push(array[i]);
  28. }
  29. }
  30. }
  31. return valueArray;
  32. },
  33. /**
  34. * 生成海报获取文字
  35. * @param string text 为传入的文本
  36. * @param int num 为单行显示的字节长度
  37. * @return array
  38. */
  39. textByteLength: function (text, num) {
  40. let strLength = 0;
  41. let rows = 1;
  42. let str = 0;
  43. let arr = [];
  44. for (let j = 0; j < text.length; j++) {
  45. if (text.charCodeAt(j) > 255) {
  46. strLength += 2;
  47. if (strLength > rows * num) {
  48. strLength++;
  49. arr.push(text.slice(str, j));
  50. str = j;
  51. rows++;
  52. }
  53. } else {
  54. strLength++;
  55. if (strLength > rows * num) {
  56. arr.push(text.slice(str, j));
  57. str = j;
  58. rows++;
  59. }
  60. }
  61. }
  62. arr.push(text.slice(str, text.length));
  63. return [strLength, arr, rows]; // [处理文字的总字节长度,每行显示内容的数组,行数]
  64. },
  65. /**
  66. * 获取分享海报
  67. * @param array arr2 海报素材
  68. * @param string store_name 素材文字
  69. * @param string price 价格
  70. * @param string ot_price 原始价格
  71. * @param function successFn 回调函数
  72. *
  73. *
  74. */
  75. PosterCanvas: function (arr2, store_name, price, ot_price, successFn) {
  76. let that = this;
  77. const { Toast } = useToast();
  78. const ctx = uni.createCanvasContext("firstCanvas");
  79. ctx.clearRect(0, 0, 0, 0);
  80. /**
  81. * 只能获取合法域名下的图片信息,本地调试无法获取
  82. *
  83. */
  84. ctx.fillStyle = "#fff";
  85. ctx.fillRect(0, 0, 750, 1150);
  86. uni.getImageInfo({
  87. src: arr2[0],
  88. success: function (res) {
  89. const WIDTH = res.width;
  90. const HEIGHT = res.height;
  91. // ctx.drawImage(arr2[0], 0, 0, WIDTH, 1050);
  92. ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
  93. ctx.save();
  94. let r = 110;
  95. let d = r * 2;
  96. let cx = 480;
  97. let cy = 790;
  98. ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
  99. // ctx.clip();
  100. ctx.drawImage(arr2[2], cx, cy, d, d);
  101. ctx.restore();
  102. const CONTENT_ROW_LENGTH = 20;
  103. let [contentLeng, contentArray, contentRows] = that.textByteLength(
  104. store_name,
  105. CONTENT_ROW_LENGTH
  106. );
  107. if (contentRows > 2) {
  108. contentRows = 2;
  109. let textArray = contentArray.slice(0, 2);
  110. textArray[textArray.length - 1] += "……";
  111. contentArray = textArray;
  112. }
  113. ctx.setTextAlign("left");
  114. ctx.setFontSize(36);
  115. ctx.setFillStyle("#000");
  116. // let contentHh = 36 * 1.5;
  117. let contentHh = 36;
  118. for (let m = 0; m < contentArray.length; m++) {
  119. // ctx.fillText(contentArray[m], 50, 1000 + contentHh * m,750);
  120. if (m) {
  121. ctx.fillText(contentArray[m], 50, 1000 + contentHh * m + 18, 1100);
  122. } else {
  123. ctx.fillText(contentArray[m], 50, 1000 + contentHh * m, 1100);
  124. }
  125. }
  126. ctx.setTextAlign("left");
  127. ctx.setFontSize(72);
  128. ctx.setFillStyle("#DA4F2A");
  129. ctx.fillText("¥" + price, 40, 820 + contentHh);
  130. // ctx.setTextAlign("left");
  131. // ctx.setFontSize(36);
  132. // ctx.setFillStyle("#999");
  133. // ctx.fillText("¥" + ot_price, 50, 876 + contentHh);
  134. // var underline = function (
  135. // ctx,
  136. // text,
  137. // x,
  138. // y,
  139. // size,
  140. // color,
  141. // thickness,
  142. // offset
  143. // ) {
  144. // var width = ctx.measureText(text).width;
  145. // switch (ctx.textAlign) {
  146. // case "center":
  147. // x -= width / 2;
  148. // break;
  149. // case "right":
  150. // x -= width;
  151. // break;
  152. // }
  153. //
  154. // y += size + offset;
  155. //
  156. // ctx.beginPath();
  157. // ctx.strokeStyle = color;
  158. // ctx.lineWidth = thickness;
  159. // ctx.moveTo(x, y);
  160. // ctx.lineTo(x + width, y);
  161. // ctx.stroke();
  162. // };
  163. // underline(ctx, "¥" + ot_price, 55, 865, 36, "#999", 2, 0);
  164. ctx.setTextAlign("left");
  165. ctx.setFontSize(28);
  166. ctx.setFillStyle("#999");
  167. ctx.fillText("长按或扫描查看", 490, 1030 + contentHh);
  168. ctx.draw(true, function () {
  169. uni.canvasToTempFilePath({
  170. canvasId: "firstCanvas",
  171. fileType: "png",
  172. destWidth: WIDTH,
  173. destHeight: HEIGHT,
  174. success: function (res) {
  175. // uni.hideLoading();
  176. successFn && successFn(res.tempFilePath);
  177. },
  178. });
  179. });
  180. },
  181. fail: function (err) {
  182. console.log("失败", err);
  183. uni.hideLoading();
  184. Toast({
  185. title: "无法获取图片信息",
  186. });
  187. },
  188. });
  189. },
  190. /**
  191. * 绘制文字自动换行
  192. * @param array arr2 海报素材
  193. * @param Number x , y 绘制的坐标
  194. * @param Number maxWigth 绘制文字的宽度
  195. * @param Number lineHeight 行高
  196. * @param Number maxRowNum 最大行数
  197. */
  198. canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
  199. if (
  200. typeof text != "string" ||
  201. typeof x != "number" ||
  202. typeof y != "number"
  203. ) {
  204. return;
  205. }
  206. // canvas.font = '20px Bold PingFang SC'; //绘制文字的字号和大小
  207. // 字符分隔为数组
  208. var arrText = text.split("");
  209. var line = "";
  210. var rowNum = 1;
  211. for (var n = 0; n < arrText.length; n++) {
  212. var testLine = line + arrText[n];
  213. var metrics = canvas.measureText(testLine);
  214. var testWidth = metrics.width;
  215. if (testWidth > maxWidth && n > 0) {
  216. if (rowNum >= maxRowNum) {
  217. var arrLine = testLine.split("");
  218. arrLine.splice(-9);
  219. var newTestLine = arrLine.join("");
  220. newTestLine += "...";
  221. canvas.fillText(newTestLine, x, y);
  222. //如果需要在省略号后面添加其他的东西,就在这个位置写(列如添加扫码查看详情字样)
  223. //canvas.fillStyle = '#2259CA';
  224. //canvas.fillText('扫码查看详情',x + maxWidth-90, y);
  225. return;
  226. }
  227. canvas.fillText(line, x, y);
  228. line = arrText[n];
  229. y += lineHeight;
  230. rowNum += 1;
  231. } else {
  232. line = testLine;
  233. }
  234. }
  235. canvas.fillText(line, x, y);
  236. },
  237. /**
  238. * 获取活动分享海报
  239. * @param array arr2 海报素材
  240. * @param string storeName 素材文字
  241. * @param string price 价格
  242. * @param string people 人数
  243. * @param string count 剩余人数
  244. * @param function successFn 回调函数
  245. */
  246. activityCanvas: function (
  247. arrImages,
  248. storeName,
  249. price,
  250. people,
  251. count,
  252. num,
  253. successFn
  254. ) {
  255. let that = this;
  256. let rain = 2;
  257. const { Toast } = useToast();
  258. const context = uni.createCanvasContext("activityCanvas");
  259. context.clearRect(0, 0, 0, 0);
  260. /**
  261. * 只能获取合法域名下的图片信息,本地调试无法获取
  262. *
  263. */
  264. context.fillStyle = "#fff";
  265. context.fillRect(0, 0, 594, 850);
  266. uni.getImageInfo({
  267. src: arrImages[0],
  268. success: function (res) {
  269. context.drawImage(arrImages[0], 0, 0, 594, 850);
  270. context.setFontSize(14 * rain);
  271. context.setFillStyle("#333333");
  272. that.canvasWraptitleText(
  273. context,
  274. storeName,
  275. 110 * rain,
  276. 110 * rain,
  277. 230 * rain,
  278. 30 * rain,
  279. 1
  280. );
  281. context.drawImage(
  282. arrImages[2],
  283. 68 * rain,
  284. 194 * rain,
  285. 160 * rain,
  286. 160 * rain
  287. );
  288. context.save();
  289. context.setFontSize(14 * rain);
  290. context.setFillStyle("#fc4141");
  291. context.fillText("¥", 157 * rain, 145 * rain);
  292. context.setFontSize(24 * rain);
  293. context.setFillStyle("#fc4141");
  294. context.fillText(price, 170 * rain, 145 * rain);
  295. context.setFontSize(10 * rain);
  296. context.setFillStyle("#fff");
  297. context.fillText(people, 118 * rain, 143 * rain);
  298. context.setFontSize(12 * rain);
  299. context.setFillStyle("#666666");
  300. context.setTextAlign("center");
  301. context.fillText(count, (167 - num) * rain, 166 * rain);
  302. that.handleBorderRect(
  303. context,
  304. 27 * rain,
  305. 94 * rain,
  306. 75 * rain,
  307. 75 * rain,
  308. 6 * rain
  309. );
  310. context.clip();
  311. context.drawImage(
  312. arrImages[1],
  313. 27 * rain,
  314. 94 * rain,
  315. 75 * rain,
  316. 75 * rain
  317. );
  318. context.draw(true, function () {
  319. uni.canvasToTempFilePath({
  320. canvasId: "activityCanvas",
  321. fileType: "png",
  322. destWidth: 594,
  323. destHeight: 850,
  324. success: function (res) {
  325. // uni.hideLoading();
  326. successFn && successFn(res.tempFilePath);
  327. },
  328. });
  329. });
  330. },
  331. fail: function (err) {
  332. console.log("失败", err);
  333. uni.hideLoading();
  334. Toast({
  335. title: "无法获取图片信息",
  336. });
  337. },
  338. });
  339. },
  340. /**
  341. * 图片圆角设置
  342. * @param string x x轴位置
  343. * @param string y y轴位置
  344. * @param string w 图片宽
  345. * @param string y 图片高
  346. * @param string r 圆角值
  347. */
  348. handleBorderRect(ctx, x, y, w, h, r) {
  349. ctx.beginPath();
  350. // 左上角
  351. ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
  352. ctx.moveTo(x + r, y);
  353. ctx.lineTo(x + w - r, y);
  354. ctx.lineTo(x + w, y + r);
  355. // 右上角
  356. ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
  357. ctx.lineTo(x + w, y + h - r);
  358. ctx.lineTo(x + w - r, y + h);
  359. // 右下角
  360. ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
  361. ctx.lineTo(x + r, y + h);
  362. ctx.lineTo(x, y + h - r);
  363. // 左下角
  364. ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
  365. ctx.lineTo(x, y + r);
  366. ctx.lineTo(x + r, y);
  367. ctx.fill();
  368. ctx.closePath();
  369. },
  370. /*
  371. * 单图上传
  372. * @param object opt
  373. * @param callable successCallback 成功执行方法 data
  374. * @param callable errorCallback 失败执行方法
  375. */
  376. uploadImageOne: function (opt, successCallback, errorCallback) {
  377. let that = this;
  378. const { Toast } = useToast();
  379. if (typeof opt === "string") {
  380. let url = opt;
  381. opt = {};
  382. opt.url = url;
  383. }
  384. let count = opt.count || 1,
  385. sizeType = opt.sizeType || ["compressed"],
  386. sourceType = opt.sourceType || ["album", "camera"],
  387. is_load = opt.is_load || true,
  388. uploadUrl = opt.url || "",
  389. inputName = opt.name || "pics",
  390. pid = opt.pid,
  391. model = opt.model;
  392. uni.chooseImage({
  393. count: count, //最多可以选择的图片总数
  394. sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
  395. sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
  396. success: function (res) {
  397. //启动上传等待中...
  398. uni.showLoading({
  399. title: "图片上传中",
  400. });
  401. let urlPath =
  402. HTTP_ADMIN_URL +
  403. "/api/admin/upload/image" +
  404. "?model=" +
  405. model +
  406. "&pid=" +
  407. pid;
  408. let localPath = res.tempFilePaths[0];
  409. const TOKEN = useAppStore.token;
  410. uni.uploadFile({
  411. url: urlPath,
  412. filePath: localPath,
  413. name: inputName,
  414. header: {
  415. // #ifdef MP
  416. "Content-Type": "multipart/form-data",
  417. // #endif
  418. [TOKENNAME]: TOKEN,
  419. },
  420. success: function (res) {
  421. uni.hideLoading();
  422. if (res.statusCode == 403) {
  423. Toast({
  424. title: res.data,
  425. });
  426. } else {
  427. let data = res.data ? JSON.parse(res.data) : {};
  428. if (data.code == 200) {
  429. data.data.localPath = localPath;
  430. successCallback && successCallback(data);
  431. } else {
  432. errorCallback && errorCallback(data);
  433. Toast({
  434. title: data.message,
  435. });
  436. }
  437. }
  438. },
  439. fail: function (res) {
  440. uni.hideLoading();
  441. Toast({
  442. title: "上传图片失败",
  443. });
  444. },
  445. });
  446. // pathToBase64(res.tempFilePaths[0])
  447. // .then(imgBase64 => {
  448. // console.log(imgBase64);
  449. // })
  450. // .catch(error => {
  451. // console.error(error)
  452. // })
  453. },
  454. });
  455. },
  456. /**
  457. * 处理服务器扫码带进来的参数
  458. * @param string param 扫码携带参数
  459. * @param string k 整体分割符 默认为:&
  460. * @param string p 单个分隔符 默认为:=
  461. * @return object
  462. *
  463. */
  464. // #ifdef MP
  465. getUrlParams: function (param, k, p) {
  466. if (typeof param != "string") return {};
  467. k = k ? k : "&"; //整体参数分隔符
  468. p = p ? p : "="; //单个参数分隔符
  469. var value = {};
  470. if (param.indexOf(k) !== -1) {
  471. param = param.split(k);
  472. for (var val in param) {
  473. if (param[val].indexOf(p) !== -1) {
  474. var item = param[val].split(p);
  475. value[item[0]] = item[1];
  476. }
  477. }
  478. } else if (param.indexOf(p) !== -1) {
  479. var item = param.split(p);
  480. value[item[0]] = item[1];
  481. } else {
  482. return param;
  483. }
  484. return value;
  485. },
  486. /**根据格式组装公共参数
  487. * @param {Object} value
  488. */
  489. formatMpQrCodeData(value) {
  490. let values = value.split(",");
  491. let result = {};
  492. if (values.length === 2) {
  493. let v1 = values[0].split(":");
  494. if (v1[0] === "pid") {
  495. result.spread = v1[1];
  496. } else {
  497. result.id = v1[1];
  498. }
  499. let v2 = values[1].split(":");
  500. if (v2[0] === "pid") {
  501. result.spread = v2[1];
  502. } else {
  503. result.id = v2[1];
  504. }
  505. } else {
  506. result = values[0].split(":")[1];
  507. }
  508. return result;
  509. },
  510. // #endif
  511. /*
  512. * 合并数组
  513. */
  514. SplitArray(list, sp) {
  515. if (!Array.isArray(list)) return [];
  516. return [...sp, ...list];
  517. },
  518. trim(str) {
  519. return String.prototype.trim.call(str);
  520. },
  521. $h: {
  522. //除法函数,用来得到精确的除法结果
  523. //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  524. //调用:$h.Div(arg1,arg2)
  525. //返回值:arg1除以arg2的精确结果
  526. Div: function (arg1, arg2) {
  527. arg1 = parseFloat(arg1);
  528. arg2 = parseFloat(arg2);
  529. var t1 = 0,
  530. t2 = 0,
  531. r1,
  532. r2;
  533. try {
  534. t1 = arg1.toString().split(".")[1].length;
  535. } catch (e) {}
  536. try {
  537. t2 = arg2.toString().split(".")[1].length;
  538. } catch (e) {}
  539. r1 = Number(arg1.toString().replace(".", ""));
  540. r2 = Number(arg2.toString().replace(".", ""));
  541. return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
  542. },
  543. //加法函数,用来得到精确的加法结果
  544. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  545. //调用:$h.Add(arg1,arg2)
  546. //返回值:arg1加上arg2的精确结果
  547. Add: function (arg1, arg2) {
  548. arg2 = parseFloat(arg2);
  549. var r1, r2, m;
  550. try {
  551. r1 = arg1.toString().split(".")[1].length;
  552. } catch (e) {
  553. r1 = 0;
  554. }
  555. try {
  556. r2 = arg2.toString().split(".")[1].length;
  557. } catch (e) {
  558. r2 = 0;
  559. }
  560. m = Math.pow(100, Math.max(r1, r2));
  561. return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  562. },
  563. //减法函数,用来得到精确的减法结果
  564. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  565. //调用:$h.Sub(arg1,arg2)
  566. //返回值:arg1减去arg2的精确结果
  567. Sub: function (arg1, arg2) {
  568. arg1 = parseFloat(arg1);
  569. arg2 = parseFloat(arg2);
  570. var r1, r2, m, n;
  571. try {
  572. r1 = arg1.toString().split(".")[1].length;
  573. } catch (e) {
  574. r1 = 0;
  575. }
  576. try {
  577. r2 = arg2.toString().split(".")[1].length;
  578. } catch (e) {
  579. r2 = 0;
  580. }
  581. m = Math.pow(10, Math.max(r1, r2));
  582. //动态控制精度长度
  583. n = r1 >= r2 ? r1 : r2;
  584. return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  585. },
  586. //乘法函数,用来得到精确的乘法结果
  587. //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  588. //调用:$h.Mul(arg1,arg2)
  589. //返回值:arg1乘以arg2的精确结果
  590. Mul: function (arg1, arg2) {
  591. arg1 = parseFloat(arg1);
  592. arg2 = parseFloat(arg2);
  593. var m = 0,
  594. s1 = arg1.toString(),
  595. s2 = arg2.toString();
  596. try {
  597. m += s1.split(".")[1].length;
  598. } catch (e) {}
  599. try {
  600. m += s2.split(".")[1].length;
  601. } catch (e) {}
  602. return (
  603. (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
  604. Math.pow(10, m)
  605. );
  606. },
  607. },
  608. // 获取地理位置;
  609. $L: {
  610. async getLocation() {
  611. // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
  612. let status = await this.getSetting();
  613. if (status === 2) {
  614. this.openSetting();
  615. return;
  616. }
  617. // #endif
  618. this.doGetLocation();
  619. },
  620. doGetLocation() {
  621. uni.getLocation({
  622. success: (res) => {
  623. uni.removeStorageSync("CACHE_LONGITUDE");
  624. uni.removeStorageSync("CACHE_LATITUDE");
  625. uni.setStorageSync("CACHE_LONGITUDE", res.longitude);
  626. uni.setStorageSync("CACHE_LATITUDE", res.latitude);
  627. },
  628. fail: (err) => {
  629. // #ifdef MP-BAIDU
  630. if (err.errCode === 202 || err.errCode === 10003) {
  631. // 202模拟器 10003真机 user deny
  632. this.openSetting();
  633. }
  634. // #endif
  635. // #ifndef MP-BAIDU
  636. if (err.errMsg.indexOf("auth deny") >= 0) {
  637. Toast({
  638. title: "访问位置被拒绝",
  639. });
  640. } else {
  641. Toast({
  642. title: err.errMsg,
  643. });
  644. }
  645. // #endif
  646. },
  647. });
  648. },
  649. getSetting: function () {
  650. return new Promise((resolve, reject) => {
  651. uni.getSetting({
  652. success: (res) => {
  653. if (res.authSetting["scope.userLocation"] === undefined) {
  654. resolve(0);
  655. return;
  656. }
  657. if (res.authSetting["scope.userLocation"]) {
  658. resolve(1);
  659. } else {
  660. resolve(2);
  661. }
  662. },
  663. });
  664. });
  665. },
  666. openSetting: function () {
  667. uni.openSetting({
  668. success: (res) => {
  669. if (res.authSetting && res.authSetting["scope.userLocation"]) {
  670. this.doGetLocation();
  671. }
  672. },
  673. fail: (err) => {},
  674. });
  675. },
  676. async checkPermission() {
  677. let status = permision.isIOS
  678. ? await permision.requestIOS("location")
  679. : await permision.requestAndroid(
  680. "android.permission.ACCESS_FINE_LOCATION"
  681. );
  682. if (status === null || status === 1) {
  683. status = 1;
  684. } else if (status === 2) {
  685. uni.showModal({
  686. content: "系统定位已关闭",
  687. confirmText: "确定",
  688. showCancel: false,
  689. success: function (res) {},
  690. });
  691. } else if (status.code) {
  692. uni.showModal({
  693. content: status.message,
  694. });
  695. } else {
  696. uni.showModal({
  697. content: "需要定位权限",
  698. confirmText: "设置",
  699. success: function (res) {
  700. if (res.confirm) {
  701. permision.gotoAppSetting();
  702. }
  703. },
  704. });
  705. }
  706. return status;
  707. },
  708. },
  709. toStringValue: function (obj) {
  710. if (obj instanceof Array) {
  711. var arr = [];
  712. for (var i = 0; i < obj.length; i++) {
  713. arr[i] = toStringValue(obj[i]);
  714. }
  715. return arr;
  716. } else if (typeof obj == "object") {
  717. for (var p in obj) {
  718. obj[p] = toStringValue(obj[p]);
  719. }
  720. } else if (typeof obj == "number") {
  721. obj = obj + "";
  722. }
  723. return obj;
  724. },
  725. /*
  726. * 替换域名
  727. */
  728. setDomain: function (url) {
  729. url = url ? url.toString() : "";
  730. if (url.indexOf("https://") > -1) return url;
  731. else return url.replace("http://", "https://");
  732. },
  733. /**
  734. * 姓名除了姓显示其他
  735. */
  736. formatName: function (str) {
  737. return str.substr(0, 1) + new Array(str.length).join("*");
  738. },
  739. /**
  740. * rpx转px
  741. */
  742. rpxToPx(rpx) {
  743. const screenWidth = uni.getSystemInfoSync().screenWidth;
  744. return (screenWidth * Number.parseInt(rpx)) / 750;
  745. },
  746. /**
  747. * px 转换 rpx
  748. */
  749. pxToRpx: function (px) {
  750. const screenWidth = uni.getSystemInfoSync().screenWidth;
  751. return (750 * Number.parseInt(px)) / screenWidth;
  752. },
  753. };
  754. /**
  755. * 格式化日期
  756. * @prama t 时间戳
  757. * @return str MM-dd HH:mm
  758. */
  759. export function formatDate(t) {
  760. t = t || Date.now();
  761. let time = new Date(t);
  762. let str =
  763. time.getMonth() < 9 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1;
  764. str += "-";
  765. str += time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
  766. str += " ";
  767. str += time.getHours();
  768. str += ":";
  769. str += time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
  770. return str;
  771. }
  772. export function previewImage(urls = []) {
  773. if (!urls.length) return;
  774. uni.previewImage({
  775. urls,
  776. });
  777. }
  778. export function telEncrypt(tel = "") {
  779. let str = tel + "";
  780. let enStr = str.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
  781. return enStr;
  782. }
  783. /*
  784. * 随机数生成
  785. */
  786. export function generateCustomId(prefix) {
  787. // 验证前缀长度
  788. if (prefix.length <= 0) {
  789. throw new Error("必须附带前缀");
  790. }
  791. if (prefix.length > 6) {
  792. throw new Error("前缀太长,仅支持6位");
  793. }
  794. // 获取当前时间并格式化为年月日后两位+时分秒+毫秒
  795. const now = new Date();
  796. const year = String(now.getFullYear()).slice(-2);
  797. const month = String(now.getMonth() + 1).padStart(2, "0");
  798. const day = String(now.getDate()).padStart(2, "0");
  799. const hours = String(now.getHours()).padStart(2, "0");
  800. const minutes = String(now.getMinutes()).padStart(2, "0");
  801. const seconds = String(now.getSeconds()).padStart(2, "0");
  802. const milliseconds = String(now.getMilliseconds()).padStart(3, "0");
  803. // 组合时间部分(精确到毫秒)
  804. const timePart =
  805. year + month + day + hours + minutes + seconds + milliseconds;
  806. // 生成8位随机字符
  807. const chars =
  808. "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  809. let randomPart = "";
  810. for (let i = 0; i < 8; i++) {
  811. const randomIndex = Math.floor(Math.random() * chars.length);
  812. randomPart += chars[randomIndex];
  813. }
  814. // 组合生成ID
  815. return `${prefix}-${timePart}-${randomPart}`;
  816. }
  817. /**
  818. * 判断图片地址是否包含 HTTPS 协议
  819. * @param {string} imageUrl - 图片地址
  820. * @returns {string} 包含HTTPS则返回原图片地址,否则返回拼接oss对象存储地址
  821. */
  822. export function isHttpsImage(imageUrl) {
  823. if (typeof imageUrl !== "string" || !imageUrl) {
  824. return "/static/avator.png";
  825. }
  826. const trimmedUrl = imageUrl.trim();
  827. if (trimmedUrl.includes("https://")) {
  828. return imageUrl;
  829. } else {
  830. return BASE_OSS_URL + imageUrl;
  831. }
  832. }
  833. // 判断当前页面是否为 tabBar 页面
  834. export function isTabBarPage() {
  835. // 获取当前页面栈
  836. const pages = getCurrentPages();
  837. // 获取当前页面路径(不包含参数部分)
  838. if (!pages[pages.length - 1]) {
  839. return false;
  840. }
  841. const currentPagePath = pages[pages.length - 1].route;
  842. // 获取 app.json 中的 tabBar 配置
  843. const tabBarPages =
  844. getApp().globalData.tabBarPages ||
  845. (() => {
  846. // 从 app.json 中读取 tabBar 配置
  847. // const appJson = import('@/pages.json');
  848. // console.log('pageJson', pageJson)
  849. const tabBarList = pageJson.tabBar ? pageJson.tabBar.list : [];
  850. // 提取所有 tabBar 页面的路径
  851. const pages = tabBarList.map((item) => item.pagePath);
  852. // 缓存到全局数据中,避免重复解析
  853. getApp().globalData.tabBarPages = pages;
  854. return pages;
  855. })();
  856. // 判断当前页面是否在 tabBar 配置中
  857. return tabBarPages.includes(currentPagePath);
  858. }
  859. // 获取邀请码
  860. export async function getSceneInfo(e, index) {
  861. if (e.scene) {
  862. const decodedScene = decodeURIComponent(e.scene);
  863. const params = {};
  864. if (decodedScene) {
  865. decodedScene.split("&").forEach((item) => {
  866. const [key, value] = item.split("=");
  867. if (key && value) {
  868. params[key] = value;
  869. }
  870. });
  871. }
  872. if (params.merchantId) appStore.UPDATE_MERCHANT_ID(params.merchantId);
  873. if (index == "index" && appStore.userInfo) {
  874. let obj = {
  875. merchantId: params.merchantId,
  876. userId: appStore.userInfo.userId,
  877. };
  878. await footprintScan(obj);
  879. }
  880. console.log("获取邀请码-params", params);
  881. return params;
  882. }
  883. return {};
  884. }
  885. // 获取用户所有的加盟角色列表
  886. export async function getJoinTeamUserRoles() {
  887. let join_roles = [];
  888. const { data: list } = await getJoinRolesAPI();
  889. list.forEach((item) => {
  890. join_roles.push(item.roleName);
  891. });
  892. return join_roles;
  893. }
  894. // 为用户添加加盟角色(推荐官)
  895. // addRecommenderRole();
  896. //
  897. export async function addRecommenderRole(remark) {
  898. try {
  899. const appStore = useAppStore();
  900. const uid = appStore.uid;
  901. console.log("appStore", appStore.uid);
  902. if (!uid) {
  903. console.error("添加推荐官角色失败:用户ID不存在");
  904. uni.showToast({ title: "用户信息异常", icon: "none" });
  905. return;
  906. }
  907. const requestParams = {
  908. remark: remark || "自动成为推荐官",
  909. roleName: "推荐官",
  910. roleType: 2, // 2-推荐官
  911. uid,
  912. };
  913. const response = await addJoinTeamUserRole(requestParams);
  914. console.log("response", response);
  915. uni.showModal({
  916. title: "恭喜",
  917. content: "您已成为推荐官,推荐用户注册、消费立得好礼,是否立即查看?",
  918. confirmText: "立即查看",
  919. cancelText: "稍后",
  920. success: (res) => {
  921. if (res.confirm) {
  922. uni.navigateTo({
  923. url: "/pages/join_us/recommed",
  924. });
  925. }
  926. },
  927. });
  928. } catch (error) {
  929. console.error("添加推荐官角色请求异常:", error);
  930. uni.showToast({
  931. title: error || "网络异常,请稍后重试",
  932. icon: "none",
  933. duration: 2000,
  934. });
  935. }
  936. }
  937. /**
  938. * 精确计算工具(支持直接调用和链式调用)
  939. * 使用方法:
  940. * import { Calc } from '@/utils/util'
  941. *
  942. * // 直接计算(两个参数)
  943. * const sum = Calc.add(0.1, 0.2).valueOf(); // 0.3
  944. *
  945. * // 链式调用(后续方法传入一个参数,基于前一步结果计算)
  946. * const result = Calc.add(1, 2).sub(1).mul(3).div(2).fixed(1).valueOf(); // 3.0
  947. *
  948. * // 截断示例:40.66 截断2位 → 40.66;40.666 截断2位 → 40.66
  949. * const truncResult = Calc.truncate(40.666, 2).valueOf(); // 40.66
  950. *
  951. * // 注意点
  952. * 需要在最后调用一次.valueOf()获取最终值,否则会返回一个Calc对象。
  953. */
  954. export const Calc = {
  955. // 存储当前计算值
  956. currentValue: null,
  957. /**
  958. * 重置当前值(内部使用,确保每次计算独立性)
  959. */
  960. _reset() {
  961. this.currentValue = null;
  962. return this;
  963. },
  964. /**
  965. * 内部工具:校验并转换为有效数字(核心修复点)
  966. * @param {any} num - 待校验的数值
  967. * @returns {Number} 有效数字(无效则返回 0)
  968. */
  969. _validateNum(num) {
  970. // 过滤 Infinity/-Infinity/NaN/undefined/null/空字符串
  971. if (
  972. num === undefined ||
  973. num === null ||
  974. num === "" ||
  975. !isFinite(num) ||
  976. isNaN(Number(num))
  977. ) {
  978. return 0;
  979. }
  980. // 转换为数字类型(处理字符串数字,如 "123.45")
  981. return Number(num);
  982. },
  983. /**
  984. * 内部工具:解析数值字符串,返回整数部分、小数部分、小数位数、符号
  985. * @param {Number|String} num - 待解析的数值
  986. * @returns {Object} 解析结果
  987. */
  988. _parseNumStr(num) {
  989. // 第一步:先校验并转换为有效数字(修复 NaN 问题)
  990. const validNum = this._validateNum(num);
  991. const str = String(validNum).trim().replace(/^\+/, ""); // 移除正号
  992. const isNegative = str.startsWith("-");
  993. const absStr = isNegative ? str.slice(1) : str;
  994. const [integerPart = "0", decimalPart = "0"] = absStr.split(".");
  995. // 处理纯小数(如.123)或纯整数(如123.)的情况
  996. const cleanInteger = integerPart || "0";
  997. const cleanDecimal = decimalPart || "0";
  998. return {
  999. isNegative,
  1000. integerPart: cleanInteger,
  1001. decimalPart: cleanDecimal,
  1002. decimalLength: cleanDecimal.length,
  1003. };
  1004. },
  1005. /**
  1006. * 内部工具:对齐两个数的小数位数,转换为大整数
  1007. * @param {Number|String} num1 - 数值1
  1008. * @param {Number|String} num2 - 数值2
  1009. * @returns {Object} 对齐后的整数和缩放比例
  1010. */
  1011. _alignDecimals(num1, num2) {
  1012. const n1 = this._parseNumStr(num1);
  1013. const n2 = this._parseNumStr(num2);
  1014. const maxDecimalLen = Math.max(n1.decimalLength, n2.decimalLength);
  1015. // 补零对齐小数位数
  1016. const n1DecimalPadded = n1.decimalPart.padEnd(maxDecimalLen, "0");
  1017. const n2DecimalPadded = n2.decimalPart.padEnd(maxDecimalLen, "0");
  1018. // 转换为大整数(避免普通整数溢出)
  1019. const n1Int =
  1020. BigInt(n1.integerPart + n1DecimalPadded) * (n1.isNegative ? -1n : 1n);
  1021. const n2Int =
  1022. BigInt(n2.integerPart + n2DecimalPadded) * (n2.isNegative ? -1n : 1n);
  1023. return {
  1024. int1: n1Int,
  1025. int2: n2Int,
  1026. scale: BigInt(10 ** maxDecimalLen), // 缩放比例(10^最大小数位数)
  1027. };
  1028. },
  1029. /**
  1030. * 加法运算(修复精度问题 + 入参校验)
  1031. */
  1032. add(a, b) {
  1033. // 链式调用/直接调用参数处理
  1034. const [arg1, arg2] =
  1035. this.currentValue === null ? [a, b] : [this.currentValue, a];
  1036. const { int1, int2, scale } = this._alignDecimals(arg1, arg2);
  1037. const sumInt = int1 + int2;
  1038. // 转换回小数(BigInt转Number,确保精度)
  1039. this.currentValue = Number(sumInt) / Number(scale);
  1040. return this;
  1041. },
  1042. /**
  1043. * 减法运算(修复精度问题 + 入参校验)
  1044. */
  1045. sub(a, b) {
  1046. const [arg1, arg2] =
  1047. this.currentValue === null ? [a, b] : [this.currentValue, a];
  1048. const { int1, int2, scale } = this._alignDecimals(arg1, arg2);
  1049. const subInt = int1 - int2;
  1050. this.currentValue = Number(subInt) / Number(scale);
  1051. return this;
  1052. },
  1053. /**
  1054. * 乘法运算(修复精度问题 + 入参校验)
  1055. */
  1056. mul(a, b) {
  1057. const [arg1, arg2] =
  1058. this.currentValue === null ? [a, b] : [this.currentValue, a];
  1059. const n1 = this._parseNumStr(arg1);
  1060. const n2 = this._parseNumStr(arg2);
  1061. // 转换为整数(移除小数点)
  1062. const n1Int =
  1063. BigInt(n1.integerPart + n1.decimalPart) * (n1.isNegative ? -1n : 1n);
  1064. const n2Int =
  1065. BigInt(n2.integerPart + n2.decimalPart) * (n2.isNegative ? -1n : 1n);
  1066. // 总小数位数
  1067. const totalDecimalLen = n1.decimalLength + n2.decimalLength;
  1068. const scale = BigInt(10 ** totalDecimalLen);
  1069. // 相乘后除以缩放比例
  1070. const mulInt = n1Int * n2Int;
  1071. this.currentValue = Number(mulInt) / Number(scale);
  1072. return this;
  1073. },
  1074. /**
  1075. * 除法运算(修复精度问题 + 入参校验)
  1076. */
  1077. div(a, b) {
  1078. const [arg1, arg2] =
  1079. this.currentValue === null ? [a, b] : [this.currentValue, a];
  1080. // 先校验除数是否为有效数字(避免 0/NaN 混淆)
  1081. const validArg2 = this._validateNum(arg2);
  1082. if (validArg2 === 0) {
  1083. throw new Error("除数不能为0");
  1084. }
  1085. const n1 = this._parseNumStr(arg1);
  1086. const n2 = this._parseNumStr(arg2);
  1087. // 转换为整数(移除小数点)
  1088. const n1Int =
  1089. BigInt(n1.integerPart + n1.decimalPart) * (n1.isNegative ? -1n : 1n);
  1090. const n2Int =
  1091. BigInt(n2.integerPart + n2.decimalPart) * (n2.isNegative ? -1n : 1n);
  1092. // 计算缩放比例:10^(n2小数位数 - n1小数位数)
  1093. const decimalDiff = n2.decimalLength - n1.decimalLength;
  1094. const scale = BigInt(10 ** Math.abs(decimalDiff));
  1095. let divResult;
  1096. if (decimalDiff >= 0) {
  1097. divResult = (n1Int * scale) / n2Int;
  1098. } else {
  1099. divResult = n1Int / (n2Int * scale);
  1100. }
  1101. // 处理除法精度(保留15位小数,避免无限循环)
  1102. this.currentValue =
  1103. Number(divResult) / Number(BigInt(10 ** Math.max(0, -decimalDiff)));
  1104. return this;
  1105. },
  1106. /**
  1107. * 四舍五入保留指定小数位
  1108. */
  1109. fixed(num, n) {
  1110. let targetNum, decimalPlaces;
  1111. if (this.currentValue === null) {
  1112. targetNum = this._validateNum(num); // 修复:校验入参
  1113. decimalPlaces = arguments.length >= 2 ? n : 2;
  1114. } else {
  1115. targetNum = this.currentValue;
  1116. decimalPlaces = num !== undefined ? num : 2;
  1117. }
  1118. decimalPlaces = Math.max(0, Math.floor(parseInt(decimalPlaces, 10) || 0));
  1119. const pow10 = Math.pow(10, decimalPlaces);
  1120. this.currentValue = Math.round(targetNum * pow10) / pow10;
  1121. return this;
  1122. },
  1123. /**
  1124. * 截断保留指定小数位
  1125. */
  1126. truncate(num, n) {
  1127. let targetNum, decimalPlaces;
  1128. if (this.currentValue === null) {
  1129. targetNum = this._validateNum(num); // 修复:校验入参
  1130. decimalPlaces = arguments.length >= 2 ? n : 2;
  1131. } else {
  1132. targetNum = this.currentValue;
  1133. decimalPlaces = num !== undefined ? num : 2;
  1134. }
  1135. decimalPlaces = Math.max(0, Math.floor(parseInt(decimalPlaces, 10) || 0));
  1136. const numStr = targetNum.toString();
  1137. const dotIndex = numStr.indexOf(".");
  1138. let integerPart, decimalPart;
  1139. if (dotIndex === -1) {
  1140. integerPart = numStr;
  1141. decimalPart = "";
  1142. } else {
  1143. integerPart = numStr.substring(0, dotIndex);
  1144. decimalPart = numStr.substring(dotIndex + 1);
  1145. }
  1146. let truncatedDecimal;
  1147. if (decimalPlaces === 0) {
  1148. truncatedDecimal = "";
  1149. } else {
  1150. truncatedDecimal = decimalPart.substring(0, decimalPlaces);
  1151. if (truncatedDecimal.length < decimalPlaces) {
  1152. truncatedDecimal = truncatedDecimal.padEnd(decimalPlaces, "0");
  1153. }
  1154. }
  1155. let resultStr;
  1156. if (decimalPlaces === 0) {
  1157. resultStr = integerPart;
  1158. } else {
  1159. resultStr = `${integerPart}.${truncatedDecimal}`;
  1160. }
  1161. this.currentValue = parseFloat(resultStr);
  1162. return this;
  1163. },
  1164. /**
  1165. * 保留两位小数,若第三位小数大于0则进一
  1166. */
  1167. fixedUpTwo(num) {
  1168. // 处理目标数值:链式调用用currentValue,直接调用用传入的num
  1169. let targetNum =
  1170. this.currentValue === null ? this._validateNum(num) : this.currentValue;
  1171. // 处理NaN/非数值情况(已被_validateNum兜底,此处冗余校验)
  1172. if (isNaN(targetNum)) {
  1173. this.currentValue = 0.0;
  1174. return this;
  1175. }
  1176. const multiplied = targetNum * 1000;
  1177. const integerPart = Math.floor(multiplied);
  1178. const thirdDecimal = integerPart % 10;
  1179. let result;
  1180. if (thirdDecimal > 0) {
  1181. result = (Math.floor(targetNum * 100) + 1) / 100;
  1182. } else {
  1183. result = Math.floor(targetNum * 100) / 100;
  1184. }
  1185. this.currentValue = parseFloat(result.toFixed(2));
  1186. return this;
  1187. },
  1188. // 获取最终值
  1189. valueOf() {
  1190. const result = this.currentValue;
  1191. this._reset();
  1192. return result;
  1193. },
  1194. };