| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285 |
- import { TOKENNAME, HTTP_REQUEST_URL } from "../config/app.js";
- import { HTTP_ADMIN_URL, BASE_OSS_URL } from "@/config/app.js";
- import { useAppStore } from "@/stores/app.js";
- import { addJoinTeamUserRole } from "@/api/api.js";
- import { getJoinRolesAPI } from "@/api/joinus";
- import { footprintScan } from "@/api/merchant.js";
- import { pathToBase64 } from "@/plugin/image-tools/index.js";
- import { useToast } from "@/hooks/useToast";
- import pageJson from "@/pages.json";
- const appStore = useAppStore(); // 调用函数获取实例
- export default {
- /**
- * 移除数组中的某个数组并组成新的数组返回
- * @param array array 需要移除的数组
- * @param int index 需要移除的数组的键值
- * @param string | int 值
- * @return array
- *
- */
- ArrayRemove: function (array, index, value) {
- const valueArray = [];
- if (array instanceof Array) {
- for (let i = 0; i < array.length; i++) {
- if (typeof index == "number" && array[index] != i) {
- valueArray.push(array[i]);
- } else if (typeof index == "string" && array[i][index] != value) {
- valueArray.push(array[i]);
- }
- }
- }
- return valueArray;
- },
- /**
- * 生成海报获取文字
- * @param string text 为传入的文本
- * @param int num 为单行显示的字节长度
- * @return array
- */
- textByteLength: function (text, num) {
- let strLength = 0;
- let rows = 1;
- let str = 0;
- let arr = [];
- for (let j = 0; j < text.length; j++) {
- if (text.charCodeAt(j) > 255) {
- strLength += 2;
- if (strLength > rows * num) {
- strLength++;
- arr.push(text.slice(str, j));
- str = j;
- rows++;
- }
- } else {
- strLength++;
- if (strLength > rows * num) {
- arr.push(text.slice(str, j));
- str = j;
- rows++;
- }
- }
- }
- arr.push(text.slice(str, text.length));
- return [strLength, arr, rows]; // [处理文字的总字节长度,每行显示内容的数组,行数]
- },
- /**
- * 获取分享海报
- * @param array arr2 海报素材
- * @param string store_name 素材文字
- * @param string price 价格
- * @param string ot_price 原始价格
- * @param function successFn 回调函数
- *
- *
- */
- PosterCanvas: function (arr2, store_name, price, ot_price, successFn) {
- let that = this;
- const { Toast } = useToast();
- const ctx = uni.createCanvasContext("firstCanvas");
- ctx.clearRect(0, 0, 0, 0);
- /**
- * 只能获取合法域名下的图片信息,本地调试无法获取
- *
- */
- ctx.fillStyle = "#fff";
- ctx.fillRect(0, 0, 750, 1150);
- uni.getImageInfo({
- src: arr2[0],
- success: function (res) {
- const WIDTH = res.width;
- const HEIGHT = res.height;
- // ctx.drawImage(arr2[0], 0, 0, WIDTH, 1050);
- ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
- ctx.save();
- let r = 110;
- let d = r * 2;
- let cx = 480;
- let cy = 790;
- ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
- // ctx.clip();
- ctx.drawImage(arr2[2], cx, cy, d, d);
- ctx.restore();
- const CONTENT_ROW_LENGTH = 20;
- let [contentLeng, contentArray, contentRows] = that.textByteLength(
- store_name,
- CONTENT_ROW_LENGTH
- );
- if (contentRows > 2) {
- contentRows = 2;
- let textArray = contentArray.slice(0, 2);
- textArray[textArray.length - 1] += "……";
- contentArray = textArray;
- }
- ctx.setTextAlign("left");
- ctx.setFontSize(36);
- ctx.setFillStyle("#000");
- // let contentHh = 36 * 1.5;
- let contentHh = 36;
- for (let m = 0; m < contentArray.length; m++) {
- // ctx.fillText(contentArray[m], 50, 1000 + contentHh * m,750);
- if (m) {
- ctx.fillText(contentArray[m], 50, 1000 + contentHh * m + 18, 1100);
- } else {
- ctx.fillText(contentArray[m], 50, 1000 + contentHh * m, 1100);
- }
- }
- ctx.setTextAlign("left");
- ctx.setFontSize(72);
- ctx.setFillStyle("#DA4F2A");
- ctx.fillText("¥" + price, 40, 820 + contentHh);
- // ctx.setTextAlign("left");
- // ctx.setFontSize(36);
- // ctx.setFillStyle("#999");
- // ctx.fillText("¥" + ot_price, 50, 876 + contentHh);
- // var underline = function (
- // ctx,
- // text,
- // x,
- // y,
- // size,
- // color,
- // thickness,
- // offset
- // ) {
- // var width = ctx.measureText(text).width;
- // switch (ctx.textAlign) {
- // case "center":
- // x -= width / 2;
- // break;
- // case "right":
- // x -= width;
- // break;
- // }
- //
- // y += size + offset;
- //
- // ctx.beginPath();
- // ctx.strokeStyle = color;
- // ctx.lineWidth = thickness;
- // ctx.moveTo(x, y);
- // ctx.lineTo(x + width, y);
- // ctx.stroke();
- // };
- // underline(ctx, "¥" + ot_price, 55, 865, 36, "#999", 2, 0);
- ctx.setTextAlign("left");
- ctx.setFontSize(28);
- ctx.setFillStyle("#999");
- ctx.fillText("长按或扫描查看", 490, 1030 + contentHh);
- ctx.draw(true, function () {
- uni.canvasToTempFilePath({
- canvasId: "firstCanvas",
- fileType: "png",
- destWidth: WIDTH,
- destHeight: HEIGHT,
- success: function (res) {
- // uni.hideLoading();
- successFn && successFn(res.tempFilePath);
- },
- });
- });
- },
- fail: function (err) {
- console.log("失败", err);
- uni.hideLoading();
- Toast({
- title: "无法获取图片信息",
- });
- },
- });
- },
- /**
- * 绘制文字自动换行
- * @param array arr2 海报素材
- * @param Number x , y 绘制的坐标
- * @param Number maxWigth 绘制文字的宽度
- * @param Number lineHeight 行高
- * @param Number maxRowNum 最大行数
- */
- canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
- if (
- typeof text != "string" ||
- typeof x != "number" ||
- typeof y != "number"
- ) {
- return;
- }
- // canvas.font = '20px Bold PingFang SC'; //绘制文字的字号和大小
- // 字符分隔为数组
- var arrText = text.split("");
- var line = "";
- var rowNum = 1;
- for (var n = 0; n < arrText.length; n++) {
- var testLine = line + arrText[n];
- var metrics = canvas.measureText(testLine);
- var testWidth = metrics.width;
- if (testWidth > maxWidth && n > 0) {
- if (rowNum >= maxRowNum) {
- var arrLine = testLine.split("");
- arrLine.splice(-9);
- var newTestLine = arrLine.join("");
- newTestLine += "...";
- canvas.fillText(newTestLine, x, y);
- //如果需要在省略号后面添加其他的东西,就在这个位置写(列如添加扫码查看详情字样)
- //canvas.fillStyle = '#2259CA';
- //canvas.fillText('扫码查看详情',x + maxWidth-90, y);
- return;
- }
- canvas.fillText(line, x, y);
- line = arrText[n];
- y += lineHeight;
- rowNum += 1;
- } else {
- line = testLine;
- }
- }
- canvas.fillText(line, x, y);
- },
- /**
- * 获取活动分享海报
- * @param array arr2 海报素材
- * @param string storeName 素材文字
- * @param string price 价格
- * @param string people 人数
- * @param string count 剩余人数
- * @param function successFn 回调函数
- */
- activityCanvas: function (
- arrImages,
- storeName,
- price,
- people,
- count,
- num,
- successFn
- ) {
- let that = this;
- let rain = 2;
- const { Toast } = useToast();
- const context = uni.createCanvasContext("activityCanvas");
- context.clearRect(0, 0, 0, 0);
- /**
- * 只能获取合法域名下的图片信息,本地调试无法获取
- *
- */
- context.fillStyle = "#fff";
- context.fillRect(0, 0, 594, 850);
- uni.getImageInfo({
- src: arrImages[0],
- success: function (res) {
- context.drawImage(arrImages[0], 0, 0, 594, 850);
- context.setFontSize(14 * rain);
- context.setFillStyle("#333333");
- that.canvasWraptitleText(
- context,
- storeName,
- 110 * rain,
- 110 * rain,
- 230 * rain,
- 30 * rain,
- 1
- );
- context.drawImage(
- arrImages[2],
- 68 * rain,
- 194 * rain,
- 160 * rain,
- 160 * rain
- );
- context.save();
- context.setFontSize(14 * rain);
- context.setFillStyle("#fc4141");
- context.fillText("¥", 157 * rain, 145 * rain);
- context.setFontSize(24 * rain);
- context.setFillStyle("#fc4141");
- context.fillText(price, 170 * rain, 145 * rain);
- context.setFontSize(10 * rain);
- context.setFillStyle("#fff");
- context.fillText(people, 118 * rain, 143 * rain);
- context.setFontSize(12 * rain);
- context.setFillStyle("#666666");
- context.setTextAlign("center");
- context.fillText(count, (167 - num) * rain, 166 * rain);
- that.handleBorderRect(
- context,
- 27 * rain,
- 94 * rain,
- 75 * rain,
- 75 * rain,
- 6 * rain
- );
- context.clip();
- context.drawImage(
- arrImages[1],
- 27 * rain,
- 94 * rain,
- 75 * rain,
- 75 * rain
- );
- context.draw(true, function () {
- uni.canvasToTempFilePath({
- canvasId: "activityCanvas",
- fileType: "png",
- destWidth: 594,
- destHeight: 850,
- success: function (res) {
- // uni.hideLoading();
- successFn && successFn(res.tempFilePath);
- },
- });
- });
- },
- fail: function (err) {
- console.log("失败", err);
- uni.hideLoading();
- Toast({
- title: "无法获取图片信息",
- });
- },
- });
- },
- /**
- * 图片圆角设置
- * @param string x x轴位置
- * @param string y y轴位置
- * @param string w 图片宽
- * @param string y 图片高
- * @param string r 圆角值
- */
- handleBorderRect(ctx, x, y, w, h, r) {
- ctx.beginPath();
- // 左上角
- ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
- ctx.moveTo(x + r, y);
- ctx.lineTo(x + w - r, y);
- ctx.lineTo(x + w, y + r);
- // 右上角
- ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
- ctx.lineTo(x + w, y + h - r);
- ctx.lineTo(x + w - r, y + h);
- // 右下角
- ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
- ctx.lineTo(x + r, y + h);
- ctx.lineTo(x, y + h - r);
- // 左下角
- ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
- ctx.lineTo(x, y + r);
- ctx.lineTo(x + r, y);
- ctx.fill();
- ctx.closePath();
- },
- /*
- * 单图上传
- * @param object opt
- * @param callable successCallback 成功执行方法 data
- * @param callable errorCallback 失败执行方法
- */
- uploadImageOne: function (opt, successCallback, errorCallback) {
- let that = this;
- const { Toast } = useToast();
- if (typeof opt === "string") {
- let url = opt;
- opt = {};
- opt.url = url;
- }
- let count = opt.count || 1,
- sizeType = opt.sizeType || ["compressed"],
- sourceType = opt.sourceType || ["album", "camera"],
- is_load = opt.is_load || true,
- uploadUrl = opt.url || "",
- inputName = opt.name || "pics",
- pid = opt.pid,
- model = opt.model;
- uni.chooseImage({
- count: count, //最多可以选择的图片总数
- sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
- sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
- success: function (res) {
- //启动上传等待中...
- uni.showLoading({
- title: "图片上传中",
- });
- let urlPath =
- HTTP_ADMIN_URL +
- "/api/admin/upload/image" +
- "?model=" +
- model +
- "&pid=" +
- pid;
- let localPath = res.tempFilePaths[0];
- const TOKEN = useAppStore.token;
- uni.uploadFile({
- url: urlPath,
- filePath: localPath,
- name: inputName,
- header: {
- // #ifdef MP
- "Content-Type": "multipart/form-data",
- // #endif
- [TOKENNAME]: TOKEN,
- },
- success: function (res) {
- uni.hideLoading();
- if (res.statusCode == 403) {
- Toast({
- title: res.data,
- });
- } else {
- let data = res.data ? JSON.parse(res.data) : {};
- if (data.code == 200) {
- data.data.localPath = localPath;
- successCallback && successCallback(data);
- } else {
- errorCallback && errorCallback(data);
- Toast({
- title: data.message,
- });
- }
- }
- },
- fail: function (res) {
- uni.hideLoading();
- Toast({
- title: "上传图片失败",
- });
- },
- });
- // pathToBase64(res.tempFilePaths[0])
- // .then(imgBase64 => {
- // console.log(imgBase64);
- // })
- // .catch(error => {
- // console.error(error)
- // })
- },
- });
- },
- /**
- * 处理服务器扫码带进来的参数
- * @param string param 扫码携带参数
- * @param string k 整体分割符 默认为:&
- * @param string p 单个分隔符 默认为:=
- * @return object
- *
- */
- // #ifdef MP
- getUrlParams: function (param, k, p) {
- if (typeof param != "string") return {};
- k = k ? k : "&"; //整体参数分隔符
- p = p ? p : "="; //单个参数分隔符
- var value = {};
- if (param.indexOf(k) !== -1) {
- param = param.split(k);
- for (var val in param) {
- if (param[val].indexOf(p) !== -1) {
- var item = param[val].split(p);
- value[item[0]] = item[1];
- }
- }
- } else if (param.indexOf(p) !== -1) {
- var item = param.split(p);
- value[item[0]] = item[1];
- } else {
- return param;
- }
- return value;
- },
- /**根据格式组装公共参数
- * @param {Object} value
- */
- formatMpQrCodeData(value) {
- let values = value.split(",");
- let result = {};
- if (values.length === 2) {
- let v1 = values[0].split(":");
- if (v1[0] === "pid") {
- result.spread = v1[1];
- } else {
- result.id = v1[1];
- }
- let v2 = values[1].split(":");
- if (v2[0] === "pid") {
- result.spread = v2[1];
- } else {
- result.id = v2[1];
- }
- } else {
- result = values[0].split(":")[1];
- }
- return result;
- },
- // #endif
- /*
- * 合并数组
- */
- SplitArray(list, sp) {
- if (!Array.isArray(list)) return [];
- return [...sp, ...list];
- },
- trim(str) {
- return String.prototype.trim.call(str);
- },
- $h: {
- //除法函数,用来得到精确的除法结果
- //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
- //调用:$h.Div(arg1,arg2)
- //返回值:arg1除以arg2的精确结果
- Div: function (arg1, arg2) {
- arg1 = parseFloat(arg1);
- arg2 = parseFloat(arg2);
- var t1 = 0,
- t2 = 0,
- r1,
- r2;
- try {
- t1 = arg1.toString().split(".")[1].length;
- } catch (e) {}
- try {
- t2 = arg2.toString().split(".")[1].length;
- } catch (e) {}
- r1 = Number(arg1.toString().replace(".", ""));
- r2 = Number(arg2.toString().replace(".", ""));
- return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
- },
- //加法函数,用来得到精确的加法结果
- //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
- //调用:$h.Add(arg1,arg2)
- //返回值:arg1加上arg2的精确结果
- Add: function (arg1, arg2) {
- arg2 = parseFloat(arg2);
- var r1, r2, m;
- try {
- r1 = arg1.toString().split(".")[1].length;
- } catch (e) {
- r1 = 0;
- }
- try {
- r2 = arg2.toString().split(".")[1].length;
- } catch (e) {
- r2 = 0;
- }
- m = Math.pow(100, Math.max(r1, r2));
- return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
- },
- //减法函数,用来得到精确的减法结果
- //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
- //调用:$h.Sub(arg1,arg2)
- //返回值:arg1减去arg2的精确结果
- Sub: function (arg1, arg2) {
- arg1 = parseFloat(arg1);
- arg2 = parseFloat(arg2);
- var r1, r2, m, n;
- try {
- r1 = arg1.toString().split(".")[1].length;
- } catch (e) {
- r1 = 0;
- }
- try {
- r2 = arg2.toString().split(".")[1].length;
- } catch (e) {
- r2 = 0;
- }
- m = Math.pow(10, Math.max(r1, r2));
- //动态控制精度长度
- n = r1 >= r2 ? r1 : r2;
- return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
- },
- //乘法函数,用来得到精确的乘法结果
- //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
- //调用:$h.Mul(arg1,arg2)
- //返回值:arg1乘以arg2的精确结果
- Mul: function (arg1, arg2) {
- arg1 = parseFloat(arg1);
- arg2 = parseFloat(arg2);
- var m = 0,
- s1 = arg1.toString(),
- s2 = arg2.toString();
- try {
- m += s1.split(".")[1].length;
- } catch (e) {}
- try {
- m += s2.split(".")[1].length;
- } catch (e) {}
- return (
- (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
- Math.pow(10, m)
- );
- },
- },
- // 获取地理位置;
- $L: {
- async getLocation() {
- // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
- let status = await this.getSetting();
- if (status === 2) {
- this.openSetting();
- return;
- }
- // #endif
- this.doGetLocation();
- },
- doGetLocation() {
- uni.getLocation({
- success: (res) => {
- uni.removeStorageSync("CACHE_LONGITUDE");
- uni.removeStorageSync("CACHE_LATITUDE");
- uni.setStorageSync("CACHE_LONGITUDE", res.longitude);
- uni.setStorageSync("CACHE_LATITUDE", res.latitude);
- },
- fail: (err) => {
- // #ifdef MP-BAIDU
- if (err.errCode === 202 || err.errCode === 10003) {
- // 202模拟器 10003真机 user deny
- this.openSetting();
- }
- // #endif
- // #ifndef MP-BAIDU
- if (err.errMsg.indexOf("auth deny") >= 0) {
- Toast({
- title: "访问位置被拒绝",
- });
- } else {
- Toast({
- title: err.errMsg,
- });
- }
- // #endif
- },
- });
- },
- getSetting: function () {
- return new Promise((resolve, reject) => {
- uni.getSetting({
- success: (res) => {
- if (res.authSetting["scope.userLocation"] === undefined) {
- resolve(0);
- return;
- }
- if (res.authSetting["scope.userLocation"]) {
- resolve(1);
- } else {
- resolve(2);
- }
- },
- });
- });
- },
- openSetting: function () {
- uni.openSetting({
- success: (res) => {
- if (res.authSetting && res.authSetting["scope.userLocation"]) {
- this.doGetLocation();
- }
- },
- fail: (err) => {},
- });
- },
- async checkPermission() {
- let status = permision.isIOS
- ? await permision.requestIOS("location")
- : await permision.requestAndroid(
- "android.permission.ACCESS_FINE_LOCATION"
- );
- if (status === null || status === 1) {
- status = 1;
- } else if (status === 2) {
- uni.showModal({
- content: "系统定位已关闭",
- confirmText: "确定",
- showCancel: false,
- success: function (res) {},
- });
- } else if (status.code) {
- uni.showModal({
- content: status.message,
- });
- } else {
- uni.showModal({
- content: "需要定位权限",
- confirmText: "设置",
- success: function (res) {
- if (res.confirm) {
- permision.gotoAppSetting();
- }
- },
- });
- }
- return status;
- },
- },
- toStringValue: function (obj) {
- if (obj instanceof Array) {
- var arr = [];
- for (var i = 0; i < obj.length; i++) {
- arr[i] = toStringValue(obj[i]);
- }
- return arr;
- } else if (typeof obj == "object") {
- for (var p in obj) {
- obj[p] = toStringValue(obj[p]);
- }
- } else if (typeof obj == "number") {
- obj = obj + "";
- }
- return obj;
- },
- /*
- * 替换域名
- */
- setDomain: function (url) {
- url = url ? url.toString() : "";
- if (url.indexOf("https://") > -1) return url;
- else return url.replace("http://", "https://");
- },
- /**
- * 姓名除了姓显示其他
- */
- formatName: function (str) {
- return str.substr(0, 1) + new Array(str.length).join("*");
- },
- /**
- * rpx转px
- */
- rpxToPx(rpx) {
- const screenWidth = uni.getSystemInfoSync().screenWidth;
- return (screenWidth * Number.parseInt(rpx)) / 750;
- },
- /**
- * px 转换 rpx
- */
- pxToRpx: function (px) {
- const screenWidth = uni.getSystemInfoSync().screenWidth;
- return (750 * Number.parseInt(px)) / screenWidth;
- },
- };
- /**
- * 格式化日期
- * @prama t 时间戳
- * @return str MM-dd HH:mm
- */
- export function formatDate(t) {
- t = t || Date.now();
- let time = new Date(t);
- let str =
- time.getMonth() < 9 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1;
- str += "-";
- str += time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
- str += " ";
- str += time.getHours();
- str += ":";
- str += time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
- return str;
- }
- export function previewImage(urls = []) {
- if (!urls.length) return;
- uni.previewImage({
- urls,
- });
- }
- export function telEncrypt(tel = "") {
- let str = tel + "";
- let enStr = str.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
- return enStr;
- }
- /*
- * 随机数生成
- */
- export function generateCustomId(prefix) {
- // 验证前缀长度
- if (prefix.length <= 0) {
- throw new Error("必须附带前缀");
- }
- if (prefix.length > 6) {
- throw new Error("前缀太长,仅支持6位");
- }
- // 获取当前时间并格式化为年月日后两位+时分秒+毫秒
- const now = new Date();
- const year = String(now.getFullYear()).slice(-2);
- const month = String(now.getMonth() + 1).padStart(2, "0");
- const day = String(now.getDate()).padStart(2, "0");
- const hours = String(now.getHours()).padStart(2, "0");
- const minutes = String(now.getMinutes()).padStart(2, "0");
- const seconds = String(now.getSeconds()).padStart(2, "0");
- const milliseconds = String(now.getMilliseconds()).padStart(3, "0");
- // 组合时间部分(精确到毫秒)
- const timePart =
- year + month + day + hours + minutes + seconds + milliseconds;
- // 生成8位随机字符
- const chars =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
- let randomPart = "";
- for (let i = 0; i < 8; i++) {
- const randomIndex = Math.floor(Math.random() * chars.length);
- randomPart += chars[randomIndex];
- }
- // 组合生成ID
- return `${prefix}-${timePart}-${randomPart}`;
- }
- /**
- * 判断图片地址是否包含 HTTPS 协议
- * @param {string} imageUrl - 图片地址
- * @returns {string} 包含HTTPS则返回原图片地址,否则返回拼接oss对象存储地址
- */
- export function isHttpsImage(imageUrl) {
- if (typeof imageUrl !== "string" || !imageUrl) {
- return "/static/avator.png";
- }
- const trimmedUrl = imageUrl.trim();
- if (trimmedUrl.includes("https://")) {
- return imageUrl;
- } else {
- return BASE_OSS_URL + imageUrl;
- }
- }
- // 判断当前页面是否为 tabBar 页面
- export function isTabBarPage() {
- // 获取当前页面栈
- const pages = getCurrentPages();
- // 获取当前页面路径(不包含参数部分)
- if (!pages[pages.length - 1]) {
- return false;
- }
- const currentPagePath = pages[pages.length - 1].route;
- // 获取 app.json 中的 tabBar 配置
- const tabBarPages =
- getApp().globalData.tabBarPages ||
- (() => {
- // 从 app.json 中读取 tabBar 配置
- // const appJson = import('@/pages.json');
- // console.log('pageJson', pageJson)
- const tabBarList = pageJson.tabBar ? pageJson.tabBar.list : [];
- // 提取所有 tabBar 页面的路径
- const pages = tabBarList.map((item) => item.pagePath);
- // 缓存到全局数据中,避免重复解析
- getApp().globalData.tabBarPages = pages;
- return pages;
- })();
- // 判断当前页面是否在 tabBar 配置中
- return tabBarPages.includes(currentPagePath);
- }
- // 获取邀请码
- export async function getSceneInfo(e, index) {
- if (e.scene) {
- const decodedScene = decodeURIComponent(e.scene);
- const params = {};
- if (decodedScene) {
- decodedScene.split("&").forEach((item) => {
- const [key, value] = item.split("=");
- if (key && value) {
- params[key] = value;
- }
- });
- }
- if (params.merchantId) appStore.UPDATE_MERCHANT_ID(params.merchantId);
- if (index == "index" && appStore.userInfo) {
- let obj = {
- merchantId: params.merchantId,
- userId: appStore.userInfo.userId,
- };
- await footprintScan(obj);
- }
- console.log("获取邀请码-params", params);
- return params;
- }
- return {};
- }
- // 获取用户所有的加盟角色列表
- export async function getJoinTeamUserRoles() {
- let join_roles = [];
- const { data: list } = await getJoinRolesAPI();
- list.forEach((item) => {
- join_roles.push(item.roleName);
- });
- return join_roles;
- }
- // 为用户添加加盟角色(推荐官)
- // addRecommenderRole();
- //
- export async function addRecommenderRole(remark) {
- try {
- const appStore = useAppStore();
- const uid = appStore.uid;
- console.log("appStore", appStore.uid);
- if (!uid) {
- console.error("添加推荐官角色失败:用户ID不存在");
- uni.showToast({ title: "用户信息异常", icon: "none" });
- return;
- }
- const requestParams = {
- remark: remark || "自动成为推荐官",
- roleName: "推荐官",
- roleType: 2, // 2-推荐官
- uid,
- };
- const response = await addJoinTeamUserRole(requestParams);
- console.log("response", response);
- uni.showModal({
- title: "恭喜",
- content: "您已成为推荐官,推荐用户注册、消费立得好礼,是否立即查看?",
- confirmText: "立即查看",
- cancelText: "稍后",
- success: (res) => {
- if (res.confirm) {
- uni.navigateTo({
- url: "/pages/join_us/recommed",
- });
- }
- },
- });
- } catch (error) {
- console.error("添加推荐官角色请求异常:", error);
- uni.showToast({
- title: error || "网络异常,请稍后重试",
- icon: "none",
- duration: 2000,
- });
- }
- }
- /**
- * 精确计算工具(支持直接调用和链式调用)
- * 使用方法:
- * import { Calc } from '@/utils/util'
- *
- * // 直接计算(两个参数)
- * const sum = Calc.add(0.1, 0.2).valueOf(); // 0.3
- *
- * // 链式调用(后续方法传入一个参数,基于前一步结果计算)
- * const result = Calc.add(1, 2).sub(1).mul(3).div(2).fixed(1).valueOf(); // 3.0
- *
- * // 截断示例:40.66 截断2位 → 40.66;40.666 截断2位 → 40.66
- * const truncResult = Calc.truncate(40.666, 2).valueOf(); // 40.66
- *
- * // 注意点
- * 需要在最后调用一次.valueOf()获取最终值,否则会返回一个Calc对象。
- */
- export const Calc = {
- // 存储当前计算值
- currentValue: null,
- /**
- * 重置当前值(内部使用,确保每次计算独立性)
- */
- _reset() {
- this.currentValue = null;
- return this;
- },
- /**
- * 内部工具:校验并转换为有效数字(核心修复点)
- * @param {any} num - 待校验的数值
- * @returns {Number} 有效数字(无效则返回 0)
- */
- _validateNum(num) {
- // 过滤 Infinity/-Infinity/NaN/undefined/null/空字符串
- if (
- num === undefined ||
- num === null ||
- num === "" ||
- !isFinite(num) ||
- isNaN(Number(num))
- ) {
- return 0;
- }
- // 转换为数字类型(处理字符串数字,如 "123.45")
- return Number(num);
- },
- /**
- * 内部工具:解析数值字符串,返回整数部分、小数部分、小数位数、符号
- * @param {Number|String} num - 待解析的数值
- * @returns {Object} 解析结果
- */
- _parseNumStr(num) {
- // 第一步:先校验并转换为有效数字(修复 NaN 问题)
- const validNum = this._validateNum(num);
- const str = String(validNum).trim().replace(/^\+/, ""); // 移除正号
- const isNegative = str.startsWith("-");
- const absStr = isNegative ? str.slice(1) : str;
- const [integerPart = "0", decimalPart = "0"] = absStr.split(".");
- // 处理纯小数(如.123)或纯整数(如123.)的情况
- const cleanInteger = integerPart || "0";
- const cleanDecimal = decimalPart || "0";
- return {
- isNegative,
- integerPart: cleanInteger,
- decimalPart: cleanDecimal,
- decimalLength: cleanDecimal.length,
- };
- },
- /**
- * 内部工具:对齐两个数的小数位数,转换为大整数
- * @param {Number|String} num1 - 数值1
- * @param {Number|String} num2 - 数值2
- * @returns {Object} 对齐后的整数和缩放比例
- */
- _alignDecimals(num1, num2) {
- const n1 = this._parseNumStr(num1);
- const n2 = this._parseNumStr(num2);
- const maxDecimalLen = Math.max(n1.decimalLength, n2.decimalLength);
- // 补零对齐小数位数
- const n1DecimalPadded = n1.decimalPart.padEnd(maxDecimalLen, "0");
- const n2DecimalPadded = n2.decimalPart.padEnd(maxDecimalLen, "0");
- // 转换为大整数(避免普通整数溢出)
- const n1Int =
- BigInt(n1.integerPart + n1DecimalPadded) * (n1.isNegative ? -1n : 1n);
- const n2Int =
- BigInt(n2.integerPart + n2DecimalPadded) * (n2.isNegative ? -1n : 1n);
- return {
- int1: n1Int,
- int2: n2Int,
- scale: BigInt(10 ** maxDecimalLen), // 缩放比例(10^最大小数位数)
- };
- },
- /**
- * 加法运算(修复精度问题 + 入参校验)
- */
- add(a, b) {
- // 链式调用/直接调用参数处理
- const [arg1, arg2] =
- this.currentValue === null ? [a, b] : [this.currentValue, a];
- const { int1, int2, scale } = this._alignDecimals(arg1, arg2);
- const sumInt = int1 + int2;
- // 转换回小数(BigInt转Number,确保精度)
- this.currentValue = Number(sumInt) / Number(scale);
- return this;
- },
- /**
- * 减法运算(修复精度问题 + 入参校验)
- */
- sub(a, b) {
- const [arg1, arg2] =
- this.currentValue === null ? [a, b] : [this.currentValue, a];
- const { int1, int2, scale } = this._alignDecimals(arg1, arg2);
- const subInt = int1 - int2;
- this.currentValue = Number(subInt) / Number(scale);
- return this;
- },
- /**
- * 乘法运算(修复精度问题 + 入参校验)
- */
- mul(a, b) {
- const [arg1, arg2] =
- this.currentValue === null ? [a, b] : [this.currentValue, a];
- const n1 = this._parseNumStr(arg1);
- const n2 = this._parseNumStr(arg2);
- // 转换为整数(移除小数点)
- const n1Int =
- BigInt(n1.integerPart + n1.decimalPart) * (n1.isNegative ? -1n : 1n);
- const n2Int =
- BigInt(n2.integerPart + n2.decimalPart) * (n2.isNegative ? -1n : 1n);
- // 总小数位数
- const totalDecimalLen = n1.decimalLength + n2.decimalLength;
- const scale = BigInt(10 ** totalDecimalLen);
- // 相乘后除以缩放比例
- const mulInt = n1Int * n2Int;
- this.currentValue = Number(mulInt) / Number(scale);
- return this;
- },
- /**
- * 除法运算(修复精度问题 + 入参校验)
- */
- div(a, b) {
- const [arg1, arg2] =
- this.currentValue === null ? [a, b] : [this.currentValue, a];
- // 先校验除数是否为有效数字(避免 0/NaN 混淆)
- const validArg2 = this._validateNum(arg2);
- if (validArg2 === 0) {
- throw new Error("除数不能为0");
- }
- const n1 = this._parseNumStr(arg1);
- const n2 = this._parseNumStr(arg2);
- // 转换为整数(移除小数点)
- const n1Int =
- BigInt(n1.integerPart + n1.decimalPart) * (n1.isNegative ? -1n : 1n);
- const n2Int =
- BigInt(n2.integerPart + n2.decimalPart) * (n2.isNegative ? -1n : 1n);
- // 计算缩放比例:10^(n2小数位数 - n1小数位数)
- const decimalDiff = n2.decimalLength - n1.decimalLength;
- const scale = BigInt(10 ** Math.abs(decimalDiff));
- let divResult;
- if (decimalDiff >= 0) {
- divResult = (n1Int * scale) / n2Int;
- } else {
- divResult = n1Int / (n2Int * scale);
- }
- // 处理除法精度(保留15位小数,避免无限循环)
- this.currentValue =
- Number(divResult) / Number(BigInt(10 ** Math.max(0, -decimalDiff)));
- return this;
- },
- /**
- * 四舍五入保留指定小数位
- */
- fixed(num, n) {
- let targetNum, decimalPlaces;
- if (this.currentValue === null) {
- targetNum = this._validateNum(num); // 修复:校验入参
- decimalPlaces = arguments.length >= 2 ? n : 2;
- } else {
- targetNum = this.currentValue;
- decimalPlaces = num !== undefined ? num : 2;
- }
- decimalPlaces = Math.max(0, Math.floor(parseInt(decimalPlaces, 10) || 0));
- const pow10 = Math.pow(10, decimalPlaces);
- this.currentValue = Math.round(targetNum * pow10) / pow10;
- return this;
- },
- /**
- * 截断保留指定小数位
- */
- truncate(num, n) {
- let targetNum, decimalPlaces;
- if (this.currentValue === null) {
- targetNum = this._validateNum(num); // 修复:校验入参
- decimalPlaces = arguments.length >= 2 ? n : 2;
- } else {
- targetNum = this.currentValue;
- decimalPlaces = num !== undefined ? num : 2;
- }
- decimalPlaces = Math.max(0, Math.floor(parseInt(decimalPlaces, 10) || 0));
- const numStr = targetNum.toString();
- const dotIndex = numStr.indexOf(".");
- let integerPart, decimalPart;
- if (dotIndex === -1) {
- integerPart = numStr;
- decimalPart = "";
- } else {
- integerPart = numStr.substring(0, dotIndex);
- decimalPart = numStr.substring(dotIndex + 1);
- }
- let truncatedDecimal;
- if (decimalPlaces === 0) {
- truncatedDecimal = "";
- } else {
- truncatedDecimal = decimalPart.substring(0, decimalPlaces);
- if (truncatedDecimal.length < decimalPlaces) {
- truncatedDecimal = truncatedDecimal.padEnd(decimalPlaces, "0");
- }
- }
- let resultStr;
- if (decimalPlaces === 0) {
- resultStr = integerPart;
- } else {
- resultStr = `${integerPart}.${truncatedDecimal}`;
- }
- this.currentValue = parseFloat(resultStr);
- return this;
- },
- /**
- * 保留两位小数,若第三位小数大于0则进一
- */
- fixedUpTwo(num) {
- // 处理目标数值:链式调用用currentValue,直接调用用传入的num
- let targetNum =
- this.currentValue === null ? this._validateNum(num) : this.currentValue;
- // 处理NaN/非数值情况(已被_validateNum兜底,此处冗余校验)
- if (isNaN(targetNum)) {
- this.currentValue = 0.0;
- return this;
- }
- const multiplied = targetNum * 1000;
- const integerPart = Math.floor(multiplied);
- const thirdDecimal = integerPart % 10;
- let result;
- if (thirdDecimal > 0) {
- result = (Math.floor(targetNum * 100) + 1) / 100;
- } else {
- result = Math.floor(targetNum * 100) / 100;
- }
- this.currentValue = parseFloat(result.toFixed(2));
- return this;
- },
- // 获取最终值
- valueOf() {
- const result = this.currentValue;
- this._reset();
- return result;
- },
- };
|