This commit is contained in:
@fawn-nine
2023-03-03 12:11:23 +08:00
commit f8e1a3015b
502 changed files with 57308 additions and 0 deletions

128
plugins/imageTools.js Normal file
View File

@@ -0,0 +1,128 @@
function getLocalFilePath(path) {
if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
return path
}
if (path.indexOf('file://') === 0) {
return path
}
if (path.indexOf('/storage/emulated/0/') === 0) {
return path
}
if (path.indexOf('/') === 0) {
var localFilePath = plus.io.convertAbsoluteFileSystem(path)
if (localFilePath !== path) {
return localFilePath
} else {
path = path.substr(1)
}
}
return '_www/' + path
}
export function pathToBase64(path) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
var canvas = document.createElement('canvas')
var c2x = canvas.getContext('2d')
var img = new Image
img.onload = function() {
canvas.width = img.width
canvas.height = img.height
c2x.drawImage(img, 0, 0)
resolve(canvas.toDataURL())
}
img.onerror = reject
img.src = path
return
}
if (typeof plus === 'object') {
plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
entry.file(function(file) {
var fileReader = new plus.io.FileReader()
fileReader.onload = function(data) {
resolve(data.target.result)
}
fileReader.onerror = function(error) {
reject(error)
}
fileReader.readAsDataURL(file)
}, function(error) {
reject(error)
})
}, function(error) {
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
wx.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: function(res) {
resolve('data:image/png;base64,' + res.data)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
export function base64ToPath(base64) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64[0].match(/:(.*?);/)[1]
var str = atob(base64[1])
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array[n] = str.charCodeAt(n)
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
}
var extName = base64.match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName[1]
} else {
reject(new Error('base64 error'))
}
var fileName = Date.now() + '.' + extName
if (typeof plus === 'object') {
var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, function() {
var filePath = '_doc/uniapp_temp/' + fileName
bitmap.save(filePath, {}, function() {
bitmap.clear()
resolve(filePath)
}, function(error) {
bitmap.clear()
reject(error)
})
}, function(error) {
bitmap.clear()
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
encoding: 'base64',
success: function() {
resolve(filePath)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}

203
plugins/md5.js Normal file
View File

@@ -0,0 +1,203 @@
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 1.1 Copyright (C) Paul Johnston 1999 - 2002.
* Code also contributed by Greg Holt
* See http://pajhome.org.uk/site/legal.html for details.
*/
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF)
var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
return (msw << 16) | (lsw & 0xFFFF)
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt))
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function cmn(q, a, b, x, s, t) {
return safe_add(rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t)
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t)
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t)
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t)
}
/*
* Calculate the MD5 of an array of little-endian words, producing an array
* of little-endian words.
*/
function coreMD5(x) {
var a = 1732584193
var b = -271733879
var c = -1732584194
var d = 271733878
for (var i = 0; i < x.length; i += 16) {
var olda = a
var oldb = b
var oldc = c
var oldd = d
a = ff(a, b, c, d, x[i + 0], 7, -680876936)
d = ff(d, a, b, c, x[i + 1], 12, -389564586)
c = ff(c, d, a, b, x[i + 2], 17, 606105819)
b = ff(b, c, d, a, x[i + 3], 22, -1044525330)
a = ff(a, b, c, d, x[i + 4], 7, -176418897)
d = ff(d, a, b, c, x[i + 5], 12, 1200080426)
c = ff(c, d, a, b, x[i + 6], 17, -1473231341)
b = ff(b, c, d, a, x[i + 7], 22, -45705983)
a = ff(a, b, c, d, x[i + 8], 7, 1770035416)
d = ff(d, a, b, c, x[i + 9], 12, -1958414417)
c = ff(c, d, a, b, x[i + 10], 17, -42063)
b = ff(b, c, d, a, x[i + 11], 22, -1990404162)
a = ff(a, b, c, d, x[i + 12], 7, 1804603682)
d = ff(d, a, b, c, x[i + 13], 12, -40341101)
c = ff(c, d, a, b, x[i + 14], 17, -1502002290)
b = ff(b, c, d, a, x[i + 15], 22, 1236535329)
a = gg(a, b, c, d, x[i + 1], 5, -165796510)
d = gg(d, a, b, c, x[i + 6], 9, -1069501632)
c = gg(c, d, a, b, x[i + 11], 14, 643717713)
b = gg(b, c, d, a, x[i + 0], 20, -373897302)
a = gg(a, b, c, d, x[i + 5], 5, -701558691)
d = gg(d, a, b, c, x[i + 10], 9, 38016083)
c = gg(c, d, a, b, x[i + 15], 14, -660478335)
b = gg(b, c, d, a, x[i + 4], 20, -405537848)
a = gg(a, b, c, d, x[i + 9], 5, 568446438)
d = gg(d, a, b, c, x[i + 14], 9, -1019803690)
c = gg(c, d, a, b, x[i + 3], 14, -187363961)
b = gg(b, c, d, a, x[i + 8], 20, 1163531501)
a = gg(a, b, c, d, x[i + 13], 5, -1444681467)
d = gg(d, a, b, c, x[i + 2], 9, -51403784)
c = gg(c, d, a, b, x[i + 7], 14, 1735328473)
b = gg(b, c, d, a, x[i + 12], 20, -1926607734)
a = hh(a, b, c, d, x[i + 5], 4, -378558)
d = hh(d, a, b, c, x[i + 8], 11, -2022574463)
c = hh(c, d, a, b, x[i + 11], 16, 1839030562)
b = hh(b, c, d, a, x[i + 14], 23, -35309556)
a = hh(a, b, c, d, x[i + 1], 4, -1530992060)
d = hh(d, a, b, c, x[i + 4], 11, 1272893353)
c = hh(c, d, a, b, x[i + 7], 16, -155497632)
b = hh(b, c, d, a, x[i + 10], 23, -1094730640)
a = hh(a, b, c, d, x[i + 13], 4, 681279174)
d = hh(d, a, b, c, x[i + 0], 11, -358537222)
c = hh(c, d, a, b, x[i + 3], 16, -722521979)
b = hh(b, c, d, a, x[i + 6], 23, 76029189)
a = hh(a, b, c, d, x[i + 9], 4, -640364487)
d = hh(d, a, b, c, x[i + 12], 11, -421815835)
c = hh(c, d, a, b, x[i + 15], 16, 530742520)
b = hh(b, c, d, a, x[i + 2], 23, -995338651)
a = ii(a, b, c, d, x[i + 0], 6, -198630844)
d = ii(d, a, b, c, x[i + 7], 10, 1126891415)
c = ii(c, d, a, b, x[i + 14], 15, -1416354905)
b = ii(b, c, d, a, x[i + 5], 21, -57434055)
a = ii(a, b, c, d, x[i + 12], 6, 1700485571)
d = ii(d, a, b, c, x[i + 3], 10, -1894986606)
c = ii(c, d, a, b, x[i + 10], 15, -1051523)
b = ii(b, c, d, a, x[i + 1], 21, -2054922799)
a = ii(a, b, c, d, x[i + 8], 6, 1873313359)
d = ii(d, a, b, c, x[i + 15], 10, -30611744)
c = ii(c, d, a, b, x[i + 6], 15, -1560198380)
b = ii(b, c, d, a, x[i + 13], 21, 1309151649)
a = ii(a, b, c, d, x[i + 4], 6, -145523070)
d = ii(d, a, b, c, x[i + 11], 10, -1120210379)
c = ii(c, d, a, b, x[i + 2], 15, 718787259)
b = ii(b, c, d, a, x[i + 9], 21, -343485551)
a = safe_add(a, olda)
b = safe_add(b, oldb)
c = safe_add(c, oldc)
d = safe_add(d, oldd)
}
return [a, b, c, d]
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray) {
var hex_tab = "0123456789abcdef"
var str = ""
for (var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF)
}
return str
}
/*
* Convert an array of little-endian words to a base64 encoded string.
*/
function binl2b64(binarray) {
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
var str = ""
for (var i = 0; i < binarray.length * 32; i += 6) {
str += tab.charAt(((binarray[i >> 5] << (i % 32)) & 0x3F) |
((binarray[i >> 5 + 1] >> (32 - i % 32)) & 0x3F))
}
return str
}
/*
* Convert an 8-bit character string to a sequence of 16-word blocks, stored
* as an array, and append appropriate padding for MD4/5 calculation.
* If any of the characters are >255, the high byte is silently ignored.
*/
function str2binl(str) {
var nblk = ((str.length + 8) >> 6) + 1 // number of 16-word blocks
var blks = new Array(nblk * 16)
for (var i = 0; i < nblk * 16; i++) blks[i] = 0
for (var i = 0; i < str.length; i++)
blks[i >> 2] |= (str.charCodeAt(i) & 0xFF) << ((i % 4) * 8)
blks[i >> 2] |= 0x80 << ((i % 4) * 8)
blks[nblk * 16 - 2] = str.length * 8
return blks
}
/*
* Convert a wide-character string to a sequence of 16-word blocks, stored as
* an array, and append appropriate padding for MD4/5 calculation.
*/
function strw2binl(str) {
var nblk = ((str.length + 4) >> 5) + 1 // number of 16-word blocks
var blks = new Array(nblk * 16)
for (var i = 0; i < nblk * 16; i++) blks[i] = 0
for (var i = 0; i < str.length; i++)
blks[i >> 1] |= str.charCodeAt(i) << ((i % 2) * 16)
blks[i >> 1] |= 0x80 << ((i % 2) * 16)
blks[nblk * 16 - 2] = str.length * 16
return blks
}
/*
* External interface
*/
function md5(str) { return binl2hex(coreMD5(str2binl(str))) }
function hexMD5w(str) { return binl2hex(coreMD5(strw2binl(str))) }
function b64MD5(str) { return binl2b64(coreMD5(str2binl(str))) }
function b64MD5w(str) { return binl2b64(coreMD5(strw2binl(str))) }
/* Backward compatibility */
function calcMD5(str) { return binl2hex(coreMD5(str2binl(str))) }
module.exports = md5

