util.js 24 KB

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