util.js 37 KB

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