348
plugins/permission.js Normal file
View File

@@ -0,0 +1,348 @@
/**
* 本模块封装了Android、iOS的应用权限判断、打开应用权限设置界面、以及位置系统服务是否开启
*/
var isIos
// #ifdef APP-PLUS
isIos = (plus.os.name == "iOS")
// #endif
// 判断推送权限是否开启
function judgeIosPermissionPush() {
var result = 0;
var UIApplication = plus.ios.import("UIApplication");
var app = UIApplication.sharedApplication();
var enabledTypes = 0;
if (app.currentUserNotificationSettings) {
var settings = app.currentUserNotificationSettings();
enabledTypes = settings.plusGetAttribute("types");
if (enabledTypes == 0) {
console.log("推送权限没有开启");
} else {
result = 1;
console.log("已经开启推送功能!")
}
plus.ios.deleteObject(settings);
} else {
enabledTypes = app.enabledRemoteNotificationTypes();
if (enabledTypes == 0) {
console.log("推送权限没有开启!");
} else {
result = 1;
console.log("已经开启推送功能!")
}
console.log("enabledTypes2:" + enabledTypes);
}
plus.ios.deleteObject(app);
plus.ios.deleteObject(UIApplication);
return result;
}
// 判断定位权限是否开启
function judgeIosPermissionLocation() {
var result = 0;
var cllocationManger = plus.ios.import("CLLocationManager");
var status = cllocationManger.authorizationStatus();
result = (status != 2) ? 1 : 0;
console.log("定位权限开启:" + result);
// 以下代码判断了手机设备的定位是否关闭,推荐另行使用方法 checkSystemEnableLocation
/* var enable = cllocationManger.locationServicesEnabled();
var status = cllocationManger.authorizationStatus();
console.log("enable:" + enable);
console.log("status:" + status);
if (enable && status != 2) {
result = true;
console.log("手机定位服务已开启且已授予定位权限");
} else {
console.log("手机系统的定位没有打开或未给予定位权限");
} */
plus.ios.deleteObject(cllocationManger);
return {
result: result,
permissionName: "定位"
};
}
// 判断麦克风权限是否开启
function judgeIosPermissionRecord() {
var result = 0;
var avaudiosession = plus.ios.import("AVAudioSession");
var avaudio = avaudiosession.sharedInstance();
var permissionStatus = avaudio.recordPermission();
console.log("permissionStatus:" + permissionStatus);
if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {
console.log("麦克风权限没有开启");
} else {
result = 1;
console.log("麦克风权限已经开启");
}
plus.ios.deleteObject(avaudiosession);
return {
result: result,
permissionName: "麦克风"
};
}
// 判断相机权限是否开启
function judgeIosPermissionCamera() {
var result = 0;
var AVCaptureDevice = plus.ios.import("AVCaptureDevice");
var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
console.log("authStatus:" + authStatus);
if (authStatus == 3) {
result = 1;
console.log("相机权限已经开启");
} else {
console.log("相机权限没有开启");
}
plus.ios.deleteObject(AVCaptureDevice);
return {
result: result,
permissionName: "相机"
};
}
// 判断相册权限是否开启
function judgeIosPermissionPhotoLibrary() {
var result = 0;
var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
var authStatus = PHPhotoLibrary.authorizationStatus();
console.log("authStatus:" + authStatus);
if (authStatus == 3) {
result = 1;
console.log("相册权限已经开启");
} else {
console.log("相册权限没有开启");
}
plus.ios.deleteObject(PHPhotoLibrary);
return {
result: result,
permissionName: "相册"
};
}
// 判断通讯录权限是否开启
function judgeIosPermissionContact() {
var result = 0;
var CNContactStore = plus.ios.import("CNContactStore");
var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
if (cnAuthStatus == 3) {
result = 1;
console.log("通讯录权限已经开启");
} else {
console.log("通讯录权限没有开启");
}
plus.ios.deleteObject(CNContactStore);
return {
result: result,
permissionName: "通讯录"
};
}
// 判断日历权限是否开启
function judgeIosPermissionCalendar() {
var result = 0;
var EKEventStore = plus.ios.import("EKEventStore");
var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
if (ekAuthStatus == 3) {
result = 1;
console.log("日历权限已经开启");
} else {
console.log("日历权限没有开启");
}
plus.ios.deleteObject(EKEventStore);
return {
result: result,
permissionName: "日历"
};
}
// 判断备忘录权限是否开启
function judgeIosPermissionMemo() {
var result = 0;
var EKEventStore = plus.ios.import("EKEventStore");
var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
if (ekAuthStatus == 3) {
result = 1;
console.log("备忘录权限已经开启");
} else {
console.log("备忘录权限没有开启");
}
plus.ios.deleteObject(EKEventStore);
return {
result: result,
permissionName: "备忘录"
};
}
// Android权限查询
function requestAndroidPermission(permissionID, permissionName) {
return new Promise((resolve, reject) => {
plus.android.requestPermissions(
[permissionID], // 理论上支持多个权限同时查询,但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
function (resultObj) {
var result = 0;
for (var i = 0; i < resultObj.granted.length; i++) {
var grantedPermission = resultObj.granted[i];
console.log('已获取的权限:' + grantedPermission);
result = 1
}
for (var i = 0; i < resultObj.deniedPresent.length; i++) {
var deniedPresentPermission = resultObj.deniedPresent[i];
console.log('拒绝本次申请的权限:' + deniedPresentPermission);
result = 0
}
for (var i = 0; i < resultObj.deniedAlways.length; i++) {
var deniedAlwaysPermission = resultObj.deniedAlways[i];
console.log('永久拒绝申请的权限:' + deniedAlwaysPermission);
result = -1
}
resolve({
result: result,
permissionName: permissionName
});
// 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
// if (result != 1) {
// gotoAppPermissionSetting()
// }
},
function (error) {
console.log('申请权限错误:' + error.code + " = " + error.message);
resolve({
code: error.code,
message: error.message
});
}
);
});
}
// 使用一个方法,根据参数判断权限
function judgePermission(permissionID, callback) {
function handle(res) {
callback && callback(res.result);
if (res.result === -1) {
uni.showModal({
title: "提示",
content: "您还未开通" + res.permissionName + "权限,是否去应用设置里开通~",
confirmText: "去开通",
cancelText: "再逛会",
success: (data) => {
if (data.confirm) {
gotoAppPermissionSetting();
}
}
});
}
}
if (permissionID == "location") { // 位置
if (isIos) {
handle(judgeIosPermissionLocation());
} else {
requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION", "位置").then(handle);
}
} else if (permissionID == "camera") { // 摄像头
if (isIos) {
handle(judgeIosPermissionCamera());
} else {
requestAndroidPermission("android.permission.CAMERA", "摄像头").then(handle);
}
} else if (permissionID == "photoLibrary") { // 相册
if (isIos) {
handle(judgeIosPermissionPhotoLibrary());
} else {
requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE", "相册读取").then(handle);
}
} else if (permissionID == "record") { // 麦克风
if (isIos) {
handle(judgeIosPermissionRecord());
} else {
requestAndroidPermission("android.permission.RECORD_AUDIO", "麦克风").then(handle);
}
} else if (permissionID == "push") { // 推送
if (isIos) {
handle(judgeIosPermissionPush());
} else {
handle(1);
}
} else if (permissionID == "contact") { // 通讯录
if (isIos) {
handle(judgeIosPermissionContact());
} else {
requestAndroidPermission("android.permission.READ_CONTACTS", "通讯录读取").then(handle);
}
} else if (permissionID == "calendar") { // 日历
if (isIos) {
handle(judgeIosPermissionCalendar());
} else {
requestAndroidPermission("android.permission.READ_CALENDAR", "日历读取").then(handle);
}
} else if (permissionID == "memo") { // 备忘录
if (isIos) {
handle(judgeIosPermissionMemo());
} else {
handle(1);
}
} else if (permissionID == "call_phone") { // 拨打电话
if (isIos) {
handle(1);
} else {
requestAndroidPermission("android.permission.CALL_PHONE", "拨打电话").then(handle);
}
}
}
// 跳转到**应用**的权限页面
function gotoAppPermissionSetting() {
if (isIos) {
var UIApplication = plus.ios.import("UIApplication");
var application2 = UIApplication.sharedApplication();
var NSURL2 = plus.ios.import("NSURL");
// var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
var setting2 = NSURL2.URLWithString("app-settings:");
application2.openURL(setting2);
plus.ios.deleteObject(setting2);
plus.ios.deleteObject(NSURL2);
plus.ios.deleteObject(application2);
} else {
// console.log(plus.device.vendor);
var Intent = plus.android.importClass("android.content.Intent");
var Settings = plus.android.importClass("android.provider.Settings");
var Uri = plus.android.importClass("android.net.Uri");
var mainActivity = plus.android.runtimeMainActivity();
var intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
intent.setData(uri);
mainActivity.startActivity(intent);
}
}
// 检查系统的设备服务是否开启
// var checkSystemEnableLocation = async function () {
function checkSystemEnableLocation() {
if (isIos) {
var result = false;
var cllocationManger = plus.ios.import("CLLocationManager");
var result = cllocationManger.locationServicesEnabled();
console.log("系统定位开启:" + result);
plus.ios.deleteObject(cllocationManger);
return result;
} else {
var context = plus.android.importClass("android.content.Context");
var locationManager = plus.android.importClass("android.location.LocationManager");
var main = plus.android.runtimeMainActivity();
var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
var result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
console.log("系统定位开启:" + result);
return result
}
}
module.exports = {
judgePermission: judgePermission,
requestAndroidPermission: requestAndroidPermission,
checkSystemEnableLocation: checkSystemEnableLocation,
gotoAppPermissionSetting: gotoAppPermissionSetting
}

