util.js 25 KB

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