You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
599 lines
17 KiB
599 lines
17 KiB
// import {emojiMap,emojiUrl} from './emojiMap';
|
|
import md5 from './md5';
|
|
import qs from 'qs';
|
|
|
|
export const phoneReg = new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/);
|
|
export const mailReg = new RegExp(/^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/);
|
|
export const specialReg = new RegExp("[^a-zA-Z0-9\_\u4e00-\u9fa5]","i");
|
|
|
|
export const debug = false //是否开启debug模式,使用非离线工程模式调试
|
|
|
|
export const isExportLog = false //是否开启log输出
|
|
|
|
export const formatTime = date => {
|
|
const year = date.getFullYear()
|
|
const month = date.getMonth() + 1
|
|
const day = date.getDate()
|
|
const hour = date.getHours()
|
|
const minute = date.getMinutes()
|
|
const second = date.getSeconds()
|
|
|
|
return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
|
|
}
|
|
|
|
export const formatDate = ({ date= new Date(), partition= '-' }) => {
|
|
let _date;
|
|
if(typeof (date) === 'string'&&date.indexOf('-')!=-1){
|
|
_date = new Date(date.replace(/\-/g,'/'))
|
|
}else{
|
|
_date = new Date(date)
|
|
}
|
|
const year = _date.getFullYear();
|
|
const month = _date.getMonth() + 1;
|
|
const day = _date.getDate();
|
|
|
|
if(partition == 'zh')return `${year}年${month}月${day}日`
|
|
return [year, month, day].map(formatNumber).join(partition);
|
|
}
|
|
|
|
export const formatNumber = n => {
|
|
n = n.toString()
|
|
return n[1] ? n : '0' + n
|
|
}
|
|
// 路由跳转
|
|
export const routeTo = (url,type) => {
|
|
switch(type){
|
|
case 'nT': uni.navigateTo({url});
|
|
break
|
|
case 'rT': uni.redirectTo({url});
|
|
break
|
|
case 'rL': uni.reLaunch({url});
|
|
break
|
|
case 'sT': uni.switchTab({url});
|
|
break
|
|
default: uni.navigateBack({delta: 1})
|
|
break
|
|
}
|
|
}
|
|
|
|
function showNone(txt,duration=1500){
|
|
uni.hideToast();
|
|
uni.hideLoading();
|
|
uni.showToast({
|
|
mask: true,
|
|
title: txt,
|
|
icon: 'none',
|
|
duration,
|
|
})
|
|
}
|
|
|
|
function showLoad(title='加载中', mask=true){
|
|
uni.showLoading({
|
|
mask,
|
|
title,
|
|
})
|
|
}
|
|
function hideLoad(){
|
|
uni.hideLoading()
|
|
}
|
|
function showModal({
|
|
title='提示',
|
|
content='',
|
|
showCancel=false,
|
|
cancelText='取消',
|
|
confirmText='确定',
|
|
confirmColor='#009874',
|
|
success,
|
|
fail,
|
|
complete
|
|
}){
|
|
uni.showModal({
|
|
title,
|
|
content,
|
|
showCancel,
|
|
cancelText,
|
|
confirmColor,
|
|
confirmText,
|
|
success,
|
|
fail,
|
|
complete
|
|
})
|
|
}
|
|
|
|
function debounce(func, wait, immediate) {
|
|
let timeout, args, context, timestamp, result;
|
|
const later = function() {
|
|
// 据上一次触发时间间隔
|
|
const last = +new Date() - timestamp;
|
|
// 上次被包装函数被调用时间间隔last小于设定时间间隔wait
|
|
if (last < wait && last > 0) {
|
|
timeout = setTimeout(later, wait - last);
|
|
} else {
|
|
timeout = null;
|
|
// 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
|
|
if (!immediate) {
|
|
result = func.apply(context, args);
|
|
if (!timeout) context = args = null;
|
|
}
|
|
}
|
|
}
|
|
return function(...args) {
|
|
context = this;
|
|
timestamp = +new Date();
|
|
const callNow = immediate && !timeout;
|
|
// 如果延时不存在,重新设定延时
|
|
if (!timeout) timeout = setTimeout(later, wait);
|
|
if (callNow) {
|
|
result = func.apply(context, args);
|
|
context = args = null;
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
|
|
function jsonStr(data){
|
|
return encodeURIComponent(JSON.stringify(data))
|
|
}
|
|
function jsonPar(json){
|
|
return JSON.parse(decodeURIComponent(json))
|
|
}
|
|
|
|
export let promisify = api => {
|
|
return (options, ...params) => {
|
|
return new Promise((resolve, reject) => {
|
|
api(Object.assign({}, options, { success: resolve, fail: reject }), ...params);
|
|
});
|
|
}
|
|
}
|
|
|
|
function previousPageFunction({fnName,query}){
|
|
return new Promise((rs,rj)=>{
|
|
try{
|
|
if(getCurrentPages().length>1){
|
|
console.log(getCurrentPages())
|
|
getCurrentPages()[getCurrentPages().length-2]['$vm'][fnName](query);
|
|
rs('success');
|
|
}else{
|
|
console.error('当前路由栈为一,无法调取上一页数据');
|
|
rj('当前路由栈为一,无法调取上一页数据');
|
|
}
|
|
}catch(err){
|
|
console.error('调用上一页面栈方法失败!',err);
|
|
rj('调用上一页面栈方法失败!');
|
|
}
|
|
})
|
|
|
|
}
|
|
|
|
// 获取节点信息
|
|
function getNodeMes(selector,_this=null){
|
|
return new Promise(rs=>{
|
|
let query = _this ? uni.createSelectorQuery().in(_this) : uni.createSelectorQuery();
|
|
query.select(selector).boundingClientRect(res=>{
|
|
rs(res)
|
|
// this.height = uni.getSystemInfoSync().windowHeight - res.height;
|
|
}).exec()
|
|
})
|
|
}
|
|
|
|
export const convertBase64 = function(base64data){
|
|
const fsm = uni.getFileSystemManager();
|
|
const FILE_BASE_NAME = 'tmp_base64src';//临时文件名
|
|
return new Promise((resolve, reject) => {
|
|
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []; //去掉 base64 的头信息:
|
|
if (!format) {
|
|
reject(new Error('ERROR_BASE64SRC_PARSE'));
|
|
}
|
|
const filePath = `${uni.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
|
|
const buffer = bodyData&&uni.base64ToArrayBuffer(bodyData); //将 base64 数据转换为 ArrayBuffer 数据
|
|
// console.log(uni.base64ToArrayBuffer(bodyData))
|
|
fsm.writeFile({ //将 ArrayBuffer 写为本地用户路径的二进制图片文件 //图片文件路径在 uni.env.USER_DATA_PATH 中
|
|
filePath,
|
|
data: buffer,
|
|
encoding: 'binary',
|
|
success() {
|
|
// console.log(buffer)
|
|
resolve(filePath);
|
|
},
|
|
fail() {
|
|
reject(new Error('ERROR_BASE64SRC_WRITE'));
|
|
},
|
|
});
|
|
});
|
|
}
|
|
export function failAuthorizeTosetting(content='调用失败,请打开检查授权状态'){
|
|
showModal({
|
|
title:'提示',
|
|
content,
|
|
showCancel:true,
|
|
confirmText:'打开',
|
|
success:res=>{if(res.confirm)uni.openSetting()}
|
|
})
|
|
}
|
|
|
|
// 解析小程序码 scene 参数
|
|
export function getSceneQuery(scene){
|
|
const queryStr = decodeURIComponent(scene) || null;
|
|
let queryObj = queryStr.split('&').reduce((obj,el)=>{
|
|
let arr = el.split('=');
|
|
obj[`${arr[0]}`] = arr[1];
|
|
return obj;
|
|
},{}) || null;
|
|
return queryObj;
|
|
}
|
|
|
|
// 格式化聊天内容
|
|
// export function formatContent(str = ''){
|
|
// let reg = /\[[\u4e00-\u9fa5_a-zA-Z0-9]{1,}\]/gi;
|
|
// let strArr = str.split(reg) || [];
|
|
// let emojiArr = str.match(reg) || [];
|
|
// let contentList = [];
|
|
// strArr.forEach(ele=>{
|
|
// if(ele)contentList.push({
|
|
// type:'txt',
|
|
// content:ele
|
|
// });
|
|
// if(!!emojiArr.length){
|
|
// let iconKey = emojiArr.splice(0,1)[0];
|
|
// if(emojiMap[iconKey]){
|
|
// contentList.push({
|
|
// type:'icon',
|
|
// src:`${emojiUrl}${emojiMap[iconKey]}`
|
|
// })
|
|
// }else{
|
|
// contentList.push({
|
|
// type:'txt',
|
|
// content:iconKey
|
|
// });
|
|
// }
|
|
// }
|
|
// });
|
|
// return contentList
|
|
// }
|
|
//获取地址栏里(URL)传递的参数
|
|
function getUrlQuery(key,url){
|
|
var _url = decodeURI(url).split('?a=1').join(''); //剪切'?a=1'安卓兼容,再获取参数
|
|
if(_url.indexOf(`${key}=`) !=-1){
|
|
return _url.split(`${key}=`)[1].split('&')[0]
|
|
}
|
|
return null
|
|
}
|
|
|
|
//获取地址字段栏信息 腾讯获取授权码时
|
|
function getQueryString(name) {
|
|
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
|
|
var r = window.location.search.substr(1).match(reg);
|
|
if (r != null) return (r[2]); // 编码的字符串进行解码
|
|
return null;
|
|
}
|
|
|
|
function getRandom(min, max) {
|
|
return Math.round(Math.random() * (max - min)) + min;
|
|
}
|
|
|
|
export function get_zh_day(date){
|
|
if(isSameDay(new Date().getTime(),new Date(date).getTime()))return '今天'
|
|
const Arr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
|
return Arr[new Date(date).getDay()] || '';
|
|
}
|
|
|
|
// 判断是否同一天
|
|
export function isSameDay(timeStampA, timeStampB) {
|
|
let dateA = new Date(timeStampA);
|
|
let dateB = new Date(timeStampB);
|
|
return (dateA.setHours(0, 0, 0, 0) == dateB.setHours(0, 0, 0, 0));
|
|
}
|
|
|
|
// 获取中文日期
|
|
export function get_zh_date(date = new Date()){
|
|
return `${new Date(date).getMonth()+1}月${new Date(date).getDate()}日`
|
|
}
|
|
|
|
export function substrDate(date){
|
|
if(!date)return;
|
|
return date.substr(0,10) || '-'
|
|
}
|
|
|
|
// package 貌似为保留字,作为参数时 编译报错
|
|
export function requestPayment(query = {}){
|
|
showLoad();
|
|
uni.requestPayment({
|
|
timeStamp: query.timeStamp || '',
|
|
nonceStr: query.nonceStr || '',
|
|
package: query.package || '',
|
|
signType: query.signType || '',
|
|
paySign: query.paySign || '',
|
|
success: function(res){
|
|
query.success&&query.success(res)
|
|
},
|
|
fail: function(res){
|
|
query.fail&&query.fail(res)
|
|
},
|
|
complete: function(res){
|
|
hideLoad();
|
|
query.complete&&query.complete(res)
|
|
},
|
|
})
|
|
}
|
|
function getQueryStr({url,name}){
|
|
let queryArr = (url.split('?')[1] || '').split("&") || [];
|
|
// let vars = query.split("&");
|
|
for (let i=0;i<queryArr.length;i++) {
|
|
let pair = queryArr[i].split("=");
|
|
if(pair[0] == name)return pair[1] || '';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function formatScene(scene = ''){
|
|
let queryArr = scene.split('&');
|
|
return queryArr.reduce((obj,e,i)=>{
|
|
let _arr = e.split('=');
|
|
obj[_arr[0]] = _arr[1];
|
|
return obj;
|
|
},{}) || {};
|
|
}
|
|
|
|
// 获取当天、明天、昨天的日期
|
|
function specialFormatDate(num){
|
|
// num:表示距离当前日期的天数,0表示当天,1明天,-1昨天
|
|
var now = new Date();
|
|
var nowTime = now.getTime();
|
|
var oneDayTime = 24 * 60 * 60 * 1000;
|
|
var ShowTime = nowTime + num * oneDayTime;
|
|
var myDate = new Date(ShowTime);
|
|
let arrDate = {};
|
|
arrDate['y'] = myDate.getFullYear(); //年
|
|
arrDate['m'] = myDate.getMonth() + 1; //月
|
|
arrDate['d'] = myDate.getDate(); //日
|
|
return arrDate;
|
|
}
|
|
// 时分秒 转为毫秒
|
|
function timeToSec(hour, min, sec) {
|
|
var s = Number(hour * 3600) + Number(min * 60) + Number(sec);
|
|
return s * 1000;
|
|
}
|
|
|
|
//log日志函数
|
|
function showLog(data,url,response){
|
|
let weburl = getWebURL(data,url)
|
|
let temp = url.split("?")[0].split("/")
|
|
let postName = temp[temp.length-1]
|
|
if(isExportLog){
|
|
console.error("-------------------->> ["+postName+"][log]\n"
|
|
+"请求 Data: \n" + JSON.stringify(data)
|
|
+"\n URL:\n"+weburl
|
|
+"\n 服务端返回:\n"+JSON.stringify(response.data)
|
|
+"\n <<-------------------- ["+postName+"][log] ↑↑↑\n")
|
|
}
|
|
}
|
|
//获取拼接url
|
|
function getWebURL(data,url){
|
|
let result = ""
|
|
for(var i in data){
|
|
result+=`&${i}=${data[i]}`
|
|
}
|
|
return url+"?"+result.slice(1)
|
|
}
|
|
|
|
// 时间戳转时间格式
|
|
function timestampToFormatDate(value){
|
|
if(!value)return "-";
|
|
var date = new Date(value); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
|
|
var year = date.getFullYear();
|
|
var month = ("0" + (date.getMonth() + 1)).slice(-2);
|
|
var sdate = ("0" + (date.getDate())).slice(-2);
|
|
var hour = ("0" + (date.getHours())).slice(-2);
|
|
var minute = ("0" + (date.getMinutes())).slice(-2);
|
|
var second = ("0" + (date.getSeconds())).slice(-2);
|
|
var result = year + "." + month + "." + sdate + " " + hour + ":" + minute + ":" + second;
|
|
return result || '-';
|
|
}
|
|
|
|
function checkSerialPortMessage(msg){
|
|
if(!msg)return"";
|
|
if(msg=="aa01ea")return""; //第四版设备,每次刷卡后会2次返回该数据.
|
|
return msg
|
|
}
|
|
function getAPIV4(){
|
|
// 一个包含了代码里的所有api_name的js数组,名字叫api_name_arr
|
|
//参考文档2023-07-05-v4版(1)/3568外设接口sdk-1.3.1-2023-07-05-v4版/ph-API文档_20230705.pdf
|
|
var api_name_arr = [
|
|
"whiteLight_Control_Open", //白光-开
|
|
"whiteLight_Control_Close", //白光-关
|
|
"orange_Led_Open", //橙灯-开
|
|
"close_Led", //关闭所有灯
|
|
"red_Led_Open", //红灯-开
|
|
"green_Led_Open", //绿灯-开
|
|
"shutdown", //关机
|
|
"reboot", //重启
|
|
"showNavigationBar", //显示导航栏
|
|
"hideNavigationBar", //隐藏导航栏
|
|
"showStatusBar", //显示状态栏
|
|
"hideStatusBar", //隐藏状态栏
|
|
"nocanStatusBarDrop", //禁止下拉状态栏
|
|
"canStatusBarDrop", //允许下拉状态栏
|
|
"fc_read", //读取防拆状态
|
|
"setSystemTime", //设置系统时间 value:时间戳,单位为毫秒, 比如:1634464800000 为 2021-10-17 18:00
|
|
"isDebugMode", //设置是否打印日志 value:true,false
|
|
"doorbell_control_open", //拉高门铃
|
|
"doorbell_control_close", //拉低门铃
|
|
"ds_control_read", //读取门磁电平
|
|
"open_door_read", //读取开门 door 电平
|
|
"fire_alm_read", //读取烟雾传感器电平
|
|
"reboot_start_app",//开机启动app
|
|
];
|
|
console.warn("注意[setSystemTime, isDebugMode]选项需传入value")
|
|
return api_name_arr
|
|
}
|
|
function getAPIV3(){
|
|
// 一个包含了代码里的所有api_name的js数组,名字叫api_name_arr
|
|
//参考文档3568-SDK-V3/sdkapi-v20201022-r20230522/%E4%B8%BB%E6%9D%BFAPI%E7%BC%96%E7%A8%8B%E6%89%8B%E5%86%8C(20230522).pdf
|
|
var api_name_arr = [
|
|
"hideNavigationBar", //
|
|
"showNavigationBar", //
|
|
"hideStatusBar", //
|
|
"showStatusBar", //
|
|
"navigationBarMaxIdle", //
|
|
"KEEPALIVE_SETUP", //
|
|
"KEEPALIVE_UNSET_ALL", //
|
|
"KEEPALIVE_UNSET", //
|
|
"BOOT_SETUP", //
|
|
"BOOT_UNSET_ALL", //
|
|
"BOOT_UNSET", //
|
|
"hardShutdown", //
|
|
"hardReboot", //
|
|
"softReboot", //
|
|
"getStatusBarStatus", //
|
|
];
|
|
// console.warn("注意[setSystemTime, isDebugMode]选项需传入value")
|
|
return api_name_arr
|
|
}
|
|
|
|
function getPageHeight() {
|
|
return new Promise((resolve, reject) => {
|
|
uni.getSystemInfo({
|
|
success: function(res) {
|
|
// console.log("getSystemInfores", res)
|
|
resolve(res.windowHeight)
|
|
},
|
|
fail:(fail)=>{
|
|
console.log("getSystemInfo fail", fail)
|
|
reject(1000)},
|
|
})
|
|
})
|
|
}
|
|
function getNvueRefSize(that,dom,refName){
|
|
return new Promise((rs,rj)=>{
|
|
// #ifdef APP-NVUE
|
|
let size = dom.getComponentRect(that.$refs[refName], async (option) => {
|
|
// console.log("getNvueRefSize: ",option.result)
|
|
if(option.result)rs(option.size)
|
|
rj(false)
|
|
});
|
|
// #endif
|
|
})
|
|
}
|
|
function getH5RefSize(that,refName){
|
|
return new Promise((rs,rj)=>{
|
|
// #ifdef H5
|
|
// 创建查询请求
|
|
const query = uni.createSelectorQuery().in(that);
|
|
// 选择需要查询的元素
|
|
query.select('.'+refName).boundingClientRect();
|
|
// 执行查询
|
|
query.exec((res) => {
|
|
// console.log(res);
|
|
if (res[0]) {
|
|
// res[0] 是包含节点信息的对象,其中 height 属性是元素的高度
|
|
const height = res[0].height;
|
|
// console.log('元素的高度为:', height);
|
|
rs(res[0])
|
|
} else {
|
|
console.warn('未找到指定元素');
|
|
rj(false)
|
|
}
|
|
});
|
|
// #endif
|
|
})
|
|
}
|
|
|
|
// getUrlParams
|
|
function getUrlParams(url) {
|
|
var params = {};
|
|
var arr = url.split("?");
|
|
if (arr.length <= 1) {
|
|
return params;
|
|
}
|
|
arr = arr[1].split("&");
|
|
for (var i = 0; i < arr.length; i++) {
|
|
var temp = arr[i].split("=");
|
|
params[temp[0]] = temp[1];
|
|
}
|
|
return params;
|
|
}
|
|
|
|
// 获取鉴权校验-逻辑由后端提供
|
|
function encrypt(config) {
|
|
// config.params = config.params || {};
|
|
// config.data = config.data || {};
|
|
// config.url = config.url || '';
|
|
// config.timeDifference
|
|
let a = '';
|
|
if (config.data) {
|
|
a = JSON.stringify(config.data);
|
|
}
|
|
let b = config.url + '?' + qs.stringify(config.params)
|
|
|
|
let t = parseInt(new Date().getTime() / 1000 - config.timeDifference);
|
|
let s = a + '|1ba2212f78610369467de90fb1e3d345|' + b + '|4e68cd333457cb297a05ec7f77a9ad978b56cf57|' + t;
|
|
let md5_str = md5.hex_md5(s)
|
|
return { S: md5_str, T: t }
|
|
}
|
|
|
|
// 更新时间差
|
|
function updateTimeDifference(extension){
|
|
let {now_timestamp} = extension
|
|
let timeDifference = ""
|
|
if(now_timestamp){
|
|
timeDifference = parseInt(new Date().getTime() / 1000 - now_timestamp)
|
|
}
|
|
getApp().globalData.timeDifference = timeDifference
|
|
}
|
|
|
|
// 重置请求头,增加鉴权校验
|
|
function resetHeader(header,url,data,params){
|
|
// if(Object.keys(header).length == 0){} //check header {}
|
|
let timeDifference = getApp().globalData.timeDifference || 0
|
|
let {S,T} = encrypt({data,params,url,timeDifference})
|
|
return {
|
|
...header,
|
|
S,T,
|
|
// 'Content-Type': 'application/x-www-form-urlencoded', //application/json
|
|
// 'Authorization': uni.getStorageSync('token') || '',
|
|
}
|
|
}
|
|
export default {
|
|
checkSerialPortMessage,
|
|
formatTime,
|
|
formatNumber,
|
|
formatDate,
|
|
routeTo,
|
|
showNone,
|
|
showLoad,
|
|
hideLoad,
|
|
showModal,
|
|
debounce,
|
|
jsonStr,
|
|
jsonPar,
|
|
promisify,
|
|
previousPageFunction,
|
|
getNodeMes,
|
|
failAuthorizeTosetting,
|
|
getSceneQuery,
|
|
getUrlQuery,
|
|
getQueryString,
|
|
getRandom,
|
|
get_zh_day,
|
|
isSameDay,
|
|
get_zh_date,
|
|
substrDate,
|
|
requestPayment,
|
|
getQueryStr,
|
|
formatScene,
|
|
specialFormatDate,
|
|
timeToSec,
|
|
debug,
|
|
showLog,
|
|
getWebURL,
|
|
getUrlParams,
|
|
timestampToFormatDate,
|
|
isExportLog,
|
|
getAPIV4,
|
|
getAPIV3,
|
|
getPageHeight,
|
|
getNvueRefSize,
|
|
getH5RefSize,
|
|
resetHeader,
|
|
updateTimeDifference,
|
|
}
|