880
plugins/utils.js Normal file
View File

@@ -0,0 +1,880 @@
// #ifdef APP-PLUS
import {
judgePermission
} from './permission'
// #endif
import Vue from 'vue';
// 身份证格式校验
export const checkIdCard = function(sIdCard) {
//Wi 加权因子 Xi 余数0~10对应的校验码 Pi省份代码
let Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
Xi = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2],
Pi = [11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 50, 51, 52, 53, 54,
61, 62, 63, 64, 65, 71, 81, 82, 91
],
checkStatus = 0;
// 检查身份证长度
if(sIdCard.length == 18){
checkStatus += 1;
}
//检验输入的省份编码是否有效
if(checkStatus >= 1){
let p2 = sIdCard.substr(0, 2);
for (let i = 0; i < Pi.length; i++) {
if (Pi[i] == p2) {
checkStatus += 1;
}
}
}
//检验18位身份证号码出生日期是否有效
//parseFloat过滤前导零年份必需大于等于1900且小于等于当前年份用Date()对象判断日期是否有效。
if(checkStatus >= 2){
let year = parseFloat(sIdCard.substr(6, 4));
let month = parseFloat(sIdCard.substr(10, 2));
let day = parseFloat(sIdCard.substr(12, 2));
let checkDay = new Date(year, month - 1, day);
let nowDay = new Date();
if (1900 <= year && year <= nowDay.getFullYear() && month == (checkDay.getMonth() + 1) && day == checkDay
.getDate()) {
checkStatus += 1;
}
}
//检验校验码是否有效
if(checkStatus >= 3){
let aIdCard = sIdCard.split("");
let sum = 0;
for (let j = 0; j < Wi.length; j++) {
sum += Wi[j] * aIdCard[j]; //线性加权求和
}
let index = sum % 11; //求模可能为0~10,可求对应的校验码是否于身份证的校验码匹配
if (Xi[index] == aIdCard[17].toUpperCase()) {
checkStatus += 1;
}
}
if (checkStatus == 4) {
return true;
} else {
return false;
}
};
/**
* 时间转换为XX前
*/
export const clickDateDiff = function(value) {
let dataValue = value;
if (typeof value == "string") {
dataValue = new Date(value.replace(/-/g, "/")).getTime();
}
var result;
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var month = day * 30;
var now = new Date().getTime();
var diffValue = parseInt(now) - parseInt(dataValue);
if (diffValue < 0) {
return;
}
var monthC = diffValue / month;
var weekC = diffValue / (7 * day);
var dayC = diffValue / day;
var hourC = diffValue / hour;
var minC = diffValue / minute;
if (monthC >= 1) {
result = "" + parseInt(monthC) + '月前';
} else if (weekC >= 1) {
result = "" + parseInt(weekC) + '周前';
} else if (dayC >= 1) {
result = "" + parseInt(dayC) + '天前';
} else if (hourC >= 1) {
result = "" + parseInt(hourC) + '小时前';
} else if (minC >= 1) {
result = "" + parseInt(minC) + '分钟前';
} else {
result = '刚刚';
}
return result;
};
/**
* 时间戳转换为想要的时间格式
*/
//时间戳转换为时间 format('yyyy-MM-dd hh:mm:ss')
//时间格式转换
Date.prototype.format = function(fmt = 'yyyy-MM-dd hh:mm:ss') { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
"00" + o[
k]).substr(("" + o[k]).length)));
return fmt;
}
// 保存图片
let settingWritePhotosAlbum = false;
export const saveImg = function(url, callback) {
if (url) {
// #ifdef MP-WEIXIN
if (settingWritePhotosAlbum) {
uni.getSetting({
success: res => {
if (res.authSetting['scope.writePhotosAlbum']) {
uni.showLoading({
title: '正在下载'
});
uni.downloadFile({
url: url,
success: data => {
if (data.statusCode == 200) {
uni.saveImageToPhotosAlbum({
filePath: data.tempFilePath,
success: () => {
uni.hideLoading();
callback && callback();
uni.showToast({
title: '保存成功'
});
},
fail(e) {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + e
.errMsg,
icon: "none"
});
}
});
} else {
uni.hideLoading();
uni.showToast({
title: '下载失败',
icon: "none"
});
}
},
fail(e) {
uni.hideLoading();
uni.showToast({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
} else {
uni.showModal({
title: '提示',
content: '请先在设置页面打开“保存相册”使用权限',
confirmText: '去设置',
cancelText: '算了',
success: data => {
if (data.confirm) {
uni.openSetting();
}
}
});
}
}
});
} else {
settingWritePhotosAlbum = true;
uni.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
uni.showLoading({
title: '正在下载'
});
uni.downloadFile({
url: url,
success: data => {
if (data.statusCode == 200) {
uni.saveImageToPhotosAlbum({
filePath: data.tempFilePath,
success: () => {
uni.hideLoading();
callback && callback();
uni.showToast({
title: '保存成功'
});
},
fail(e) {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
} else {
uni.hideLoading();
uni.showToast({
title: '下载失败',
icon: "none"
});
}
},
fail(e) {
uni.hideLoading();
uni.showToast({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
}
});
}
// #endif
// #ifdef H5
uni.showLoading({
title: '正在下载'
});
uni.downloadFile({
url: url,
success: data => {
uni.hideLoading();
if (data.statusCode == 200) {
callback && callback();
window.open(data.tempFilePath);
} else {
uni.showToast({
title: '下载失败',
icon: "none"
});
}
},
fail(e) {
uni.hideLoading();
uni.showToast({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
// #endif
// #ifdef APP-PLUS
uni.showLoading({
title: '正在下载'
});
uni.saveImageToPhotosAlbum({
filePath: url,
success: () => {
uni.hideLoading();
callback && callback();
uni.showToast({
title: '保存成功'
});
},
fail(e) {
uni.hideLoading();
uni.showToast({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
// #endif
} else {
uni.showToast({
title: '未找到图片',
icon: 'none'
});
}
};
// 保存视频
function tip(data) {
setTimeout(() => {
uni.showToast(data);
}, 500);
}
export const saveVideo = function(url, callback) {
if (url) {
// #ifdef MP-WEIXIN
if (settingWritePhotosAlbum) {
uni.getSetting({
success: res => {
if (res.authSetting['scope.writePhotosAlbum']) {
// let urlArr = url.split("/");
// let updateUrl = urlArr[urlArr.length - 1];
// let filePath = wx.env.USER_DATA_PATH + '/' + updateUrl;
uni.showLoading({
title: '正在下载'
});
uni.downloadFile({
url: url,
// filePath: filePath,
success: data => {
if (data.statusCode == 200) {
uni.saveVideoToPhotosAlbum({
filePath: data.tempFilePath,
success: () => {
uni.hideLoading();
callback && callback();
tip({
title: '保存成功'
});
},
fail(e) {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + e
.errMsg,
icon: "none"
});
}
});
} else {
uni.hideLoading();
tip({
title: '下载失败',
icon: "none"
});
}
},
fail(e) {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
} else {
uni.showModal({
title: '提示',
content: '请先在设置页面打开“保存相册”使用权限',
confirmText: '去设置',
cancelText: '算了',
success: data => {
if (data.confirm) {
uni.openSetting();
}
}
});
}
}
});
} else {
settingWritePhotosAlbum = true;
uni.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
// let urlArr = url.split("/");
// let updateUrl = urlArr[urlArr.length - 1];
// let filePath = wx.env.USER_DATA_PATH + '/' + updateUrl;
uni.showLoading({
title: '正在下载'
});
uni.downloadFile({
url: url,
// filePath: filePath,
success: data => {
if (data.statusCode == 200) {
uni.saveVideoToPhotosAlbum({
filePath: data.tempFilePath,
success: () => {
uni.hideLoading();
callback && callback();
tip({
title: '保存成功'
});
},
fail(e) {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
} else {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + data.errMsg,
icon: "none"
});
}
},
fail(e) {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
}
});
}
// #endif
// #ifdef H5
uni.showLoading({
title: '正在下载'
});
uni.downloadFile({
url: url,
success: data => {
uni.hideLoading();
if (data.statusCode == 200) {
callback && callback();
window.open(data.tempFilePath);
} else {
tip({
title: '下载失败',
icon: "none"
});
}
},
fail(e) {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
// #endif
// #ifdef APP-PLUS
uni.showLoading({
title: '正在下载'
});
uni.saveVideoToPhotosAlbum({
filePath: url,
success: () => {
uni.hideLoading();
callback && callback();
tip({
title: '保存成功'
});
},
fail(e) {
uni.hideLoading();
tip({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
// #endif
} else {
tip({
title: '未找到视频',
icon: 'none'
});
}
};
// 微信小程序获取定位权限判断
function wxAppletsLocation(successCallback, errCallback) {
uni.getSetting({
success: res => {
if (res.authSetting['scope.userLocation']) {
uni.getLocation({
type: 'gcj02',
success: res => {
successCallback(res);
},
fail: (err) => {
console.log("位置信息错误", err);
errCallback("位置信息获取失败");
}
});
} else {
errCallback("“位置信息”未授权");
uni.showModal({
title: '提示',
content: '请先在设置页面打开“位置信息”使用权限',
confirmText: '去设置',
cancelText: '再逛会',
success: res => {
if (res.confirm) {
uni.openSetting();
}
}
});
}
}
});
}
// 获取地址信息
let locationAuthorize = true;
export const getAppWxLatLon = function(successCallback, errCallback) {
const _this = this;
// #ifdef MP
if (locationAuthorize) {
uni.authorize({
scope: 'scope.userLocation',
success: () => {
wxAppletsLocation(successCallback, errCallback);
locationAuthorize = false;
},
fail: () => {
locationAuthorize = false;
}
});
} else {
wxAppletsLocation(successCallback, errCallback);
}
// #endif
// #ifdef APP-PLUS
judgePermission("location", function(result) {
if (result == 1) {
uni.getLocation({
type: 'gcj02',
success: res => {
// store.commit("setCurrentAddress", {
// latitude: res.latitude,
// longitude: res.longitude
// });
successCallback(res);
},
fail: (err) => {
console.log("位置信息错误", err);
errCallback("位置信息获取失败");
}
});
}
});
// #endif
}
//金额过滤
Vue.filter('money', function(val) {
console.log(val);
if (val) {
let value = Math.round(parseFloat(val) * 100) / 100;
let valMoney = value.toString().split(".");
if (valMoney.length == 1) {
value = value.toString() + ".00";
return value;
}
if (valMoney.length > 1) {
if (valMoney[1].length < 2) {
value = value.toString() + "0";
}
return value;
}
return value;
} else {
return "0.00";
}
});
//时间格式化
Vue.filter('dateDiff', function(val) {
if (val) {
return clickDateDiff(val);
} else {
return "";
}
});
// 时间距离现在多少天前
Vue.filter('timeFormat', function(val, fmt = 'yyyy-MM-dd hh:mm:ss') {
if (val) {
if(typeof val == "string"){
let timeText = val.replace(/-/g, "/");
return new Date(timeText).format(fmt);
} else if(typeof val == "number"){
return new Date(val).format(fmt);
}
} else {
return "";
}
});
// #ifdef APP-PLUS
// 文字换行
function drawtext(text, maxWidth) {
let textArr = text.split("");
let len = textArr.length;
// 上个节点
let previousNode = 0;
// 记录节点宽度
let nodeWidth = 0;
// 文本换行数组
let rowText = [];
// 如果是字母,侧保存长度
let letterWidth = 0;
// 汉字宽度
let chineseWidth = 16;
// otherFont宽度
let otherWidth = 8;
for (let i = 0; i < len; i++) {
if (/[\u4e00-\u9fa5]|[\uFE30-\uFFA0]/g.test(textArr[i])) {
if(letterWidth > 0){
if(nodeWidth + chineseWidth + letterWidth * otherWidth > maxWidth){
rowText.push({
type: "text",
content: text.substring(previousNode, i)
});
previousNode = i;
nodeWidth = chineseWidth;
letterWidth = 0;
} else {
nodeWidth += chineseWidth + letterWidth * otherWidth;
letterWidth = 0;
}
} else {
if(nodeWidth + chineseWidth > maxWidth){
rowText.push({
type: "text",
content: text.substring(previousNode, i)
});
previousNode = i;
nodeWidth = chineseWidth;
}else{
nodeWidth += chineseWidth;
}
}
} else {
if(/\n/g.test(textArr[i])){
rowText.push({
type: "break",
content: text.substring(previousNode, i)
});
previousNode = i + 1;
nodeWidth = 0;
letterWidth = 0;
}else if(textArr[i] == "\\" && textArr[i + 1] == "n"){
rowText.push({
type: "break",
content: text.substring(previousNode, i)
});
previousNode = i + 2;
nodeWidth = 0;
letterWidth = 0;
}else if(/[a-zA-Z0-9]/g.test(textArr[i])){
letterWidth += 1;
if(nodeWidth + letterWidth * otherWidth > maxWidth){
rowText.push({
type: "text",
content: text.substring(previousNode, i + 1 - letterWidth)
});
previousNode = i + 1 - letterWidth;
nodeWidth = letterWidth * otherWidth;
letterWidth = 0;
}
} else{
if(nodeWidth + otherWidth > maxWidth){
rowText.push({
type: "text",
content: text.substring(previousNode, i)
});
previousNode = i;
nodeWidth = otherWidth;
}else{
nodeWidth += otherWidth;
}
}
}
}
if (previousNode < len) {
rowText.push({
type: "text",
content: text.substring(previousNode, len)
});
}
return rowText;
}
// 重写app弹窗
uni.showModal = function(options){
let optionsObj = Object.assign({
title: "提示",
content: "自定义内容",
align: "center", // 对齐方式 left/center/right
cancelText: "取消", // 取消按钮的文字
cancelColor: "#8F8F8F", // 取消按钮颜色
confirmText: "确定", // 确认按钮文字
confirmColor: "#1C79D6", // 确认按钮颜色
showCancel: true, // 是否显示取消按钮,默认为 true
}, options);
// 以下为计算菜单的nview绘制布局为固定算法使用者无关关心
const screenWidth = plus.screen.resolutionWidth;
const screenHeight = plus.screen.resolutionHeight;
//弹窗容器宽度
const popupViewWidth = screenWidth * 0.8;
// 弹窗容器的Padding
const viewContentPadding = 20;
// 弹窗容器的宽度
const viewContentWidth = parseInt(popupViewWidth - (viewContentPadding * 2));
// 描述的列表
const descriptionList = drawtext(optionsObj.content, viewContentWidth);
// 弹窗高度
let popupViewHeight = 168;
// 弹窗遮罩层
let maskLayer = new plus.nativeObj.View("maskLayer", { //先创建遮罩层
top: '0px',
left: '0px',
height: '100%',
width: '100%',
backgroundColor: 'rgba(0,0,0,0.5)'
});
let popupViewContentList = [{
tag: 'font',
id: 'title',
text: optionsObj.title,
textStyles: {
size: '18px',
color: "#333",
weight: "bold",
whiteSpace: "normal"
},
position: {
top: viewContentPadding + "px",
left: viewContentPadding + "px",
width: viewContentWidth + "px",
height: "30px",
}
}];
const textHeight = 22;
let contentTop = 65;
descriptionList.forEach((item,index) => {
if(index > 0){
popupViewHeight += textHeight;
contentTop += textHeight;
}
popupViewContentList.push({
tag: 'font',
id: 'content' + index + 1,
text: item.content,
textStyles: {
size: '16px',
color: "#333",
lineSpacing: "50%",
align: optionsObj.align
},
position: {
top: contentTop + "px",
left: viewContentPadding + "px",
width: viewContentWidth + "px",
height: textHeight + "px",
}
});
if(item.type == "break"){
contentTop += 10;
popupViewHeight += 10;
}
});
popupViewContentList.push({
tag: 'rect',
id: 'lineTop',
rectStyles: {
color: "#f1f1f1",
},
position: {
top: contentTop + 50 + "px",
left: "0px",
width: "100%",
height: "1px",
}
});
if(optionsObj.showCancel){
popupViewContentList.push({
tag: 'rect',
id: 'line',
rectStyles: {
color: "#f1f1f1",
},
position: {
top: contentTop + 50 + "px",
left: popupViewWidth / 2 + "px",
width: "1px",
height: "50px",
}
});
popupViewContentList.push({
tag: 'font',
id: 'cancelText',
text: optionsObj.cancelText,
textStyles: {
size: '16px',
color: optionsObj.cancelColor,
},
position: {
top: contentTop + 50 + "px",
left: "0px",
width: popupViewWidth / 2 + "px",
height: "50px",
}
});
popupViewContentList.push({
tag: 'font',
id: 'confirmText',
text: optionsObj.confirmText,
textStyles: {
size: '16px',
color: optionsObj.confirmColor,
},
position: {
top: contentTop + 50 + "px",
left: popupViewWidth / 2 + "px",
width: popupViewWidth / 2 + "px",
height: "50px",
}
});
} else {
popupViewContentList.push({
tag: 'font',
id: 'confirmText',
text: optionsObj.confirmText,
textStyles: {
size: '16px',
color: optionsObj.confirmColor,
},
position: {
top: contentTop + 50 + "px",
left: "0px",
width: "100%",
height: "50px",
}
});
}
// 弹窗内容
let popupView = new plus.nativeObj.View("popupView", { //创建底部图标菜单
tag: "rect",
top: (screenHeight - popupViewHeight) / 2 + "px",
left: '10%',
height: popupViewHeight + "px",
width: "80%"
});
// 绘制白色背景
popupView.drawRect({
color: "#FFFFFF",
radius: "8px"
}, {
top: "0px",
height: popupViewHeight + "px",
});
popupView.draw(popupViewContentList);
popupView.addEventListener("click", function(e) {
if(optionsObj.showCancel){
if (e.clientY > popupViewHeight - 50 && e.clientX < popupViewWidth / 2) {
// 取消
maskLayer.close();
popupView.close();
options.success && options.success({confirm: false, cancel: true});
} else if(e.clientY > popupViewHeight - 50 && e.clientX > popupViewWidth / 2){
// 确定
maskLayer.close();
popupView.close();
options.success && options.success({confirm: true, cancel: false});
}
} else {
if (e.clientY > popupViewHeight - 50) {
// 确定
maskLayer.close();
popupView.close();
options.success && options.success({confirm: true, cancel: false});
}
}
});
// 显示弹窗
maskLayer.show();
popupView.show();
options.complete && options.complete();
};
// #endif

111
plugins/wxJsSDK.js Normal file
View File

@@ -0,0 +1,111 @@
// 获取微信公众号SDK权限
//接口请求方法
import $http from '@/config/requestConfig';
import base from '@/config/baseUrl';
import { publicShareFun } from '@/config/html5Utils';
//获取地理位置
export const getLocation = () => {
return new Promise((resolve, reject) => {
//配置校验成功后执行
jWeixin.ready(function () {
// config信息验证后会执行ready方法所有接口调用都必须在config接口获得结果之后config是一个客户端的异步操作所以如果需要在页面加载时就调用相关接口则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口则可以直接调用不需要放在ready函数中。
jWeixin.getLocation({
type: 'gcj02', // 默认为wgs84的gps坐标如果要返回直接给openLocation用的火星坐标可传入'gcj02'
success: function (res) {
console.log(res);
resolve(res);
},
fail: (err) => {
reject(err);
}
});
});
});
}
//设置分享信息
export const setShare = (data, callback) => {
//配置校验成功后执行
jWeixin.ready(function () {
if (!data.link) {
let url = window.location.href;
let index = url.indexOf("?");
if (index != -1) {
if (url.indexOf("#") != -1 && url.indexOf("#") > index) {
url = url.substring(0, index) + url.substring(url.indexOf("#"));
} else {
url = url.substr(0, index);
}
}
data.link = url;
}
// config信息验证后会执行ready方法所有接口调用都必须在config接口获得结果之后config是一个客户端的异步操作所以如果需要在页面加载时就调用相关接口则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口则可以直接调用不需要放在ready函数中。
jWeixin.updateAppMessageShareData({
title: data.title, // 分享标题
desc: data.desc, // 分享描述
link: data.link, // 分享链接该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: data.imgUrl, // 分享图标
success: function () {
// 设置成功
callback && callback();
}
});
jWeixin.updateTimelineShareData({
title: data.title, // 分享标题
link: data.link, // 分享链接该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: data.imgUrl, // 分享图标
success: function () {
// 设置成功
callback && callback();
}
});
});
}
//微信扫一扫
export const scanQRCode = ( callback,needResult = 0) => {
//配置校验成功后执行
jWeixin.ready(function () {
jWeixin.scanQRCode({
needResult: needResult, // 默认为0扫描结果由微信处理1则直接返回扫描结果
scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
callback && callback(res);
}
});
});
}
window.onload = function () {
// 配置文件里面没有publicAppId将不激活微信SDK功能
if (!base.publicAppId) {
return;
}
//获取当前页面地址
let url = window.location.href;
url = url.substring(0, url.indexOf("#"));
//获取微信公众号SDK权限的签名、随机数、时间戳
$http.post("api/open/signature", {
url: url
}).then(res => {
// 微信SDK配置
jWeixin.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来若要查看传入的参数可以在pc端打开参数信息会通过log打出仅在pc端时才会打印。
appId: base.publicAppId, // 必填,公众号的唯一标识
timestamp: res.timestamp, // 必填,生成签名的时间戳
nonceStr: res.noncestr, // 必填,生成签名的随机串
signature: res.signature,// 必填,签名
jsApiList: [
"getLocation",
"updateAppMessageShareData",
"updateTimelineShareData",
'onMenuShareAppMessage', //旧的接口,即将废弃
'onMenuShareTimeline' //旧的接口,即将废弃
] // 必填需要使用的JS接口列表
});
//设置分享内容
publicShareFun();
});
//配置校验失败后执行
jWeixin.error(function (res) {
// config信息验证失败会执行error函数如签名过期导致验证失败具体错误信息可以打开config的debug模式查看也可以在返回的res参数中查看对于SPA可以在这里更新签名。
console.log(res);
});
};