util.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. y += size + offset;
  154. ctx.beginPath();
  155. ctx.strokeStyle = color;
  156. ctx.lineWidth = thickness;
  157. ctx.moveTo(x, y);
  158. ctx.lineTo(x + width, y);
  159. ctx.stroke();
  160. };
  161. underline(ctx, "¥" + ot_price, 55, 865, 36, "#999", 2, 0);
  162. ctx.setTextAlign("left");
  163. ctx.setFontSize(28);
  164. ctx.setFillStyle("#999");
  165. ctx.fillText("长按或扫描查看", 490, 1030 + contentHh);
  166. ctx.draw(true, function () {
  167. uni.canvasToTempFilePath({
  168. canvasId: "firstCanvas",
  169. fileType: "png",
  170. destWidth: WIDTH,
  171. destHeight: HEIGHT,
  172. success: function (res) {
  173. // uni.hideLoading();
  174. successFn && successFn(res.tempFilePath);
  175. },
  176. });
  177. });
  178. },
  179. fail: function (err) {
  180. console.log("失败", err);
  181. uni.hideLoading();
  182. Toast({
  183. title: "无法获取图片信息",
  184. });
  185. },
  186. });
  187. },
  188. /**
  189. * 绘制文字自动换行
  190. * @param array arr2 海报素材
  191. * @param Number x , y 绘制的坐标
  192. * @param Number maxWigth 绘制文字的宽度
  193. * @param Number lineHeight 行高
  194. * @param Number maxRowNum 最大行数
  195. */
  196. canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
  197. if (
  198. typeof text != "string" ||
  199. typeof x != "number" ||
  200. typeof y != "number"
  201. ) {
  202. return;
  203. }
  204. // canvas.font = '20px Bold PingFang SC'; //绘制文字的字号和大小
  205. // 字符分隔为数组
  206. var arrText = text.split("");
  207. var line = "";
  208. var rowNum = 1;
  209. for (var n = 0; n < arrText.length; n++) {
  210. var testLine = line + arrText[n];
  211. var metrics = canvas.measureText(testLine);
  212. var testWidth = metrics.width;
  213. if (testWidth > maxWidth && n > 0) {
  214. if (rowNum >= maxRowNum) {
  215. var arrLine = testLine.split("");
  216. arrLine.splice(-9);
  217. var newTestLine = arrLine.join("");
  218. newTestLine += "...";
  219. canvas.fillText(newTestLine, x, y);
  220. //如果需要在省略号后面添加其他的东西,就在这个位置写(列如添加扫码查看详情字样)
  221. //canvas.fillStyle = '#2259CA';
  222. //canvas.fillText('扫码查看详情',x + maxWidth-90, y);
  223. return;
  224. }
  225. canvas.fillText(line, x, y);
  226. line = arrText[n];
  227. y += lineHeight;
  228. rowNum += 1;
  229. } else {
  230. line = testLine;
  231. }
  232. }
  233. canvas.fillText(line, x, y);
  234. },
  235. /**
  236. * 获取活动分享海报
  237. * @param array arr2 海报素材
  238. * @param string storeName 素材文字
  239. * @param string price 价格
  240. * @param string people 人数
  241. * @param string count 剩余人数
  242. * @param function successFn 回调函数
  243. */
  244. activityCanvas: function (
  245. arrImages,
  246. storeName,
  247. price,
  248. people,
  249. count,
  250. num,
  251. successFn
  252. ) {
  253. let that = this;
  254. let rain = 2;
  255. const { Toast } = useToast();
  256. const context = uni.createCanvasContext("activityCanvas");
  257. context.clearRect(0, 0, 0, 0);
  258. /**
  259. * 只能获取合法域名下的图片信息,本地调试无法获取
  260. *
  261. */
  262. context.fillStyle = "#fff";
  263. context.fillRect(0, 0, 594, 850);
  264. uni.getImageInfo({
  265. src: arrImages[0],
  266. success: function (res) {
  267. context.drawImage(arrImages[0], 0, 0, 594, 850);
  268. context.setFontSize(14 * rain);
  269. context.setFillStyle("#333333");
  270. that.canvasWraptitleText(
  271. context,
  272. storeName,
  273. 110 * rain,
  274. 110 * rain,
  275. 230 * rain,
  276. 30 * rain,
  277. 1
  278. );
  279. context.drawImage(
  280. arrImages[2],
  281. 68 * rain,
  282. 194 * rain,
  283. 160 * rain,
  284. 160 * rain
  285. );
  286. context.save();
  287. context.setFontSize(14 * rain);
  288. context.setFillStyle("#fc4141");
  289. context.fillText("¥", 157 * rain, 145 * rain);
  290. context.setFontSize(24 * rain);
  291. context.setFillStyle("#fc4141");
  292. context.fillText(price, 170 * rain, 145 * rain);
  293. context.setFontSize(10 * rain);
  294. context.setFillStyle("#fff");
  295. context.fillText(people, 118 * rain, 143 * rain);
  296. context.setFontSize(12 * rain);
  297. context.setFillStyle("#666666");
  298. context.setTextAlign("center");
  299. context.fillText(count, (167 - num) * rain, 166 * rain);
  300. that.handleBorderRect(
  301. context,
  302. 27 * rain,
  303. 94 * rain,
  304. 75 * rain,
  305. 75 * rain,
  306. 6 * rain
  307. );
  308. context.clip();
  309. context.drawImage(
  310. arrImages[1],
  311. 27 * rain,
  312. 94 * rain,
  313. 75 * rain,
  314. 75 * rain
  315. );
  316. context.draw(true, function () {
  317. uni.canvasToTempFilePath({
  318. canvasId: "activityCanvas",
  319. fileType: "png",
  320. destWidth: 594,
  321. destHeight: 850,
  322. success: function (res) {
  323. // uni.hideLoading();
  324. successFn && successFn(res.tempFilePath);
  325. },
  326. });
  327. });
  328. },
  329. fail: function (err) {
  330. console.log("失败", err);
  331. uni.hideLoading();
  332. Toast({
  333. title: "无法获取图片信息",
  334. });
  335. },
  336. });
  337. },
  338. /**
  339. * 图片圆角设置
  340. * @param string x x轴位置
  341. * @param string y y轴位置
  342. * @param string w 图片宽
  343. * @param string y 图片高
  344. * @param string r 圆角值
  345. */
  346. handleBorderRect(ctx, x, y, w, h, r) {
  347. ctx.beginPath();
  348. // 左上角
  349. ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
  350. ctx.moveTo(x + r, y);
  351. ctx.lineTo(x + w - r, y);
  352. ctx.lineTo(x + w, y + r);
  353. // 右上角
  354. ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
  355. ctx.lineTo(x + w, y + h - r);
  356. ctx.lineTo(x + w - r, y + h);
  357. // 右下角
  358. ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
  359. ctx.lineTo(x + r, y + h);
  360. ctx.lineTo(x, y + h - r);
  361. // 左下角
  362. ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
  363. ctx.lineTo(x, y + r);
  364. ctx.lineTo(x + r, y);
  365. ctx.fill();
  366. ctx.closePath();
  367. },
  368. /*
  369. * 单图上传
  370. * @param object opt
  371. * @param callable successCallback 成功执行方法 data
  372. * @param callable errorCallback 失败执行方法
  373. */
  374. uploadImageOne: function (opt, successCallback, errorCallback) {
  375. let that = this;
  376. const { Toast } = useToast();
  377. if (typeof opt === "string") {
  378. let url = opt;
  379. opt = {};
  380. opt.url = url;
  381. }
  382. let count = opt.count || 1,
  383. sizeType = opt.sizeType || ["compressed"],
  384. sourceType = opt.sourceType || ["album", "camera"],
  385. is_load = opt.is_load || true,
  386. uploadUrl = opt.url || "",
  387. inputName = opt.name || "pics",
  388. pid = opt.pid,
  389. model = opt.model;
  390. uni.chooseImage({
  391. count: count, //最多可以选择的图片总数
  392. sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
  393. sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
  394. success: function (res) {
  395. //启动上传等待中...
  396. uni.showLoading({
  397. title: "图片上传中",
  398. });
  399. let urlPath =
  400. HTTP_ADMIN_URL +
  401. "/api/admin/upload/image" +
  402. "?model=" +
  403. model +
  404. "&pid=" +
  405. pid;
  406. let localPath = res.tempFilePaths[0];
  407. const TOKEN = useAppStore.token;
  408. uni.uploadFile({
  409. url: urlPath,
  410. filePath: localPath,
  411. name: inputName,
  412. header: {
  413. // #ifdef MP
  414. "Content-Type": "multipart/form-data",
  415. // #endif
  416. [TOKENNAME]: TOKEN,
  417. },
  418. success: function (res) {
  419. uni.hideLoading();
  420. if (res.statusCode == 403) {
  421. Toast({
  422. title: res.data,
  423. });
  424. } else {
  425. let data = res.data ? JSON.parse(res.data) : {};
  426. if (data.code == 200) {
  427. data.data.localPath = localPath;
  428. successCallback && successCallback(data);
  429. } else {
  430. errorCallback && errorCallback(data);
  431. Toast({
  432. title: data.message,
  433. });
  434. }
  435. }
  436. },
  437. fail: function (res) {
  438. uni.hideLoading();
  439. Toast({
  440. title: "上传图片失败",
  441. });
  442. },
  443. });
  444. // pathToBase64(res.tempFilePaths[0])
  445. // .then(imgBase64 => {
  446. // console.log(imgBase64);
  447. // })
  448. // .catch(error => {
  449. // console.error(error)
  450. // })
  451. },
  452. });
  453. },
  454. /**
  455. * 处理服务器扫码带进来的参数
  456. * @param string param 扫码携带参数
  457. * @param string k 整体分割符 默认为:&
  458. * @param string p 单个分隔符 默认为:=
  459. * @return object
  460. *
  461. */
  462. // #ifdef MP
  463. getUrlParams: function (param, k, p) {
  464. if (typeof param != "string") return {};
  465. k = k ? k : "&"; //整体参数分隔符
  466. p = p ? p : "="; //单个参数分隔符
  467. var value = {};
  468. if (param.indexOf(k) !== -1) {
  469. param = param.split(k);
  470. for (var val in param) {
  471. if (param[val].indexOf(p) !== -1) {
  472. var item = param[val].split(p);
  473. value[item[0]] = item[1];
  474. }
  475. }
  476. } else if (param.indexOf(p) !== -1) {
  477. var item = param.split(p);
  478. value[item[0]] = item[1];
  479. } else {
  480. return param;
  481. }
  482. return value;
  483. },
  484. /**根据格式组装公共参数
  485. * @param {Object} value
  486. */
  487. formatMpQrCodeData(value) {
  488. let values = value.split(",");
  489. let result = {};
  490. if (values.length === 2) {
  491. let v1 = values[0].split(":");
  492. if (v1[0] === "pid") {
  493. result.spread = v1[1];
  494. } else {
  495. result.id = v1[1];
  496. }
  497. let v2 = values[1].split(":");
  498. if (v2[0] === "pid") {
  499. result.spread = v2[1];
  500. } else {
  501. result.id = v2[1];
  502. }
  503. } else {
  504. result = values[0].split(":")[1];
  505. }
  506. return result;
  507. },
  508. // #endif
  509. /*
  510. * 合并数组
  511. */
  512. SplitArray(list, sp) {
  513. if (!Array.isArray(list)) return [];
  514. return [...sp, ...list];
  515. },
  516. trim(str) {
  517. return String.prototype.trim.call(str);
  518. },
  519. $h: {
  520. //除法函数,用来得到精确的除法结果
  521. //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  522. //调用:$h.Div(arg1,arg2)
  523. //返回值:arg1除以arg2的精确结果
  524. Div: function (arg1, arg2) {
  525. arg1 = parseFloat(arg1);
  526. arg2 = parseFloat(arg2);
  527. var t1 = 0,
  528. t2 = 0,
  529. r1,
  530. r2;
  531. try {
  532. t1 = arg1.toString().split(".")[1].length;
  533. } catch (e) {}
  534. try {
  535. t2 = arg2.toString().split(".")[1].length;
  536. } catch (e) {}
  537. r1 = Number(arg1.toString().replace(".", ""));
  538. r2 = Number(arg2.toString().replace(".", ""));
  539. return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
  540. },
  541. //加法函数,用来得到精确的加法结果
  542. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  543. //调用:$h.Add(arg1,arg2)
  544. //返回值:arg1加上arg2的精确结果
  545. Add: function (arg1, arg2) {
  546. arg2 = parseFloat(arg2);
  547. var r1, r2, m;
  548. try {
  549. r1 = arg1.toString().split(".")[1].length;
  550. } catch (e) {
  551. r1 = 0;
  552. }
  553. try {
  554. r2 = arg2.toString().split(".")[1].length;
  555. } catch (e) {
  556. r2 = 0;
  557. }
  558. m = Math.pow(100, Math.max(r1, r2));
  559. return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  560. },
  561. //减法函数,用来得到精确的减法结果
  562. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  563. //调用:$h.Sub(arg1,arg2)
  564. //返回值:arg1减去arg2的精确结果
  565. Sub: function (arg1, arg2) {
  566. arg1 = parseFloat(arg1);
  567. arg2 = parseFloat(arg2);
  568. var r1, r2, m, n;
  569. try {
  570. r1 = arg1.toString().split(".")[1].length;
  571. } catch (e) {
  572. r1 = 0;
  573. }
  574. try {
  575. r2 = arg2.toString().split(".")[1].length;
  576. } catch (e) {
  577. r2 = 0;
  578. }
  579. m = Math.pow(10, Math.max(r1, r2));
  580. //动态控制精度长度
  581. n = r1 >= r2 ? r1 : r2;
  582. return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  583. },
  584. //乘法函数,用来得到精确的乘法结果
  585. //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  586. //调用:$h.Mul(arg1,arg2)
  587. //返回值:arg1乘以arg2的精确结果
  588. Mul: function (arg1, arg2) {
  589. arg1 = parseFloat(arg1);
  590. arg2 = parseFloat(arg2);
  591. var m = 0,
  592. s1 = arg1.toString(),
  593. s2 = arg2.toString();
  594. try {
  595. m += s1.split(".")[1].length;
  596. } catch (e) {}
  597. try {
  598. m += s2.split(".")[1].length;
  599. } catch (e) {}
  600. return (
  601. (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
  602. Math.pow(10, m)
  603. );
  604. },
  605. },
  606. // 获取地理位置;
  607. $L: {
  608. async getLocation() {
  609. // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
  610. let status = await this.getSetting();
  611. if (status === 2) {
  612. this.openSetting();
  613. return;
  614. }
  615. // #endif
  616. this.doGetLocation();
  617. },
  618. doGetLocation() {
  619. uni.getLocation({
  620. success: (res) => {
  621. uni.removeStorageSync("CACHE_LONGITUDE");
  622. uni.removeStorageSync("CACHE_LATITUDE");
  623. uni.setStorageSync("CACHE_LONGITUDE", res.longitude);
  624. uni.setStorageSync("CACHE_LATITUDE", res.latitude);
  625. },
  626. fail: (err) => {
  627. // #ifdef MP-BAIDU
  628. if (err.errCode === 202 || err.errCode === 10003) {
  629. // 202模拟器 10003真机 user deny
  630. this.openSetting();
  631. }
  632. // #endif
  633. // #ifndef MP-BAIDU
  634. if (err.errMsg.indexOf("auth deny") >= 0) {
  635. Toast({
  636. title: "访问位置被拒绝",
  637. });
  638. } else {
  639. Toast({
  640. title: err.errMsg,
  641. });
  642. }
  643. // #endif
  644. },
  645. });
  646. },
  647. getSetting: function () {
  648. return new Promise((resolve, reject) => {
  649. uni.getSetting({
  650. success: (res) => {
  651. if (res.authSetting["scope.userLocation"] === undefined) {
  652. resolve(0);
  653. return;
  654. }
  655. if (res.authSetting["scope.userLocation"]) {
  656. resolve(1);
  657. } else {
  658. resolve(2);
  659. }
  660. },
  661. });
  662. });
  663. },
  664. openSetting: function () {
  665. uni.openSetting({
  666. success: (res) => {
  667. if (res.authSetting && res.authSetting["scope.userLocation"]) {
  668. this.doGetLocation();
  669. }
  670. },
  671. fail: (err) => {},
  672. });
  673. },
  674. async checkPermission() {
  675. let status = permision.isIOS
  676. ? await permision.requestIOS("location")
  677. : await permision.requestAndroid(
  678. "android.permission.ACCESS_FINE_LOCATION"
  679. );
  680. if (status === null || status === 1) {
  681. status = 1;
  682. } else if (status === 2) {
  683. uni.showModal({
  684. content: "系统定位已关闭",
  685. confirmText: "确定",
  686. showCancel: false,
  687. success: function (res) {},
  688. });
  689. } else if (status.code) {
  690. uni.showModal({
  691. content: status.message,
  692. });
  693. } else {
  694. uni.showModal({
  695. content: "需要定位权限",
  696. confirmText: "设置",
  697. success: function (res) {
  698. if (res.confirm) {
  699. permision.gotoAppSetting();
  700. }
  701. },
  702. });
  703. }
  704. return status;
  705. },
  706. },
  707. toStringValue: function (obj) {
  708. if (obj instanceof Array) {
  709. var arr = [];
  710. for (var i = 0; i < obj.length; i++) {
  711. arr[i] = toStringValue(obj[i]);
  712. }
  713. return arr;
  714. } else if (typeof obj == "object") {
  715. for (var p in obj) {
  716. obj[p] = toStringValue(obj[p]);
  717. }
  718. } else if (typeof obj == "number") {
  719. obj = obj + "";
  720. }
  721. return obj;
  722. },
  723. /*
  724. * 替换域名
  725. */
  726. setDomain: function (url) {
  727. url = url ? url.toString() : "";
  728. if (url.indexOf("https://") > -1) return url;
  729. else return url.replace("http://", "https://");
  730. },
  731. /**
  732. * 姓名除了姓显示其他
  733. */
  734. formatName: function (str) {
  735. return str.substr(0, 1) + new Array(str.length).join("*");
  736. },
  737. /**
  738. * rpx转px
  739. */
  740. rpxToPx(rpx) {
  741. const screenWidth = uni.getSystemInfoSync().screenWidth;
  742. return (screenWidth * Number.parseInt(rpx)) / 750;
  743. },
  744. /**
  745. * px 转换 rpx
  746. */
  747. pxToRpx: function (px) {
  748. const screenWidth = uni.getSystemInfoSync().screenWidth;
  749. return (750 * Number.parseInt(px)) / screenWidth;
  750. },
  751. };
  752. /**
  753. * 格式化日期
  754. * @prama t 时间戳
  755. * @return str MM-dd HH:mm
  756. */
  757. export function formatDate(t) {
  758. t = t || Date.now();
  759. let time = new Date(t);
  760. let str =
  761. time.getMonth() < 9 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1;
  762. str += "-";
  763. str += time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
  764. str += " ";
  765. str += time.getHours();
  766. str += ":";
  767. str += time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
  768. return str;
  769. }
  770. export function previewImage(urls = []) {
  771. if (!urls.length) return;
  772. uni.previewImage({
  773. urls,
  774. });
  775. }
  776. export function telEncrypt(tel = "") {
  777. let str = tel + "";
  778. let enStr = str.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
  779. return enStr;
  780. }
  781. /*
  782. * 随机数生成
  783. */
  784. export function generateCustomId(prefix) {
  785. // 验证前缀长度
  786. if (prefix.length <= 0) {
  787. throw new Error("必须附带前缀");
  788. }
  789. if (prefix.length > 6) {
  790. throw new Error("前缀太长,仅支持6位");
  791. }
  792. // 获取当前时间并格式化为年月日后两位+时分秒+毫秒
  793. const now = new Date();
  794. const year = String(now.getFullYear()).slice(-2);
  795. const month = String(now.getMonth() + 1).padStart(2, "0");
  796. const day = String(now.getDate()).padStart(2, "0");
  797. const hours = String(now.getHours()).padStart(2, "0");
  798. const minutes = String(now.getMinutes()).padStart(2, "0");
  799. const seconds = String(now.getSeconds()).padStart(2, "0");
  800. const milliseconds = String(now.getMilliseconds()).padStart(3, "0");
  801. // 组合时间部分(精确到毫秒)
  802. const timePart =
  803. year + month + day + hours + minutes + seconds + milliseconds;
  804. // 生成8位随机字符
  805. const chars =
  806. "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  807. let randomPart = "";
  808. for (let i = 0; i < 8; i++) {
  809. const randomIndex = Math.floor(Math.random() * chars.length);
  810. randomPart += chars[randomIndex];
  811. }
  812. // 组合生成ID
  813. return `${prefix}-${timePart}-${randomPart}`;
  814. }
  815. /**
  816. * 判断图片地址是否包含 HTTPS 协议
  817. * @param {string} imageUrl - 图片地址
  818. * @returns {string} 包含HTTPS则返回原图片地址,否则返回拼接oss对象存储地址
  819. */
  820. export function isHttpsImage(imageUrl) {
  821. if (typeof imageUrl !== "string" || !imageUrl) {
  822. return "/static/avator.png";
  823. }
  824. const trimmedUrl = imageUrl.trim();
  825. if (trimmedUrl.includes("https://")) {
  826. return imageUrl;
  827. } else {
  828. return BASE_OSS_URL + imageUrl;
  829. }
  830. }
  831. // 判断当前页面是否为 tabBar 页面
  832. export function isTabBarPage() {
  833. // 获取当前页面栈
  834. const pages = getCurrentPages();
  835. // 获取当前页面路径(不包含参数部分)
  836. if(!pages[pages.length - 1]){
  837. return false;
  838. }
  839. const currentPagePath = pages[pages.length - 1].route;
  840. // 获取 app.json 中的 tabBar 配置
  841. const tabBarPages = getApp().globalData.tabBarPages || (() => {
  842. // 从 app.json 中读取 tabBar 配置
  843. // const appJson = import('@/pages.json');
  844. // console.log('pageJson', pageJson)
  845. const tabBarList = pageJson.tabBar ? pageJson.tabBar.list : [];
  846. // 提取所有 tabBar 页面的路径
  847. const pages = tabBarList.map(item => item.pagePath);
  848. // 缓存到全局数据中,避免重复解析
  849. getApp().globalData.tabBarPages = pages;
  850. return pages;
  851. })();
  852. // 判断当前页面是否在 tabBar 配置中
  853. return tabBarPages.includes(currentPagePath);
  854. }
  855. // 获取邀请码
  856. export async function getSceneInfo (e,index) {
  857. if (e.scene) {
  858. const decodedScene = decodeURIComponent(e.scene);
  859. const params = {};
  860. if (decodedScene) {
  861. decodedScene.split('&').forEach(item => {
  862. const [key, value] = item.split('=');
  863. if (key && value) {
  864. params[key] = value;
  865. }
  866. });
  867. }
  868. if (params.merchantId) appStore.UPDATE_MERCHANT_ID(params.merchantId);
  869. if(index == 'index' && appStore.userInfo){
  870. let obj ={
  871. merchantId:params.merchantId,
  872. userId:appStore.userInfo.userId
  873. }
  874. await footprintScan(obj)
  875. }
  876. console.log("获取邀请码-params", params)
  877. return params;
  878. }
  879. return {};
  880. }
  881. // 获取用户所有的加盟角色列表
  882. export async function getJoinTeamUserRoles() {
  883. let join_roles = [];
  884. const { data: list } = await getJoinRolesAPI();
  885. list.forEach((item) => {
  886. join_roles.push(item.roleName);
  887. });
  888. return join_roles;
  889. }
  890. // 为用户添加加盟角色(推荐官)
  891. // addRecommenderRole();
  892. //
  893. export async function addRecommenderRole(remark) {
  894. try {
  895. const appStore = useAppStore();
  896. const uid = appStore.uid;
  897. console.log("appStore", appStore.uid);
  898. if (!uid) {
  899. console.error("添加推荐官角色失败:用户ID不存在");
  900. uni.showToast({ title: "用户信息异常", icon: "none" });
  901. return;
  902. }
  903. const requestParams = {
  904. remark: remark || "自动成为推荐官",
  905. roleName: "推荐官",
  906. roleType: 2, // 2-推荐官
  907. uid,
  908. };
  909. const response = await addJoinTeamUserRole(requestParams);
  910. console.log("response", response);
  911. uni.showModal({
  912. title: "恭喜",
  913. content: "您已成为推荐官,推荐用户注册、消费立得好礼,是否立即查看?",
  914. confirmText: "立即查看",
  915. cancelText: "稍后",
  916. success: (res) => {
  917. if (res.confirm) {
  918. uni.navigateTo({
  919. url: "/pages/join_us/recommed",
  920. });
  921. }
  922. },
  923. });
  924. } catch (error) {
  925. console.error("添加推荐官角色请求异常:", error);
  926. uni.showToast({
  927. title: error || "网络异常,请稍后重试",
  928. icon: "none",
  929. duration: 2000,
  930. });
  931. }
  932. }