import {buriedPoint,reportBuriedPoint,zhuColor} from './publicAPI.js'; const tools = { timer:'', timerNot:'', // 埋点倒计时 daoTime(){ let daoTime = uni.getStorageSync('daoTime') if(daoTime==''){//初次判断倒计时是否为空 uni.setStorageSync('daoTime',60)//设置倒计时 daoTime = uni.getStorageSync('daoTime') this.timer = setInterval(()=>{ uni.setStorageSync('daoTime',daoTime--)//设置倒计时 // console.log('埋点倒计时初次:',daoTime); // console.log('埋点长度初次:',uni.getStorageSync('maiList').length); if(uni.getStorageSync('daoTime')<=0 || uni.getStorageSync('maiList').length==5){ uni.removeStorageSync('daoTime')//清空倒计时 clearInterval(this.timer)//关闭倒计时 // console.log('上/报,埋点'); // reportBuriedPoint(uni.getStorageSync('maiList'))//上报事件 uni.removeStorageSync('maiList')//清空上报参数 this.daoTime()//重新倒计时 } },1000) } else {//继续当前倒计时倒计 this.timer = setInterval(()=>{ uni.setStorageSync('daoTime',daoTime--)//设置倒计时 // console.log('埋点倒计时:',daoTime); // console.log('埋点长度:',uni.getStorageSync('maiList').length); if(uni.getStorageSync('daoTime')<=0 || uni.getStorageSync('maiList').length==5){ uni.removeStorageSync('daoTime')//清空倒计时 clearInterval(this.timer)//关闭倒计时 // console.log('上报,埋点'); // reportBuriedPoint(uni.getStorageSync('maiList'))//上报事件 uni.removeStorageSync('maiList')//清空上报参数 this.daoTime()//重新倒计时 } },1000) } }, zhuColorT(){//调用主色调 zhuColor() }, networkStatus(){//检查网络状态 uni.getNetworkType({ success: function (res) { console.log('当前网络状态:',res.networkType);//none:当前无网络连接 if(res.networkType=='none'){ uni.setStorageSync('isNet',false) } else { uni.setStorageSync('isNet',true); // 微信小程序原生API性能优化 // #ifdef MP-WEIXIN // 连网下,检测小程序是否有更新 tools.updaX(); // #endif } } }); }, closeTimer(){ clearInterval(this.timer)//关闭倒计时 console.log('倒计时清空了'); clearInterval(this.timerNot)//关闭倒计时 }, buriedPointAll(){//查询埋点类型事件 buriedPoint() }, maiDian(data){//埋点事件 let maiList = uni.getStorageSync('maiList') // console.log(maiList); if(maiList==''){ maiList = [data] } else maiList.push(data) uni.setStorageSync('maiList',maiList) }, weekDate(){//获取未来七天星期几,几号 let date = new Date() let year = date.getFullYear() let month = date.getMonth()+1 let day = date.getDate() let nth = date.getDay()//星期几 // console.log(year,month,day); let xingq = ['周一','周二','周三','周四','周五','周六','周日'] }, // 手机号验证 isPhone:function(phone){ // 手机号正则表达式 let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/; if(!reg_tel.test(phone)){ return true } return false }, // 手机号中间四位用"****"带替 hideMPhone(phone){ return `${phone.substr(0, 3)}****${phone.substr(7)}` }, // 只显示姓,名使用"*"代替 // hideName(name,num){//苹果手机运行不起 // let hname = '' // let reg = /(?<=.)./g; // if(num==1) hname = name.replace(reg, '*') // if(num==2) hname = `${name.substr(0, 1)}****${name.substr(name.length-1)}` // return hname // }, // 昵称从第一个字开始,后面的都用"*"代替 hideName(name,num){ let hname = '' hname = `${name.substr(0, 1)}****${name.substr(name.length-1)}` return hname }, // 金额转换各三位数使用英文","隔开 changeNum(num){ if (num) { // 针对整数部分进行格式化处理,这是此方法的核心,也是稍难理解的一个地方,逆向的来思考或者采用简单的事例来实现就容易多了 /* 也可以这样想象,现在有一串数字字符串在你面前,如果让你给他家千分位的逗号的话,你是怎么来思考和操作的? 字符串长度为0/1/2/3时都不用添加 字符串长度大于3的时候,从右往左数,有三位字符就加一个逗号,然后继续往前数,直到不到往前数少于三位字符为止 */ num = num+''; // 数字转换为字符串,数字是没有.length属性的 for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) { num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3)) } // 将数据(符号、整数部分、小数部分)整体组合返回 return num; } }, // 整数添加.00,小数就不添加 addXiaoShu(num){ let str = num.toString(); if(str.length > 9){ str = str*1; str = str.toFixed(2); str = str+''; } return str.includes('.') ? str*1 : str = num + '.00'; }, // type:+加、-减、*乘、/除 // len:小数后保留几位 operationEv(num1,num2,type,len=0){ // 将数字转化成字符串 num1 = num1.toString(); num2 = num2.toString(); // 获取小数点的位置 var index1 = num1.indexOf("."); var index2 = num2.indexOf("."); // 如果小数点存在,那么就再获取各自的小数位数 var ws1 = 0; var ws2 = 0; if(index1 != -1){ ws1 = num1.split(".")[1].length; } if(index2 != -1){ ws2 = num2.split(".")[1].length; } // 看谁的小数位数大,谁的小数位数小 var bigger = (ws1 > ws2) ? ws1 : ws2; var smaller = (ws1 < ws2) ? ws1 : ws2; // 计算得到需要补齐的0的个数 var zerosCount = bigger - smaller; // 好了,现在不管三七二十,全部去除小数点 num1 = num1.replace(".",""); num2 = num2.replace(".",""); // 比较num1和num2谁大,比较方法就是看谁是smaller,是smaller的一方就补0 if(ws1 == smaller){ for (var i = 0; i < zerosCount; i++) { num1 += "0"; } } else { for (var i = 0; i < zerosCount; i++) { num2 += "0"; } } // 开始计算 var sum = ""; if(type=="+"){ // 加 sum = parseInt(num1) + parseInt(num2); } if(type=="-"){ // 减 sum = parseInt(num1) - parseInt(num2); } if(type=="*"){ // 乘 sum = parseInt(num1) * parseInt(num2); } if(type=="/"){ // 除 sum = parseInt(num1) / parseInt(num2); } // 根据较大的小数位数计算倍数 var beishu = 1; for (var i = 0; i < bigger; i++) { beishu = beishu*10; } sum = sum/beishu; if(type=="*"){ switch (bigger){ case 1: sum = sum / 10; break; case 2: sum = sum / 100; break; case 3: sum = sum / 1000; break; } } if(type=="/"){ switch (bigger){ case 1: sum = sum * 10; break; case 2: sum = sum * 100; break; case 3: sum = sum * 1000; break; } } len!=0 ? sum = sum.toFixed(len) : ''; return sum; }, // 时间戳===>日期 timestampToTime(timestamp) { var date = timestamp.toString().length==13 ? new Date(timestamp*1) : new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000 var Y = date.getFullYear(); var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1); var D = date.getDate() < 10 ? '0'+date.getDate() : date.getDate(); var h = date.getHours() < 10 ? '0'+date.getHours() : date.getHours(); var m = date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes(); var s = date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds(); return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' +s; }, // 日期===>时间戳 timeToTimestamp(time){ var date = new Date(time); var timestamp = date.getTime();//精确到毫秒 return timestamp // var date = new Date('2014-04-23 18:55:49:123'); // 有三种方式获取 // var time1 = date.getTime();//精确到毫秒 // var time2 = date.valueOf();//精确到毫秒 // var time3 = Date.parse(date);//只能精确到秒,毫秒用000替代 // console.log(time1);//1398250549123 // console.log(time2);//1398250549123 // console.log(time3);//1398250549000 }, // 随机数生成 randomStr(){ var strData = ""; //如果觉得12个数太少也可以多放点,将i<4修改即可 for(var i=0;i<4;i++){ var num = random(0,9); //数字 var upper = String.fromCharCode(random(65,90)); //大写字母 var lower = String.fromCharCode(random(97,122)); //小写字母 strData = strData+num+upper+lower; //将所有结果放进strData中 } var str = ""; for (var i = 0; i < 4; i++) { str += strData[random(0,strData.length-1)]; //在strData里面随机抽取四个数 } return str; }, // 金额输入框验证 checkPrice(number,zong){ let reg = /^[0-9]*$/;//数字正则表达式 let newObj = {} zong = parseInt(zong).toString()//取小数点左边的整数 if(!reg.test(number)){//不是数字时 newObj = { len:zong.length,//动态设置长度 val:zong//动态设置值正整数的总金额 } } else {//是数字时 newObj = { len:zong.length, val:number//动态设置当前输入的值 } if(number*1 > zong*1){//输入的金额大于总金额 newObj.val = zong//赋值总金额 } } return newObj }, // 提示方法 showToast: function(msg, icon,time) { // 弹框图标:none默认无图标、loading、success var newIncon = 'none'; if (icon) {newIncon = icon;} // 弹框显示时间:默认2秒 var newTime = 2000 if (time) {newTime = time;} return uni.showToast({ title: msg, icon: newIncon, duration:newTime }) }, formatDuring: function(mss) { // let dangTime = Math.round(new Date()/1000)//获取当前时间戳 var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60)); var seconds = (mss % (1000 * 60)) / 1000; hours = hours < 10 ? ('0' + hours) : hours; minutes = minutes < 10 ? ('0' + minutes) : minutes; seconds = seconds < 10 && seconds >= 1 ? ('0' + seconds) : seconds; return hours + ' : ' + minutes + ' : ' + seconds; }, escape2Html(str) {//富文本 var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' }; return str.replace(/&(lt|gt|nbsp|amp|quot|src);/ig, function (all, t) { return arrEntities[t]; }).replace(' { if (res.confirm) { // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 updateManager.applyUpdate() } } }) }) updateManager.onUpdateFailed(function (res) { // 新版本下载失败 // console.log('新版本下载失败:',res); }) }, clearClog(){//去除某环境下的所有console.log()//输出信息 // uniapp性能优化 // #ifdef APP-PLUS if(uni.getSystemInfoSync().platform != "devtool"){//devtools:开发版 值域为:ios、android、mac(3.1.10+)、windows(3.1.10+)、linux(3.1.10+) console.log = () =>{} } // #endif // 微信小程序原生API性能优化 // #ifdef MP-WEIXIN let hInfo = wx.getAccountInfoSync(); // console.log(hInfo.envVersion);//develop:开发版 trial:体验版 release:正式版 if(hInfo.miniProgram.envVersion == "release"){ console.log = () =>{} } // #endif }, overdue(){//查询过期时间和是否有token,并调用登录事件 var date = new Date(); var timestamp = date.getTime();//精确到毫秒 console.log('进入检测登录',375); if((uni.getStorageSync('expire')*1000) - 60000 < timestamp || uni.getStorageSync('token')==''){ this.loginEv(); } }, loginEv(){//执行登录事件 uni.login({ provider: 'weixin', success: (res)=> { if (res.code) { let code = res.code; let obj = uni.getStorageSync('params'); var params = { invite_code: uni.getStorageSync('is_active')!='' ? uni.getStorageSync('invite_code') : '', code:code, nickname: obj.nickname || '', avatar: obj.avatarUrl || '', country: obj.country || '', province: obj.province || '', city: obj.city || '', gender: obj.gender || '', language:obj.language || '' } uni.request({ url: `${uni.getStorageSync('hostapi')}/api/user/login`, method: 'post', data: params, header: { 'Content-Type': 'application/json; charset=UTF-8', // "content-type": "application/x-www-form-urlencoded;charset=UTF-8", 'Authorization': 'Bearer '+uni.getStorageSync('token') || '' }, success: res => { if(res.data.data.token!=''){ uni.setStorageSync('token',res.data.data.token)//缓存token uni.setStorageSync('openid',res.data.data.openid)//缓存Openid uni.setStorageSync('expire',res.data.data.expire)//缓存失效时间(时间戳格式) uni.setStorageSync('is_active',res.data.data.is_active)//是否第一次授权 uni.setStorageSync('phone_active',res.data.data.phone_active)//是否绑定手机号 uni.setStorageSync('userId',res.data.data.account_id)//用户id uni.setStorageSync('invite_code',res.data.data.invite_code)//邀请码 } } }) } }, }); }, // 文本复制 clickCopy(data){ uni.setClipboardData({ data: data, success: function() { uni.showToast({ title: '复制成功', duration: 2000, icon: 'none' }); } }); }, dayTime(endTime,startTime=''){//开启倒计时 let totalSecond = ''; // 本地倒计时 // if(startTime=='') totalSecond = Math.floor((new Date(endTime).getTime() - new Date().getTime())/1000); // 解决苹果手机问题 let date = endTime; date = endTime.replace(/-/g,'/') // 服务器倒计时 if(startTime!='') totalSecond = Math.floor((new Date(date).getTime() - startTime)/1000); // 总秒数 let second = totalSecond; // 天数 let day = Math.floor(second / 3600 / 24); let dayStr = day.toString(); if(dayStr.length == 1) dayStr = '0' + dayStr; // 小时 let hr = Math.floor((second - day * 3600 * 24) / 3600); let hrStr = hr.toString(); if(hrStr.length == 1) hrStr = '0' + hrStr; // 分钟 let min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60); let minStr = min.toString(); if(minStr.length == 1) minStr = '0' + minStr; // 秒 let sec = second - day * 3600 * 24 - hr * 3600 - min * 60; let secStr = sec.toString(); if(secStr.length == 1) secStr = '0' + secStr; let newTime = ''; if(dayStr==0) { newTime = hrStr +'时'+ minStr +'分'+ secStr +'秒'; } else { newTime = dayStr +'天'+ hrStr +'时'+ minStr +'分'+ secStr +'秒'; } return newTime; }, isVedio(){//是否显示视频内容 uni.request({ url: `${uni.getStorageSync('hostapi')}/api/index/base-config`, method: 'get', header: { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'Bearer '+uni.getStorageSync('token') || '' }, success: res => { if(res.data.code==0){ if(res.data.data.v==0) { uni.setStorageSync('is_vedio',false); } else { uni.setStorageSync('is_vedio',true); } } } }) }, // 清空分享过来的缓存 clearShare(){ uni.removeStorageSync('existCode'); uni.removeStorageSync('transientUrl'); }, // 前往登录页 goLogin(){ uni.navigateTo({ url:'/pages/login/login.vue' }) }, // 获取当前页面url obtainUrl(){ let pages = getCurrentPages(); let route = pages[pages.length - 1].route; console.log(`/${route}`,'tools.js:当前页面路径') return `/${route}`; }, tokenTime:null, // 定时刷新token timedRefreshToken(){ console.log('开启了刷新token事件'); this.loginEv(); clearInterval(this.tokenTime); this.tokenTime = setInterval(()=>{ this.loginEv(); },1000*3200) }, // 清除刷新token clearTokenTime(){ console.log('清除了刷新token事件'); clearInterval(this.tokenTime); } } export default { tools }