module.exports = {
// 判断是 IOS 还是安卓
getPhoneType() {
var type = 'other'
switch (uni.getSystemInfoSync().platform) {
case 'android':
type = 'android'
break;
case 'ios':
type = 'ios'
break;
default:
break;
}
return type
},
// 处理手机号码中间四位
phoneNumHide(phone) {
var reg = /^(\d{3})\d{4}(\d{4})$/;
phone = phone.replace(reg, "$1****$2");
return phone
},
// 处理文件路径
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
},
// 图片转 base64ToPath
pathToBase64(path) {
let that = this
return new Promise((resolve, reject) => {
if (typeof window === 'object' && 'document' in window) {
if (typeof FileReader === 'function') {
var xhr = new XMLHttpRequest()
xhr.open('GET', path, true)
xhr.responseType = 'blob'
xhr.onload = () => {
if (this.status === 200) {
let fileReader = new FileReader()
fileReader.onload = (e) => {
resolve(e.target.result)
}
fileReader.onerror = reject
fileReader.readAsDataURL(this.response)
}
}
xhr.onerror = reject
xhr.send()
return
}
var canvas = document.createElement('canvas')
var c2x = canvas.getContext('2d')
var img = new Image
img.onload = () => {
canvas.width = img.width
canvas.height = img.height
c2x.drawImage(img, 0, 0)
resolve(canvas.toDataURL())
canvas.height = canvas.width = 0
}
img.onerror = reject
img.src = path
return
}
if (typeof plus === 'object') {
plus.io.resolveLocalFileSystemURL(that.getLocalFilePath(path), (entry) => {
entry.file((file) => {
var fileReader = new plus.io.FileReader()
fileReader.onload = (data) => {
resolve(data.target.result)
}
fileReader.onerror = (error) => {
reject(error)
}
fileReader.readAsDataURL(file)
}, (error) => {
reject(error)
})
}, (error) => {
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
wx.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success(res) {
resolve('data:image/png;base64,' + res.data)
},
fail(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
},
// base 64 转文件路径
base64ToPath(base64) {
return new Promise((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, () => {
var filePath = '_doc/uniapp_temp/' + fileName
bitmap.save(filePath, {}, () => {
bitmap.clear()
resolve(filePath)
}, (error) => {
bitmap.clear()
reject(error)
})
}, (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() {
resolve(filePath)
},
fail(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
},
// 打开第三方地图应用
toMapAPP(latitude, longitude, name) {
let url = "";
if (plus.os.name == "Android") { // 判断是安卓端
plus.nativeUI.actionSheet({ // 选择菜单
title: "选择地图应用",
cancel: "取消",
buttons: [{
title: "腾讯地图"
}, {
title: "百度地图"
}, {
title: "高德地图"
}]
}, (e) => {
switch (e.index) {
// 下面是拼接 url,不同系统以及不同地图都有不同的拼接字段
case 1:
// 注意 referer=xxx 的 xxx 替换成你在腾讯地图开发平台申请的 key
url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=7ZDBZ-POOWJ-3PRFG-KCBCD-WAH5K-AVFVL`;
break;
case 2:
url =
`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
break;
case 3:
url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
break;
default:
break;
}
if (url != "") {
url = encodeURI(url);
// plus.runtime.openURL(url, (e) => {}) // 调起手机APP应用
plus.runtime.openURL(url, (e) => {
plus.nativeUI.alert("本机未安装指定的地图应用");
});
}
})
} else {
// iOS上获取本机是否安装了百度高德地图,需要在 manifest 里配置
// 在 manifest.json 文件 app-plus -> distribute -> apple -> urlschemewhitelist 点下添加
// (如urlschemewhitelist:["iosamap","baidumap","qqmap"])
plus.nativeUI.actionSheet({
title: "选择地图应用",
cancel: "取消",
buttons: [{
title: "腾讯地图"
}, {
title: "百度地图"
}, {
title: "高德地图"
}]
}, (e) => {
switch (e.index) {
case 1:
url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=xxx`;
break;
case 2:
url =
`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
break;
case 3:
url =
`iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
break;
default:
break;
}
if (url != "") {
url = encodeURI(url);
plus.runtime.openURL(url, (e) => {
plus.nativeUI.alert("本机未安装指定的地图应用");
});
}
})
}
},
// 获取页面路径
getCurPage() {
var pages = getCurrentPages();
var page = pages[pages.length - 1]
return 'https://czjxmx.com/h5/#' + page.route
},
// 短震动
vibrate() {
let UIImpactFeedbackGenerator = plus.ios.importClass('UIImpactFeedbackGenerator');
let impact = new UIImpactFeedbackGenerator();
impact.prepare();
impact.init(1);
impact.impactOccurred();
},
// 获取用户cid
getUserCid() {
let clientInfo = plus.push.getClientInfo()
return clientInfo.clientid // 设备CID
},
// 数组内是否包含
inArray(search, array) {
for (var i in array) {
if (array[i] == search) {
return true;
}
}
return false;
},
// 公众号登录鉴权--静默授权
gzhLoginBase(url, type) {
// type : snsapi_base 静默授权 snsapi_userinfo 获取用户信息
let local = encodeURIComponent(url) // 获取当前页面地址
let Appid = '你的APPID'
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
Appid + // 你APP申请的APPId,每个app都有个ID是识别你app的方式
"&redirect_uri=" +
local +
"&response_type=code&scope=" + type + "&state=1#wechat_redirect";
},
// 判断是否是微信浏览器
is_wx() {
let en = window.navigator.userAgent.toLowerCase()
// 匹配en中是否含有 MicroMessenger 字符串
if (en.match(/MicroMessenger/i) == 'micromessenger') {
return true
}
if (en.match(/MicroMessenger/i) != 'micromessenger') {
return false
}
},
// 随机整数
random(lower, upper) {
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
},
// 监听网络
onNetWork() {
let func = (res) => {
if (res.networkType === 'none') {
uni.showToast({
title: '网络异常,请先连接',
icon: 'none',
duration: 3000
});
}
}
uni.getNetworkType({
success: func
});
uni.onNetworkStatusChange(func);
},
// 数组置顶
toFirst(arr, index) {
if (index != 0) {
arr.unshift(arr.splice(index, 1)[0]);
}
return arr;
},
// 判断地址是否包含前缀
httpLink(url) {
const Http = url.substr(0, 7).toLowerCase()
const Https = url.substr(0, 8).toLowerCase()
if (Http === "http://" || Https === "https://") {
return true
}
return false
},
// 获取当前页面路由---包含参数
getNowPagePath() {
let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
if (routes.length == 0) {
return '/index/index'
}
let curRoute = routes[routes.length - 1].route // 获取当前页面路由
let curParam = routes[routes.length - 1].options; // 获取路由参数
// 拼接参数
let param = ''
for (let key in curParam) {
if (key != 'code') {
if (param == '') {
param += '?' + key + '=' + curParam[key]
} else {
param += '&' + key + '=' + curParam[key]
}
}
}
let page_url = '/' + curRoute + param
return page_url
},
// 获取字符长度 中文2个字符,英文一个字符
strlen(str) {
var len = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
// 单字节加1
if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
len++
} else {
len += 2
}
}
return len
},
// 字符空格过滤
trim(str) {
return str.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '');
},
// 数字转中文
toChinesNum(num) {
let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
let unit = ["", "十", "百", "千", "万"];
num = parseInt(num);
let getWan = (temp) => {
let strArr = temp.toString().split("").reverse();
let newNum = "";
for (var i = 0; i < strArr.length; i++) {
newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
}
return newNum;
}
let overWan = Math.floor(num / 10000);
let noWan = num % 10000;
if (noWan.toString().length < 4) {
noWan = "0" + noWan;
}
return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}
}