util.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  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. await footprintScan(obj);
  880. await appStore.USERINFO();
  881. }
  882. console.log("获取邀请码-params", params);
  883. return params;
  884. }
  885. return {};
  886. }
  887. // 获取用户所有的加盟角色列表
  888. export async function getJoinTeamUserRoles() {
  889. let join_roles = [];
  890. const { data: list } = await getJoinRolesAPI();
  891. list.forEach((item) => {
  892. join_roles.push(item.roleName);
  893. });
  894. return join_roles;
  895. }
  896. // 为用户添加加盟角色(推荐官)
  897. // addRecommenderRole();
  898. //
  899. export async function addRecommenderRole(remark) {
  900. try {
  901. const appStore = useAppStore();
  902. const uid = appStore.uid;
  903. console.log("appStore", appStore.uid);
  904. if (!uid) {
  905. console.error("添加推荐官角色失败:用户ID不存在");
  906. uni.showToast({ title: "用户信息异常", icon: "none" });
  907. return;
  908. }
  909. const requestParams = {
  910. remark: remark || "自动成为推荐官",
  911. roleName: "推荐官",
  912. roleType: 2, // 2-推荐官
  913. uid,
  914. };
  915. const response = await addJoinTeamUserRole(requestParams);
  916. console.log("response", response);
  917. uni.showModal({
  918. title: "恭喜",
  919. content: "您已成为推荐官,推荐用户注册、消费立得好礼,是否立即查看?",
  920. confirmText: "立即查看",
  921. cancelText: "稍后",
  922. success: (res) => {
  923. if (res.confirm) {
  924. uni.navigateTo({
  925. url: "/pages/join_us/recommed",
  926. });
  927. }
  928. },
  929. });
  930. } catch (error) {
  931. console.error("添加推荐官角色请求异常:", error);
  932. uni.showToast({
  933. title: error || "网络异常,请稍后重试",
  934. icon: "none",
  935. duration: 2000,
  936. });
  937. }
  938. }
  939. /**
  940. * 精确计算工具(支持直接调用和链式调用)
  941. * 使用方法:
  942. * import { Calc } from '@/utils/util'
  943. *
  944. * // 直接计算(两个参数)
  945. * const sum = Calc.add(0.1, 0.2).valueOf(); // 0.3
  946. *
  947. * // 链式调用(后续方法传入一个参数,基于前一步结果计算)
  948. * const result = Calc.add(1, 2).sub(1).mul(3).div(2).fixed(1).valueOf(); // 3.0
  949. *
  950. * // 截断示例:40.66 截断2位 → 40.66;40.666 截断2位 → 40.66
  951. * const truncResult = Calc.truncate(40.666, 2).valueOf(); // 40.66
  952. *
  953. * // 注意点
  954. * 需要在最后调用一次.valueOf()获取最终值,否则会返回一个Calc对象。
  955. */
  956. export const Calc = {
  957. // 存储当前计算值
  958. currentValue: null,
  959. /**
  960. * 重置当前值(内部使用,确保每次计算独立性)
  961. */
  962. _reset() {
  963. this.currentValue = null;
  964. return this;
  965. },
  966. /**
  967. * 内部工具:校验并转换为有效数字(核心修复点)
  968. * @param {any} num - 待校验的数值
  969. * @returns {Number} 有效数字(无效则返回 0)
  970. */
  971. _validateNum(num) {
  972. // 过滤 Infinity/-Infinity/NaN/undefined/null/空字符串
  973. if (
  974. num === undefined ||
  975. num === null ||
  976. num === "" ||
  977. !isFinite(num) ||
  978. isNaN(Number(num))
  979. ) {
  980. return 0;
  981. }
  982. // 转换为数字类型(处理字符串数字,如 "123.45")
  983. return Number(num);
  984. },
  985. /**
  986. * 内部工具:解析数值字符串,返回整数部分、小数部分、小数位数、符号
  987. * @param {Number|String} num - 待解析的数值
  988. * @returns {Object} 解析结果
  989. */
  990. _parseNumStr(num) {
  991. // 第一步:先校验并转换为有效数字(修复 NaN 问题)
  992. const validNum = this._validateNum(num);
  993. const str = String(validNum).trim().replace(/^\+/, ""); // 移除正号
  994. const isNegative = str.startsWith("-");
  995. const absStr = isNegative ? str.slice(1) : str;
  996. const [integerPart = "0", decimalPart = "0"] = absStr.split(".");
  997. // 处理纯小数(如.123)或纯整数(如123.)的情况
  998. const cleanInteger = integerPart || "0";
  999. const cleanDecimal = decimalPart || "0";
  1000. return {
  1001. isNegative,
  1002. integerPart: cleanInteger,
  1003. decimalPart: cleanDecimal,
  1004. decimalLength: cleanDecimal.length,
  1005. };
  1006. },
  1007. /**
  1008. * 内部工具:对齐两个数的小数位数,转换为大整数
  1009. * @param {Number|String} num1 - 数值1
  1010. * @param {Number|String} num2 - 数值2
  1011. * @returns {Object} 对齐后的整数和缩放比例
  1012. */
  1013. _alignDecimals(num1, num2) {
  1014. const n1 = this._parseNumStr(num1);
  1015. const n2 = this._parseNumStr(num2);
  1016. const maxDecimalLen = Math.max(n1.decimalLength, n2.decimalLength);
  1017. // 补零对齐小数位数
  1018. const n1DecimalPadded = n1.decimalPart.padEnd(maxDecimalLen, "0");
  1019. const n2DecimalPadded = n2.decimalPart.padEnd(maxDecimalLen, "0");
  1020. // 转换为大整数(避免普通整数溢出)
  1021. const n1Int =
  1022. BigInt(n1.integerPart + n1DecimalPadded) * (n1.isNegative ? -1n : 1n);
  1023. const n2Int =
  1024. BigInt(n2.integerPart + n2DecimalPadded) * (n2.isNegative ? -1n : 1n);
  1025. return {
  1026. int1: n1Int,
  1027. int2: n2Int,
  1028. scale: BigInt(10 ** maxDecimalLen), // 缩放比例(10^最大小数位数)
  1029. };
  1030. },
  1031. /**
  1032. * 加法运算(修复精度问题 + 入参校验)
  1033. */
  1034. add(a, b) {
  1035. // 链式调用/直接调用参数处理
  1036. const [arg1, arg2] =
  1037. this.currentValue === null ? [a, b] : [this.currentValue, a];
  1038. const { int1, int2, scale } = this._alignDecimals(arg1, arg2);
  1039. const sumInt = int1 + int2;
  1040. // 转换回小数(BigInt转Number,确保精度)
  1041. this.currentValue = Number(sumInt) / Number(scale);
  1042. return this;
  1043. },
  1044. /**
  1045. * 减法运算(修复精度问题 + 入参校验)
  1046. */
  1047. sub(a, b) {
  1048. const [arg1, arg2] =
  1049. this.currentValue === null ? [a, b] : [this.currentValue, a];
  1050. const { int1, int2, scale } = this._alignDecimals(arg1, arg2);
  1051. const subInt = int1 - int2;
  1052. this.currentValue = Number(subInt) / Number(scale);
  1053. return this;
  1054. },
  1055. /**
  1056. * 乘法运算(修复精度问题 + 入参校验)
  1057. */
  1058. mul(a, b) {
  1059. const [arg1, arg2] =
  1060. this.currentValue === null ? [a, b] : [this.currentValue, a];
  1061. const n1 = this._parseNumStr(arg1);
  1062. const n2 = this._parseNumStr(arg2);
  1063. // 转换为整数(移除小数点)
  1064. const n1Int =
  1065. BigInt(n1.integerPart + n1.decimalPart) * (n1.isNegative ? -1n : 1n);
  1066. const n2Int =
  1067. BigInt(n2.integerPart + n2.decimalPart) * (n2.isNegative ? -1n : 1n);
  1068. // 总小数位数
  1069. const totalDecimalLen = n1.decimalLength + n2.decimalLength;
  1070. const scale = BigInt(10 ** totalDecimalLen);
  1071. // 相乘后除以缩放比例
  1072. const mulInt = n1Int * n2Int;
  1073. this.currentValue = Number(mulInt) / Number(scale);
  1074. return this;
  1075. },
  1076. /**
  1077. * 除法运算(修复精度问题 + 入参校验)
  1078. */
  1079. div(a, b) {
  1080. const [arg1, arg2] =
  1081. this.currentValue === null ? [a, b] : [this.currentValue, a];
  1082. // 先校验除数是否为有效数字(避免 0/NaN 混淆)
  1083. const validArg2 = this._validateNum(arg2);
  1084. if (validArg2 === 0) {
  1085. throw new Error("除数不能为0");
  1086. }
  1087. const n1 = this._parseNumStr(arg1);
  1088. const n2 = this._parseNumStr(arg2);
  1089. // 转换为整数(移除小数点)
  1090. const n1Int =
  1091. BigInt(n1.integerPart + n1.decimalPart) * (n1.isNegative ? -1n : 1n);
  1092. const n2Int =
  1093. BigInt(n2.integerPart + n2.decimalPart) * (n2.isNegative ? -1n : 1n);
  1094. // 计算缩放比例:10^(n2小数位数 - n1小数位数)
  1095. const decimalDiff = n2.decimalLength - n1.decimalLength;
  1096. const scale = BigInt(10 ** Math.abs(decimalDiff));
  1097. let divResult;
  1098. if (decimalDiff >= 0) {
  1099. divResult = (n1Int * scale) / n2Int;
  1100. } else {
  1101. divResult = n1Int / (n2Int * scale);
  1102. }
  1103. // 处理除法精度(保留15位小数,避免无限循环)
  1104. this.currentValue =
  1105. Number(divResult) / Number(BigInt(10 ** Math.max(0, -decimalDiff)));
  1106. return this;
  1107. },
  1108. /**
  1109. * 四舍五入保留指定小数位
  1110. */
  1111. fixed(num, n) {
  1112. let targetNum, decimalPlaces;
  1113. if (this.currentValue === null) {
  1114. targetNum = this._validateNum(num); // 修复:校验入参
  1115. decimalPlaces = arguments.length >= 2 ? n : 2;
  1116. } else {
  1117. targetNum = this.currentValue;
  1118. decimalPlaces = num !== undefined ? num : 2;
  1119. }
  1120. decimalPlaces = Math.max(0, Math.floor(parseInt(decimalPlaces, 10) || 0));
  1121. const pow10 = Math.pow(10, decimalPlaces);
  1122. this.currentValue = Math.round(targetNum * pow10) / pow10;
  1123. return this;
  1124. },
  1125. /**
  1126. * 截断保留指定小数位
  1127. */
  1128. truncate(num, n) {
  1129. let targetNum, decimalPlaces;
  1130. if (this.currentValue === null) {
  1131. targetNum = this._validateNum(num); // 修复:校验入参
  1132. decimalPlaces = arguments.length >= 2 ? n : 2;
  1133. } else {
  1134. targetNum = this.currentValue;
  1135. decimalPlaces = num !== undefined ? num : 2;
  1136. }
  1137. decimalPlaces = Math.max(0, Math.floor(parseInt(decimalPlaces, 10) || 0));
  1138. const numStr = targetNum.toString();
  1139. const dotIndex = numStr.indexOf(".");
  1140. let integerPart, decimalPart;
  1141. if (dotIndex === -1) {
  1142. integerPart = numStr;
  1143. decimalPart = "";
  1144. } else {
  1145. integerPart = numStr.substring(0, dotIndex);
  1146. decimalPart = numStr.substring(dotIndex + 1);
  1147. }
  1148. let truncatedDecimal;
  1149. if (decimalPlaces === 0) {
  1150. truncatedDecimal = "";
  1151. } else {
  1152. truncatedDecimal = decimalPart.substring(0, decimalPlaces);
  1153. if (truncatedDecimal.length < decimalPlaces) {
  1154. truncatedDecimal = truncatedDecimal.padEnd(decimalPlaces, "0");
  1155. }
  1156. }
  1157. let resultStr;
  1158. if (decimalPlaces === 0) {
  1159. resultStr = integerPart;
  1160. } else {
  1161. resultStr = `${integerPart}.${truncatedDecimal}`;
  1162. }
  1163. this.currentValue = parseFloat(resultStr);
  1164. return this;
  1165. },
  1166. /**
  1167. * 保留两位小数,若第三位小数大于0则进一
  1168. */
  1169. fixedUpTwo(num) {
  1170. // 处理目标数值:链式调用用currentValue,直接调用用传入的num
  1171. let targetNum =
  1172. this.currentValue === null ? this._validateNum(num) : this.currentValue;
  1173. // 处理NaN/非数值情况(已被_validateNum兜底,此处冗余校验)
  1174. if (isNaN(targetNum)) {
  1175. this.currentValue = 0.0;
  1176. return this;
  1177. }
  1178. const multiplied = targetNum * 1000;
  1179. const integerPart = Math.floor(multiplied);
  1180. const thirdDecimal = integerPart % 10;
  1181. let result;
  1182. if (thirdDecimal > 0) {
  1183. result = (Math.floor(targetNum * 100) + 1) / 100;
  1184. } else {
  1185. result = Math.floor(targetNum * 100) / 100;
  1186. }
  1187. this.currentValue = parseFloat(result.toFixed(2));
  1188. return this;
  1189. },
  1190. // 获取最终值
  1191. valueOf() {
  1192. const result = this.currentValue;
  1193. this._reset();
  1194. return result;
  1195. },
  1196. };
  1197. export async function getPhoneNumber(e, inviteCode) {
  1198. const { Toast } = useToast();
  1199. console.log('getPhoneNumber123', e);
  1200. // 用户拒绝授权
  1201. if (e.detail.errMsg !== 'getPhoneNumber:ok') {
  1202. Toast({ title: '请授权手机号以完成登录' });
  1203. return null;
  1204. }
  1205. // 授权成功
  1206. if (e.detail.code) {
  1207. try {
  1208. // 2. 将授权码发送到后端换取手机号
  1209. const res = await wxLogin({ code: e.detail.code });
  1210. console.log('wxLogin接口res=', res);
  1211. // 3. 处理后端响应
  1212. if (res.code === 200) {
  1213. return res; // 返回数据
  1214. } else {
  1215. Toast({ title: res.message || '获取失败' });
  1216. return null;
  1217. }
  1218. } catch (error) {
  1219. Toast({ title: "获取手机号失败:" + error });
  1220. console.error('获取手机号失败:', error);
  1221. return null;
  1222. } finally {
  1223. }
  1224. } else {
  1225. // 授权失败
  1226. Toast({ title: e.detail?.errorMessage || "请允许授权以获取手机号" });
  1227. return null;
  1228. }
  1229. };