util.js 25 KB

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