let carmera = uni.requireNativePlugin('ziteng-maskcamera') let cameraModule = uni.requireNativePlugin("SMUniPlugin-CameraModule") // 处理数字千位分隔符 num 数值,decimal要保留的小数位数 export const toThousands = (num, decimal) => { if (decimal) { num = formatDecimal(num, decimal) } return num.toString().replace(/\d+/, function (n) { // 先提取整数部分 return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) { return $1 + ',' }) }) } // 保留decimal位小数(不四舍五入) num 数值,decimal要保留的小数位数 export const formatDecimal = function (num, decimal) { num = num.toString() const index = num.indexOf('.') if (index !== -1) { num = num.substring(0, decimal + index + 1) } else { num = num.substring(0) } return parseFloat(num).toFixed(decimal) } export function objToUrl(obj) { let uri = ''; let keys = Object.keys(obj); keys.forEach(item => { uri += '&' + item + '=' + obj[item]; }); uri = uri.substr(1); return uri; } // 获取地址栏参数 export function getQueryString(url, name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)") var r = url.substr(1).match(reg) if(r!=null) return unescape(r[2]) return null } // 节流函数 export function throttle(fn, gaptime) { if (gaptime == null || gaptime == undefined) { gaptime = 200 } let _lastTime = null return function() { let _nowTime = +new Date() if (_nowTime - _lastTime > gaptime || !_lastTime) { fn.apply(this, arguments) _lastTime = _nowTime } } } // 图片转Base64,pad 平台 export const imgToBase64 = function (path,callback){ // plus.nativeUI.previewImage([path]); // return plus.io.resolveLocalFileSystemURL(path, function (entry) { // 可通过entry对象操作文件 entry.file(function (file){ var fileReader = new plus.io.FileReader() fileReader.readAsDataURL(file, 'utf-8') fileReader.onloadend = function (evt) { let result = evt.target.result callback(1,result.split(',')[1]) // remove this file entry.remove( function ( entry ) { console.log( "Remove succeeded" ); }, function ( e ) { console.log( e.message ); }); } fileReader.onerror = function (e){ callback(0,'文件读取失败') } }) }, function (e) { console.log(JSON.stringify(e)) uni.showToast({icon: 'none',title: 'Resolve file URL failed: ' + e.message}) }) } // 打开摄像头 export const openCamera = function (type,callback){ let carNumberOptions = { widthRatio: 0.8, heightRatio: 0.2, showText: '请将车牌号码对准框中' } let carVinNumberOptions = { widthRatio: 0.9, heightRatio: 0.1, showText: '请将车辆VIN码对准框中' } let option = (type == 'searchCar' || type == 'carNumber') ? carNumberOptions : carVinNumberOptions // 竖屏 false,横屏 true let isLandscape = false //安卓摄像头 if(uni.getSystemInfoSync().platform === 'android'){ option.isLandscape = isLandscape carmera.show(option,function(result){ console.log(result) if(result.msg != 'backCancel'){ callback(result.data) } }) } // ios 摄像头 if(uni.getSystemInfoSync().platform == 'ios'){ let screenWidth = uni.getSystemInfoSync().screenWidth let screenHeight = uni.getSystemInfoSync().screenHeight let [w,h,x,y] = [0,0,0,0] // 横屏 if(isLandscape){ h = screenWidth*option.widthRatio*1.2 w = screenHeight*option.heightRatio x = (screenWidth - w)/2 y = (screenHeight - h)/2 }else{ // 竖屏 w = screenWidth*option.widthRatio h = screenHeight*option.heightRatio x = (screenWidth - w)/2 y = (screenHeight - h)/2 - 50 } cameraModule.showCamera({ 'showTitle': option.showText, 'size': [w, h], 'orign': [x, y], 'isLandscape': isLandscape }, (result) => { callback('file://'+result) }) } } /** * @param {*} obj1 对象 * @param {*} obj2 对象 * @description 遍历赋值 */ export const objExtend = (obj1, obj2) => { for (let a in obj1){ obj2[a] = obj1[a] } return obj2 } // 正则验证车牌,验证通过返回true,不通过返回false export const isLicensePlate = function (str) { return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(str) } /** * 校验身份证号合法性 */ export const checkIdNumberValid = (tex) => { // var tip = '输入的身份证号有误,请检查后重新输入!' let num = tex num = num.toUpperCase() let len = num.length let re if (len == 0) return true // 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X。 if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))){ return false } // 验证前两位地区是否有效 let aCity = {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: '国外'} if (aCity[parseInt(num.substr(0, 2))] == null){ return false } // 当身份证为15位时的验证出生日期。 if (len == 15){ re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/) let arrSplit = num.match(re) // 检查生日日期是否正确 let dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]) let bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4])) if (!bGoodDay){ return false } } // 当身份证号为18位时,校验出生日期和校验位。 if (len == 18){ re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/) let arrSplit = num.match(re) // 检查生日日期是否正确 let dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]) let bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4])) if (!bGoodDay){ return false } else { // 检验18位身份证的校验码是否正确。 // 校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。 let valnum let arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] let arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'] let nTemp = 0 let i for (i = 0; i < 17; i++){ nTemp += num.substr(i, 1) * arrInt[i] } valnum = arrCh[nTemp % 11] if (valnum != num.substr(17, 1)){ return false } } } return true } // 正则有效手机号码 export const isvalidPhone = function (str) { const reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/ return reg.test(str) } // 日期格式化 export const formatSubmitDate = (val, type) => { if (val == null || val == '' || val == undefined) { return '' } else { let _date = new Date(val) let _year = _date.getFullYear() let _montn = (_date.getMonth() + 1) < 10 ? '0' + (_date.getMonth() + 1) : (_date.getMonth() + 1) let _day = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate() let _hour = _date.getHours() < 10 ? '0' + _date.getHours() : _date.getHours() let _minutes = _date.getMinutes() < 10 ? '0' + _date.getMinutes() : _date.getMinutes() let _seconds = _date.getSeconds() < 10 ? '0' + _date.getSeconds() : _date.getSeconds() if (type == 'minutes') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes else if (type == 'seconds') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes + ':' + _seconds else return _year + '-' + _montn + '-' + _day } } /** * //设置应用版本号对应的缓存信息 * @param {Object} currTimeStamp 当前获取的时间戳 */ export const setStorageForAppVersion = function(currTimeStamp){ uni.setStorage({ key: 'tip_version_update_time', data: currTimeStamp, success: function () { console.log('setStorage-success'); } }); } /** * 进行版本型号的比对 以及下载更新请求 * @param {Object} server_version 服务器最新 应用版本号 * @param {Object} curr_version 当前应用版本号 * isQzgx 是否强制更新 * callback 登录 */ export const checkVersionToLoadUpdate = function(newVersion,type,callback){ if(newVersion.version == '2001'||newVersion.version == '2002'){ newVersion.version = 201 } const curVer = getApp().globalData.version // 当前版本信息 console.log(newVersion,curVer,callback) if(!newVersion || !curVer){ callback() return } const curr_version = curVer && curVer.version ? curVer.version.replace(/\./g,'') : '' const server_version = newVersion && newVersion.version ? newVersion.version : '' // 最新版本信息 const isQzgx = newVersion && newVersion.forceUpgrade != 1 let isWifi = plus.networkinfo.getCurrentType()!=3 ? '有新的版本发布,检测到您目前非Wifi连接,' : '有新的版本发布,' let msg = isWifi + (!isQzgx ? '请立即更新?' : '是否立即更新版本?') // 下载app并安装 let downloadApp = function(downloadApkUrl){ uni.showLoading({ title: '正在更新中...', mask: true, }); var dtask = plus.downloader.createDownload( downloadApkUrl, {}, function ( d, status ) { // 下载完成 if ( status == 200 ) { plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename),{},{},function(error){ uni.showToast({ icon: 'none', title: '安装失败', duration: 1500 }); }) uni.hideLoading() } else { uni.showToast({ icon: 'none', title: '更新失败', duration: 1500 }); } }); dtask.start(); } // 打开ios 应用市场 let openIosAppSotre = function(downloadUrl){ //在App Store Connect中的App Store下的app信息,可找到appleId plus.runtime.launchApplication({ action: downloadUrl }, function(e) { console.log('Open system default browser failed: ' + e.message); }) } console.log(server_version,curr_version) if(Number(server_version) > Number(curr_version)){ uni.showModal({ title: msg, content: '更新内容:'+newVersion.upgradeContent, showCancel: isQzgx, confirmText:'立即更新', cancelText:'稍后进行', success: function (res) { if (res.confirm) { // 清空缓存token let tmp = uni.getStorageSync('lifeData'); tmp = tmp ? tmp : {}; tmp['vuex_token'] = ''; uni.setStorageSync('lifeData', tmp); if(curVer.platform == 'android'){ //设置 最新版本apk的下载链接 downloadApp(newVersion.attachment); }else{ openIosAppSotre(newVersion.downloadUrl) } } else if (res.cancel) { console.log('稍后更新'); callback() } } }); uni.hideLoading(); }else{ if(type){ uni.showToast({ icon: 'none', title: '已是最新版本', duration: 1500 }); }else{ callback() } } } // 确认弹框 export const clzConfirm = function(opts){ // #ifndef APP-PLUS uni.showModal({ title: opts.title, content: opts.content, showCancel: opts.showCancel, confirmText: opts.confirmText || '确定', cancelText: opts.cancelText || '取消', success: opts.success, }) // #endif // #ifdef APP-PLUS if(opts.showCancel==false){ if(!opts.buttons){ opts.buttons = ["确定"] } } plus.nativeUI.confirm( opts.content, opts.success, {"title":opts.title,"buttons": opts.buttons || ["确定","取消"]}, ) // #endif } // 小数点后两位 export const numberToFixed = function (val, num, max) { let maxNums = max || 100000000 let _value = val + '' _value = _value.replace(/[^\d.]/g, '')// 清楚数字和.以外的字数 _value = _value.replace(/^\./g, '') _value = _value.replace(/\.{2,}/g, '')// 保留第一个,清楚多余的 if (num == 1)_value = _value.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3') else if (num == 3)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d).*$/, '$1$2.$3') else if (num == 4)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3') else if (num == 5)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d\d\d).*$/, '$1$2.$3') else if (num == 0)_value = _value.indexOf('.') >= 0 ? _value.split('.')[0] : _value else _value = _value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // console.log(_value,maxNums,Number(_value)>Number(maxNums),'_value') return Number(_value)>Number(maxNums) ? maxNums : _value } // 保存图片到阿里云 export const saveImgToAliOss = function(src,callback){ console.log(src,getApp().globalData.baseUrl,'getApp().globalData.baseUrl') const authorization = getApp().globalData.token uni.uploadFile({ url: getApp().globalData.baseUrl + 'upload/', //自行修改各自的对应的接口 filePath: src, name: 'file', header: {'X-AUTH-TOKEN':authorization}, success: (uploadFileRes) => { if (uploadFileRes) { let res = JSON.parse(uploadFileRes.data); callback(res) } uni.showToast({ icon: 'none', title: uploadFileRes ? '保存图片成功' : '保存图片失败' }) }, fail:(error) => { console.log(error) } }); } // 点击消息打开对应的页面 export const openMessagePage = function(data){ // 急送订单 if (data.extras.bizType == 'TEMP_ORDER') { uni.navigateTo({ url: '/pages/sales/edit?pageType=detail&data='+JSON.stringify({ salesBillSn: data.extras.bizSn }) }) } // 补货订单 if (data.extras.bizType == 'SHELF_REPLENISH') { uni.navigateTo({ url: '/pages/replenishmentManage/replenishmentList?billState=WAIT_CONFIRM' }) } // 货架订单 if (data.extras.bizType == 'SHELF_ORDER') { uni.navigateTo({ url: '/pages/shelfOrder/orderDetail?pageType=detail&orderBillSn='+data.extras.bizSn }) } // 货架异常 if (data.extras.bizType == 'SHELF_WARN') { const shelfName = data.content.split('已经超过')[0] uni.navigateTo({ url: '/pages/shelfOrder/shelfOrder?bizType=SHELF_WARN&shelfSn='+data.extras.bizSn+'&shelfName='+shelfName }) } }