jiuyiUniapp/jiuyi2/unpackage/dist/dev/mp-weixin/common/js/util.js

1337 lines
40 KiB
JavaScript
Raw Normal View History

2024-12-18 15:46:27 +08:00
"use strict";
const common_vendor = require("../vendor.js");
const store_index = require("../../store/index.js");
const common_js_config = require("./config.js");
const api_index = require("../../api/index.js");
const utils_msgtype = require("../../utils/msgtype.js");
const TUIKit_debug_GenerateTestUserSig = require("../../TUIKit/debug/GenerateTestUserSig.js");
const util = {
// 配置参数
config: common_js_config.config,
// 正则
reg: {
// 手机号
tel: /^1[3-9]\d{9}$/,
// 身份证
idCard: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
},
/**
* 弹窗
* @param {Object|String} obj String类型只是弹出文字 object如下
* @param {String} obj.title 弹窗的标题
* @param {String} obj.content 弹窗的内容
* @param {String} obj.confirmText 确定的文本
* @param {String} obj.showCancel 是否显示取消
* @param {String} obj.cancelText 取消的文本
* @param {Function} params.success 请求成功回调 可通过promise.then捕获
* @param {Function} params.fail 请求失败回调 可通过promise.catch捕获
* @param {Function} params.complete 请求结束回调 无论是否成功失败都会执行
* @return {Object} string返回null object返回返回promis对象 执行成功返回resolve 执行失败返回reject
*/
alert(obj) {
if (obj == null || obj == void 0)
return;
if (typeof obj == "string" || typeof obj == "number") {
common_vendor.index.showToast({
"title": "" + obj,
"icon": "none",
duration: 3e3
});
return null;
}
obj.title = obj.title ? obj.title : "";
obj.content = obj.content ? obj.content : "";
obj.confirmText = obj.confirmText ? obj.confirmText : "确定";
obj.showCancel = obj.showCancel === false ? false : true;
obj.cancelText = obj.cancelText ? obj.cancelText : "取消";
return new Promise((resolve, reject) => {
common_vendor.index.showModal({
title: obj.title,
content: obj.content,
confirmText: obj.confirmText,
showCancel: obj.showCancel,
cancelText: obj.cancelText,
success: (res) => {
obj.success ? obj.success(res) : () => {
};
resolve(res);
},
fail: (err) => {
obj.fail ? obj.fail(err) : () => {
};
reject(err);
},
complete: (res) => {
}
});
});
},
/**
* 上传文件
* @param {Object} obj
* @param {String} obj.mode img图片 video视频
*/
upload(obj) {
return new Promise((resolve, reject) => {
let token = common_vendor.index.getStorageSync("token") || "";
obj.url = obj.url ? obj.url : api_index.api[{
img: "uploadImg",
video: "uploadVideo"
}[obj.mode]];
console.log("obj.url", obj.url);
obj.file = obj.file ? obj.file : "";
obj.data = obj.data ? obj.data : {};
obj.header = {
// 'Content-Type': 'multipart/form-data; ',
// 'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
...obj.header
};
if (token)
obj.header["Authorization"] = `Bearer ${token}`;
common_vendor.index.showLoading({
title: "正在上传"
});
common_vendor.index.uploadFile({
url: util.config.host + obj.url,
filePath: obj.file,
header: obj.header,
formData: obj.data,
dataType: "json",
name: "file",
success: (res) => {
common_vendor.index.hideLoading();
obj.success ? obj.success(JSON.parse(res.data)) : "";
resolve(JSON.parse(res.data));
},
fail: (res) => {
common_vendor.index.hideLoading();
obj.fail ? obj.fail(res.data) : "";
reject(res);
}
});
});
},
/**
* 发送网络请求
* @param {Object} params 传参
* @param {String} params.url 请求地址 一般用于后台请求接口
* @param {Array} params.query 请求地址拼接参数 用于后台请求地址拼接补全
* @param {String} params.fullurl 全请求地址 一般用于第三方请求地址
* @param {Boolean} params.load 是否显示加载动画 默认不显示
* @param {Object} params.data 请求入参 没有则不传
* @param {Object} params.header 请求头 默认不传
* @param {String} params.method 请求方式 默认值POST
* @param {Function} params.success 请求成功回调 可通过promise.then捕获
* @param {Function} params.fail 请求失败回调 可通过promise.catch捕获
* @param {Function} params.complete 请求结束回调 无论是否成功失败都会执行
* @return {Object} 返回promis对象 执行成功返回resolve 执行失败返回reject
*/
request(params) {
let token = common_vendor.index.getStorageSync("token") || "";
return new Promise((resolve, reject) => {
let url = util.config.host + (params.url ? params.url : "/api/index/index");
if (params.path && params.path instanceof Array)
params.path.forEach((item) => {
url += `/${item}`;
});
if (common_js_config.config.env == "config") {
url = util.setUrl(url, params.query);
}
if (common_js_config.config.env == "test") {
if (params.query) {
url = util.setUrl(url, {
...params.query,
userId: 16
});
}
params.data = {
...params.data,
userId: 16
};
}
if (params.load) {
common_vendor.index.showLoading({
title: "加载中",
mask: true
});
}
params.header = {
"ngrok-skip-browser-warning": true,
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
// token: uni.getStorageSync('token'),
"Access-Control-Allow-Origin": "*",
...params.header
};
if (token)
params.header["Authorization"] = `Bearer ${token}`;
common_vendor.index.request({
// 请求地址
url,
// 请求方式 get/post
method: params.method ? params.method : "POST",
// 是否开启SSL验证
sslVerify: false,
// 请求参数
data: params.data,
// header请求头
header: params.header,
// 数据类型
dataType: "json",
// 请求成功返回
success: (res) => {
if (params.load) {
common_vendor.index.hideLoading();
}
if (res.data.code == 401) {
util.logout(() => {
util.alert("请先登录");
reject(res.data);
});
}
params.success ? params.success(res.data) : "";
resolve(res.data);
},
// 请求失败返回
fail: (res) => {
if (params.load) {
common_vendor.index.hideLoading();
}
params.fail ? params.fail(res) : "";
reject(res);
},
complete(res) {
params.complete ? params.complete(res) : "";
}
});
});
},
// 替换图片的宽度为最大宽度100% (移动端解析html富文本专用)
imgReplace(value, th) {
if (!th) {
value = value.replace(/<img src="/ig, '<img src="' + util.config.host);
}
return value.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, "<p").replace(/<p>/ig, '<p style="font-size: 15px; line-height: 25px;">').replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, "<img$1").replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, "<img$1").replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, "<img$1").replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, "<img$1").replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img style="width: 100%;" $1');
},
/**
* 路由跳转方法
* @param {string} url 跳转的目标页面路径
* @param {Object} params 要传递的参数对象
* @param {string} method 跳转方法默认为 navigateTo
*/
routeWithParams(url, params = {}, method = "navigateTo") {
const paramStr = Object.keys(params).length > 0 ? "?" + new URLSearchParams(params) : "";
const fullUrl = `${url}${paramStr}`;
switch (method) {
case "navigateTo":
common_vendor.index.navigateTo({
url: fullUrl
});
break;
case "redirectTo":
common_vendor.index.redirectTo({
url: fullUrl
});
break;
case "reLaunch":
common_vendor.index.reLaunch({
url: fullUrl
});
break;
case "switchTab":
common_vendor.index.switchTab({
url: fullUrl
});
break;
default:
throw new Error(`Unsupported method: ${method}`);
}
},
/**
* get参数拼接
* @param {Object} data 需要转化的对象
*/
set_param(data) {
let url = "";
if (!data)
data = [];
for (let [key, value] of Object.entries(data)) {
url += `${key}=${value}&`;
}
url = url.substring(url.length - 1) == "&" ? url.substring(0, url.length - 1) : url;
return url ? url : url.substring(1);
},
/**
* get参数拼接url
* @param {String} url 需要处理的url
* @param {Object} data 需要转化的Object对象
*/
setUrl(url, data) {
let result = url += (url.indexOf("?") < 0 ? "?" : "&") + util.set_param(data);
return result;
},
/**
* query字符串转对象
* @param {Object} str query字符串
*/
query_to_param(str) {
let obj = {};
decodeURIComponent(str).split("&").forEach((item) => {
let [key, val] = item.split("=");
obj[key] = val;
});
return obj;
},
/**
* 倒计时
* @param {String} endtime 结束时间
*/
countDownd(endtime) {
if (!endtime) {
return;
}
endtime = Number(endtime);
let day = util.timeFormin(parseInt(time / (60 * 60 * 24)));
let hou = util.timeFormin(parseInt(time % (60 * 60 * 24) / 3600));
let min = util.timeFormin(parseInt(time % (60 * 60 * 24) % 3600 / 60));
let sec = util.timeFormin(parseInt(time % (60 * 60 * 24) % 3600 % 60));
let str = "";
if (day) {
str += day + "天";
}
if (hou || hou == 0) {
if (hou > 9) {
str += hou + ":";
} else {
str += "0" + hou + ":";
}
} else {
str += "00:";
}
if (min || min == 0) {
if (min > 9) {
str += min + ":";
} else {
str += "0" + min + ":";
}
} else {
str += "00:";
}
if (sec) {
if (sec > 9) {
str += sec;
} else {
str += "0" + sec;
}
} else {
str += "00";
}
return str;
},
// 格式化时间
timeFormin(param) {
return param < 0 ? 0 : param;
},
/**
* 对二补齐
* @param {String} str 数字或数字字符串
*/
toTwo(str) {
let num = String(Number(str));
if (num.length < 2) {
num = "0" + num;
}
return num;
},
/**
* 时间戳处理成时间
* @param {Object} str
* 时间格式 单个字母不补0
* yyyy
* MM
* dd
* WW
* HH 小时 24小时制
* hh 小时 12小时制
* mm 分钟
* ss
* a am/pm
* 比如 'yyyy-MM-dd HH:mm:ss 周w a' 返回2023-02-06 11:19:19 周一 pm
* @param {Number} timestamp 需要处理时间戳
*/
formatTime(str, timestamp) {
const nowDate = /* @__PURE__ */ new Date();
let weekList = ["日", "一", "二", "三", "四", "五", "六"];
if (!str || typeof str != "string") {
str = "yyyy-MM-dd HH:mm:ss";
}
if (!timestamp) {
timestamp = nowDate.valueOf();
} else if (String(timestamp).length <= 10) {
timestamp = timestamp * 1e3;
}
const date = new Date(timestamp);
let year = date.getFullYear(), moth = date.getMonth() + 1, day = date.getDate(), week = date.getDay(), hour = date.getHours(), minute = date.getMinutes(), second = date.getSeconds();
str = str.replace("yyyy", year);
str = str.replace("MM", this.toTwo(moth));
str = str.replace("M", moth);
str = str.replace("dd", this.toTwo(day));
str = str.replace("d", day);
str = str.replace("w", weekList[week]);
if (str.match("h")) {
hour = hour > 12 ? hour - 12 : hour;
str = str.replace("hh", this.toTwo(hour));
str = str.replace("h", hour);
} else if (str.match("H")) {
str = str.replace("HH", this.toTwo(hour));
str = str.replace("H", hour);
}
str = str.replace("mm", this.toTwo(minute));
str = str.replace("m", minute);
str = str.replace("ss", this.toTwo(second));
str = str.replace("s", second);
let a = hour > 12 ? "am" : "pm";
str = str.replace("a", a);
return str;
},
/**
* 时间计算
* @param {String} format 格式化 规则
* format '+1 month' 往后一个月
* @param {Number} value 需要处理的时间戳 单位秒
*/
strtotime(format, value) {
if (value && format.indexOf(" ") > -1) {
let unit = format.split(" ");
let pre = unit[0];
let next = unit[1];
if (!value)
value = nowDate2.valueOf();
else if (String(value).length <= 10)
value = value * 1e3;
let nowDate2 = new Date(value);
switch (next) {
case "year":
nowDate2.setYear(nowDate2.getFullYear() + parseInt(pre));
break;
case "month":
nowDate2.setMonth(nowDate2.getMonth() + parseInt(pre));
break;
case "day":
nowDate2.setDate(nowDate2.getDate() + parseInt(pre));
break;
case "week":
nowDate2.setDate(nowDate2.getDate() + parseInt(pre) * 7);
break;
case "hour":
nowDate2.setHours(nowDate2.getHours() + parseInt(pre));
break;
case "minute":
nowDate2.setMinutes(nowDate2.getMinutes() + parseInt(pre));
break;
}
return nowDate2.getTime();
} else {
var nowDate = new Date(value);
return nowDate.getTime();
}
},
/**
* 上传图片
* @param {Object} obj 对象类型
* @param {Array} obj.value 操作的对象
* @param {Boolean} obj.unlimited 不限制
* @param {Number} obj.count 图片计数
* @param {Number} obj.type 1单张 2多张
* @param {Array} obj.sourceType ['album', 'camera']
* @param {Function} obj.success 执行成功返回的方法return修改的对象
*/
upload_image(obj) {
const count = obj.count ? obj.count : 8;
if (!obj.type)
obj.type = 2;
if (obj.value != "" && obj.value == void 0 && obj.value == null)
obj.value = obj.type == 1 ? "" : [];
if (obj.value.length >= count && obj.type == 2) {
util.alert("上传图片已达上限");
return;
}
let sourceType = ["album", "camera"];
common_vendor.index.chooseImage({
// 限制图片
count: obj.type == 1 ? 1 : count - obj.value.length,
sourceType: obj.sourceType || sourceType,
success: (rs) => {
rs.tempFiles.forEach((item) => {
let size = 1024 * 1024 * util.config.img_size;
if (item.size > size && !obj.unlimited) {
util.alert(`大小超过${util.config.img_size}m`);
return;
}
util.upload({
file: item.path,
mode: "img",
success(res) {
if (res.code === 200) {
if (obj.type == 2) {
obj.value.push(util.format_url(res.msg, "img"));
} else if (obj.type == 1) {
obj.value = util.format_url(res.msg, "img");
}
console.log("obj", obj, obj.value);
obj.success && obj.success({
result: res.msg,
value: obj.value
});
return;
}
util.alert(rs.msg);
}
});
});
},
fail(rs) {
if (rs.errMsg == "chooseImage:fail cancel")
;
}
});
},
/**
* 上传视频
* @param {Object} obj 对象类型
* @param {Array} obj.value 操作的对象
* @param {Object} obj.unlimited 不限制
* @param {Object} obj.count 计数
* @param {Object} obj.success 执行成功返回的方法return修改的对象
*/
upload_video(obj) {
obj.count ? obj.count : 1;
common_vendor.index.chooseVideo({
compressed: false,
success(rs) {
util.upload({
file: rs.tempFilePath,
mode: "video",
success(res) {
if (res.code == 200) {
const fullUrl = util.format_url(res.msg, "video");
obj.success && obj.success({
result: res.msg,
value: fullUrl
});
return;
} else {
util.alert(res.msg);
}
}
});
},
fail(rs) {
if (rs.errMsg == "chooseImage:fail cancel")
;
}
});
},
/**
* 上传文件
* @param {Object} obj 对象类型
* @param {Array} obj.value 操作的对象
* @param {Object} obj.count 计数
* @param {Object} obj.success 执行成功返回的方法return修改的对象
*/
upload_files(obj) {
const value = obj.value;
const file_suffix = util.config.file_suffix;
const count = obj.count ? obj.count : 1;
if (value.length >= count) {
util.alert("上传数量已达上限");
return;
}
console.log("upload_files", obj);
function result_fn(path) {
let str = path.split(".").pop().toLowerCase();
let reult = file_suffix.find((node) => node.id == str);
if (!reult) {
util.alert(`不能上传${str}格式文件`);
return;
}
util.upload({
file: path,
success(res) {
if (res.code == 200) {
value.push(res.data);
obj.success && obj.success({
...res.data,
value
});
} else {
util.alert(res.msg);
}
}
});
}
common_vendor.wx$1.chooseMessageFile({
count: 1,
type: "file",
// 文件过滤
extension: file_suffix.map((node) => node.id),
success: (rs) => {
rs.tempFiles.forEach((e, i) => {
result_fn(e.path);
});
}
});
return;
},
/**
* 上传音频
* @param {Object} obj 对象类型
* @param {Array} obj.value 操作的对象
* @param {Object} obj.count 计数
* @param {Object} obj.success 执行成功返回的方法return修改的对象
*/
upload_audio(obj) {
const value = obj.value;
const audio_suffix = util.config.audio_suffix;
const count = obj.count ? obj.count : 1;
if (value.length >= count) {
util.alert("上传数量已达上限");
return;
}
function result_fn(path) {
let str = path.split(".").pop().toLowerCase();
let reult = audio_suffix.find((node) => node.id == str);
if (!reult) {
util.alert(`不能上传${str}格式文件`);
return;
}
util.upload({
file: path,
success(res) {
if (res.code == 200) {
value.push(res.data);
obj.success && obj.success({
...res.data,
value
});
} else {
util.alert(res.msg);
}
}
});
}
common_vendor.wx$1.chooseMessageFile({
count: 1,
type: "file",
// 文件过滤
extension: audio_suffix.map((node) => node.id),
success: (rs) => {
rs.tempFiles.forEach((e, i) => {
result_fn(e.path);
});
}
});
return;
},
/**
* 视频转封面 oss特有
* @param {Object} url 视频路径
*/
video_coverImage(url) {
let result = `${url}?x-oss-process=video/snapshot,t_1,m_fast`;
return result;
},
/**
* 预览图片
* @param {Array} urls 图片列表
* @param {Number} current 当前预览的下标
*/
view_imgs(urls, current) {
if (!urls || urls.length == 0) {
util.alert("暂无");
return;
}
common_vendor.index.previewImage({
urls,
current
});
},
/**
* 预览文件
* @param {String} url 文件路径
*/
view_file(url) {
let suffix = util.get_file_suffix(url).id;
if (!["doc", "xls", "ppt", "pdf", "docx", "xlsx", "pptx"].includes(suffix)) {
util.alert("操作需要在web端");
console.log("Unsupported suffix", suffix);
return;
}
common_vendor.index.downloadFile({
url,
success: (res) => {
common_vendor.index.openDocument({
filePath: res.tempFilePath,
fail: (rs) => {
console.log("rs", rs);
}
});
}
});
},
/**
* 通过路径获取文件后缀
* @param {Object} url 需要获取的文件路径
* @param {Object} type file文件 audio音频
* @return {Object} 返回后缀列表对象 util.config.file_suffix
*/
get_file_suffix(url, type) {
if (!type)
type = "file";
const file_suffix = util.config[{
"file": "file_suffix",
"audio": "audio_suffix"
}[type]];
let result = "";
if (url)
result = file_suffix.find((item) => item.id === url.split(".").pop().toLowerCase());
return result;
},
/**
* 通过路径获取音频后缀
* @param {Object} url 需要获取的文件路径
* @return {Object} 返回后缀列表对象 util.config.file_suffix
*/
get_audio_suffix(url) {
const audio_suffix = util.config.audio_suffix;
let result = "";
if (url)
result = audio_suffix.find((item) => item.id === url.split(".").pop().toLowerCase());
return result;
},
/**
* 调起支付
* @param {Object} obj 操作对象
* @param {String} obj.payType 支付方式 WeChat微信 AliPay支付宝 4钱包
* @param {String} obj.method 支付环境 app手机应用 mp小程序
* @param {String} obj.debug 调试模式
* @param {Boolean|Object} obj.cb 支付结果跳转 false为不跳转 跳转需携带object定义对象
* @param {String} obj.cb.styles 风格 style1蓝色 style2绿色 style3橙色
* @param {String} obj.cb.result 结果 success成功 fail失败
* @param {String} obj.cb.price 价格
* @param {String} obj.cb.url 跳转的详情路径
* @param {Function} obj.fn 请求接口函数
* @param {Function} obj.success 成功方法
* @param {Function} obj.fail 失败方法
* @param {Function} obj.complete 结束方法
*/
payment(obj) {
obj = obj ? obj : {};
obj.data = obj.data ? obj.data : {};
obj.method = "mp";
common_vendor.index.login({
success: (rs) => {
obj.data.code = rs.code;
util.payment_request(obj);
}
});
},
// 支付请求
payment_request(obj) {
obj.debug ? console.log("params", obj) : "";
if (!obj.fn) {
throw "no function";
}
function result_goto(result) {
const cb = obj.cb;
if (!cb)
return;
common_vendor.index.redirectTo({
url: util.set_url("/index/pay_result", {
orderNumber: cb.orderNumbers || "",
result,
styles: cb.styles || "",
price: cb.price || "",
url: cb.url || ""
})
});
}
obj.fn(obj.data).then((rs) => {
obj.debug ? console.log("request success result", rs) : "";
if (rs.code == 200) {
switch (obj.data.payType) {
case "1":
switch (obj.method) {
case "mp":
if (rs.data && rs.data.paySign) {
common_vendor.index.requestPayment({
provider: "wxpay",
timeStamp: rs.data.timeStamp,
package: rs.data.package,
nonceStr: rs.data.nonceStr,
paySign: rs.data.paySign,
signType: rs.data.signType,
success(result) {
obj.success ? obj.success(rs) : "";
result_goto("success");
},
fail(result) {
obj.fail ? obj.fail(result) : "";
result_goto("fail");
},
complete(result) {
obj.debug ? console.log(
"requestPayment complete",
result
) : "";
obj.complete ? obj.complete(result) : "";
}
});
} else {
obj.fail ? obj.fail("no data") : "";
}
break;
case "app":
common_vendor.index.requestPayment({
provider: "wxpay",
orderInfo: rs.data,
success(result) {
obj.success ? obj.success(rs) : "";
result_goto("success");
},
fail(result) {
obj.fail ? obj.fail(result) : "";
result_goto("fail");
},
complete(result) {
obj.debug ? console.log("requestPayment complete", result) : "";
obj.complete ? obj.complete(result) : "";
}
});
break;
}
break;
case "2":
switch (obj.method) {
case "app":
common_vendor.index.requestPayment({
provider: "alipay",
orderInfo: rs.msg,
success(result) {
obj.success ? obj.success(rs) : "";
result_goto("success");
},
fail(result) {
obj.fail ? obj.fail(result) : "";
result_goto("fail");
},
complete(result) {
obj.debug ? console.log("requestPayment complete", result) : "";
obj.complete ? obj.complete(result) : "";
}
});
break;
}
break;
case "4":
obj.success ? obj.success(rs) : "";
result_goto("success");
break;
}
} else {
util.alert(rs.msg);
obj.fail ? obj.fail(rs) : "";
}
}).catch((rs) => {
console.log("request catch result", rs);
});
},
// 微信小程序登录
weChatLogin(obj) {
obj = obj ? obj : {};
const parent_id = common_vendor.index.getStorageSync("parent_id");
const admin_id = common_vendor.index.getStorageSync("admin_id");
common_vendor.index.getUserProfile({
desc: "weixin",
success: (e) => {
const userInfo = e.userInfo;
let data = {
nickName: userInfo.nickName,
avatarUrl: userInfo.avatarUrl
};
common_vendor.index.login({
provider: "weixin",
success: (rs) => {
data.code = rs.code;
data.platform = "wechatMini";
if (parent_id)
data.parent_id = parent_id;
if (admin_id)
data.admin_id = admin_id;
if (rs.errMsg == "login:ok") {
util.request({
url: "/api/user/third",
data,
load: 1
}).then((res) => {
if (res.code == 200) {
obj.success ? obj.success(res) : "";
}
});
}
}
});
},
fail(res) {
util.alert("您拒绝了授权");
obj.fail ? obj.fail(res) : (res2) => {
};
},
complete() {
obj.complete ? obj.complete() : "";
}
});
},
/**
* 拉起授权请求: 微信小程序app
*/
authorize(obj) {
return new Promise((resolve, reject) => {
obj ? obj : obj = {};
const menu = {
// 定位
location: {
name: "定位服务",
scope: "scope.userLocation",
txt: "需要获取您的地理位置"
},
// 相册
photosAlbum: {
name: "相册",
scope: "scope.writePhotosAlbum",
txt: "需要访问您的相册"
},
// 相机
camera: {
name: "摄像头",
scope: "scope.camera",
txt: "需要访问您的摄像头"
}
};
if (obj.key) {
obj = {
...obj,
...menu[obj.key]
};
}
let fnName = "";
fnName = "weChatAuthorize";
this[fnName](obj).then((rs) => {
obj.success ? obj.success(rs) : "";
resolve(rs);
}).catch((err) => {
obj.fail ? obj.fail(err) : "";
reject(err);
});
});
},
// app授权
appAuthorize(obj) {
return new Promise((resolve, reject) => {
const systemSetting = common_vendor.index.getSystemSetting();
if (systemSetting.locationEnabled === false) {
this.alert(obj.txt);
reject({
msg: "未授权对应功能"
});
return;
}
const authorized = common_vendor.index.getAppAuthorizeSetting().locationAuthorized;
console.log("locationAuthorized", authorized);
if (authorized === "config error") {
reject({
msg: "开发者未勾选定位服务模块"
});
return;
} else if (authorized === "denied")
;
else if (authorized === "authorized") {
resolve(obj);
return;
}
if (common_vendor.index.getSystemInfoSync().platform == "android") {
plus.android.requestPermissions(
// 对应权限
["android.permission.ACCESS_FINE_LOCATION"],
// 成功
(resultObj) => {
let result = null;
for (let i = 0; i < resultObj.granted.length; i++) {
let grantedPermission = resultObj.granted[i];
console.log("已获取的权限:" + grantedPermission);
}
for (let i = 0; i < resultObj.deniedPresent.length; i++) {
let deniedPresentPermission = resultObj.deniedPresent[i];
console.log("拒绝本次申请的权限:" + deniedPresentPermission);
}
for (let i = 0; i < resultObj.deniedAlways.length; i++) {
let deniedAlwaysPermission = resultObj.deniedAlways[i];
console.log("永久拒绝申请的权限:" + deniedAlwaysPermission);
}
if ([-1].includes(result)) {
common_vendor.index.openAppAuthorizeSetting({
success: (rs) => {
reject({
msg: "引导用户打开设置页面",
info: rs
});
},
fail: (err) => {
reject({
msg: "用户设置页面打开失败",
info: err
});
}
});
}
},
// 失败
(error) => {
console.log("申请权限错误:" + error.code + " = " + error.message);
resolve({
code: error.code,
message: error.message
});
}
);
} else {
this.alert("请在设置里允许打开定位信息");
resolve({
msg: "用户未开启定位权限"
});
return;
}
});
},
// 微信小程序授权
weChatAuthorize(obj) {
return new Promise((resolve, reject) => {
if (![
"scope.userInfo",
"scope.userLocation",
"scope.userLocationBackground",
"scope.address",
"scope.record",
"scope.writePhotosAlbum",
"scope.camera",
"scope.invoice",
"scope.invoiceTitle",
"scope.werun"
].includes(obj.scope)) {
resolve({
msg: "不在限制范围内"
});
return;
}
common_vendor.index.authorize({
scope: obj.scope,
success: (rs) => {
resolve(rs);
},
fail: (err) => {
reject(err);
util.alert({
title: "系统提示",
value: obj.txt,
success: (rs) => {
if (rs.confirm) {
common_vendor.index.openSetting();
}
}
});
}
});
});
},
/**
* 最终登录 用于请求登录接口后统一调用的登录方法
* @param {Object} param 数据对象
* @param {Function} cb 回调函数
*/
finalLogin(param, cb) {
const token = param.data;
common_vendor.index.setStorageSync("token", token);
common_vendor.index.showLoading({
mask: true
});
util.getUserinfo(() => {
common_vendor.index.$emit("login");
setTimeout(() => {
common_vendor.index.switchTab({
url: "/pages/index/index"
});
}, 500);
cb ? cb() : "";
});
},
// 登录账号管理
loginAccountManagement(userInfo) {
let userList = common_vendor.index.getStorageSync("userInfoList") || [];
const index = userList.findIndex((item) => item.userId === userInfo.userId);
if (index !== -1) {
userList.splice(index, 1);
}
userList.push(userInfo);
common_vendor.index.setStorageSync("userInfoList", userList);
},
// 登录腾讯聊天
loginTencent(userInfo) {
try {
const res = TUIKit_debug_GenerateTestUserSig.genTestUserSig({
SDKAppID: common_vendor.index.$SDKAppID,
secretKey: common_vendor.index.$secretKey,
userID: userInfo.userId
});
console.log("uni.$userSig ", res);
common_vendor.index.$userSig = "eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwoamUNHilOzEgoLMFCUrQzMDAwNTcyNzU4hMakVBZlEqUNzU1NQIKAURLcnMBYmZG1maWJqaG1pATclMBxrqHVBmmRmjH5jlnGxSWmnq4*NomZRXEmhcmuhqUeHtWezi45MU4RpcauzsHWirVAsAXPAvzA__";
common_vendor.A.login({
SDKAppID: common_vendor.index.$SDKAppID,
userID: userInfo.userId,
userSig: common_vendor.index.$userSig,
useUploadPlugin: true,
// If you need to send rich media messages, please set to true.
framework: `vue3`
// framework used vue2 / vue3
}).catch(() => {
});
} catch (error) {
console.log(error);
}
},
/**
* 获取用户信息
* @param {Function} cb 回调函数
*/
getUserinfo(cb) {
return new Promise((reslove) => {
api_index.api.mine.getUserinfo().then((rs) => {
if (rs.code === 200) {
const userinfo = rs.user;
console.log("userinfo", userinfo);
userinfo.userPortrait = util.format_url(userinfo.userPortrait, "img");
userinfo.background = util.format_url(userinfo.background, "img");
reslove(rs);
store_index.store.commit("setState", {
key: "userinfo",
value: userinfo
});
util.loginTencent(userinfo);
common_vendor.index.setStorageSync("userinfo", userinfo);
util.loginAccountManagement(userinfo);
cb ? cb() : "";
}
}).finally(() => {
common_vendor.index.hideLoading();
});
});
},
/**
* 验证登录
* @param {Object} cb 回调函数
*/
isLogin(cb) {
let userinfo = common_vendor.index.$store.state.userinfo;
return new Promise((resolve, reject) => {
if (!userinfo.userId) {
reject();
return;
}
resolve();
cb ? cb() : "";
});
},
/**
* 清除登录状态
* @param {Function} cb 回调函数
*/
logout(cb) {
store_index.store.commit("setState", {
key: "userinfo",
value: {}
});
common_vendor.index.removeStorageSync("userinfo");
common_vendor.index.removeStorageSync("token");
common_vendor.index.$emit("logout");
cb ? cb() : "";
},
// 拨打电话
makePhone(phoneNumber) {
if (!phoneNumber) {
util.alert("暂无手机号");
}
common_vendor.index.makePhoneCall({
phoneNumber,
fail(err) {
console.log("err", err);
}
});
},
/**
* 处理路径添加host或这默认图片地址
* @param {String} ev 需要处理的字符串
* @param {String} mode img图片 video视频
* @return {String} 返回的路径
*/
format_url(ev, mode) {
if (!ev)
return "";
if (ev.match(/^http/))
return ev;
return util.config.host + common_js_config.config[{
img: "uploadFilePath",
video: "uploadVideoPath"
}[mode]] + ev;
},
/**
* 去除路径里的host
* @param {Object} ev 需要处理的字符串
* @return {String} 处理之后的路径
*/
replace_url(ev) {
if (!ev || typeof ev != "string")
throw `${ev} is not String`;
let result = ev.slice(ev.indexOf("?fileName=") + 10);
return result;
},
/**
* 格式化经纬度
* @param {String} num 数字或数字字符串
*/
formart_lnglat(num) {
if (!num)
return num;
num = parseFloat(Number(num).toFixed(6));
return num;
},
/**
* 检查跳转
* @param {String} route 路径
* @param {String} type 跳转
*/
checkLink(route, type = "navigateTo") {
const currentPages = getCurrentPages();
const find_route = route;
const find_index = currentPages.findIndex((node) => {
return node.route == find_route;
});
if (find_index < 0) {
common_vendor.index[type]({
url: `/${find_route}`
});
} else {
common_vendor.index.navigateBack({
delta: currentPages.length - find_index - 1
});
}
},
/**
* 数字转化
*/
rp(n) {
var cnum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
var s = "";
n = "" + n;
for (var i = 0; i < n.length; i++) {
s += cnum[parseInt(n.charAt(i))];
}
if (s.length == 2) {
if (s.charAt(1) == cnum[0]) {
s = s.charAt(0) + cnum[10];
if (s == cnum[1] + cnum[10]) {
s = cnum[10];
}
} else if (s.charAt(0) == cnum[1]) {
s = cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[2]) {
s = cnum[2] + cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[3]) {
s = cnum[3] + cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[4]) {
s = cnum[4] + cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[5]) {
s = cnum[5] + cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[6]) {
s = cnum[6] + cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[7]) {
s = cnum[7] + cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[8]) {
s = cnum[8] + cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[9]) {
s = cnum[9] + cnum[10] + s.charAt(1);
} else if (s.charAt(0) == cnum[10]) {
s = cnum[10] + cnum[10] + s.charAt(1);
}
}
return s;
},
/**
* 复制文本
* @param {String} text 需要复制的文本
*/
copyText(text) {
common_vendor.index.setClipboardData({
data: text,
success: () => {
util.alert({
title: "文本已复制到剪贴板"
});
}
});
},
showToastAndRedirect(title, icon = "none", fun = () => {
}) {
common_vendor.index.showToast({
title,
icon,
duration: 2e3,
// 显示两秒
complete: () => {
fun();
common_vendor.index.hideLoading();
}
});
},
notificationChat(user, type) {
switch (type) {
case utils_msgtype.msgType.chatType.SINGLE_CHAT:
user.userNickname;
conversationID = user.userId;
break;
case utils_msgtype.msgType.chatType.GROUP_CHAT:
user.groupname;
conversationID = user.groupid;
break;
default:
console.log("====================================");
console.log("未定义的聊天类型");
console.log("====================================");
return;
}
try {
common_vendor.index.setStorageSync("toUser", {
...user,
msgType: type
});
common_vendor.index.navigateTo({
url: `/TUIKit/components/TUIChat/index?conversationID=C2C${conversationID}`
});
} catch (error) {
console.log("====================================");
console.log(error);
console.log("====================================");
}
}
};
exports.util = util;