123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546 |
- import permision from "@/js_sdk/wa-permission/permission.js"
- import cryptoJs from 'crypto-js'
- let tools = {}
- /**
- * 大小判断
- * @param a
- * @param b
- * @returns {number}
- */
- tools.sortNumber = function (a, b) {
- return a - b;
- }
- /**
- * 保留两位小数
- * @param num
- * @returns {string}
- */
- tools.twoFloating = function (num) {
- // 获取两位小数
- let price = "";
- price = num * 1;
- price = String(price).split(".")[1];
- if (price !== undefined && price.length === 1) {
- price = `.${price}0`;
- } else {
- price === undefined ? (price = ".00") : (price = `.${price}`);
- }
- return price;
- }
- tools.formatDecimal = function (num, decimal) {
- num = num.toString()
- let index = num.indexOf('.')
- if (index !== -1) {
- num = num.substring(0, decimal + index + 1)
- } else {
- num = num.substring(0)
- }
- return parseFloat(num).toFixed(decimal)
- }
- /**
- * 错误提示
- * @param msg
- */
- tools.error = function (msg,icon='error') {
- uni.showToast({
- 'title': msg,
- 'icon': icon,
- 'mask': true,
- 'duration': 1500
- })
- }
- /**
- * 成功提示
- * @param msg
- */
- tools.success = function (msg,icon='success') {
- uni.showToast({
- 'title': msg,
- 'icon': icon,
- 'mask': true,
- 'duration': 1500
- })
- }
- /**
- * 显示Loading
- */
- tools.showLoading = function () {
- uni.showLoading({
- title: '加载中...',
- mask: true
- });
- }
- /**
- * 关闭Loading
- */
- tools.hideLoading = function () {
- uni.hideLoading();
- }
- /**
- * 获取时间戳(毫秒)
- * @returns {number}
- */
- tools.getTime = function () {
- return new Date().getTime();
- }
- tools.getCountDays=function (date){
- let curDate = new Date(date);
- // 获取当前月份
- curDate.setDate(32);
- // 返回当前月份的天数
- return 32-curDate.getDate();
- }
- /**
- * 获取当前年
- * @returns {number}
- */
- tools.getYear=function (){
- return new Date().getFullYear()
- }
- tools.updateVersion = function (sysVersion, appUrl) {
- let app_version = plus.runtime.version;
- console.log('版本号信息对比------------------------------' + app_version + '---------' + sysVersion)
- console.log(app_version < sysVersion)
- if (app_version < sysVersion) {
- uni.showLoading({
- title: '更新中……'
- })
- uni.downloadFile({//执行下载
- url: appUrl, //下载地址
- success: (downloadResult) => {//下载成功
- uni.hideLoading();
- if (downloadResult.statusCode === 200) {
- uni.showModal({
- title: '',
- content: '更新成功,确定现在重启吗?',
- confirmText: '重启',
- confirmColor: '#EE8F57',
- success: function (res) {
- if (res.confirm === true) {
- plus.runtime.install(//安装
- downloadResult.tempFilePath, {
- force: true
- },
- function (res) {
- tools.success('更新成功,重启中')
- plus.runtime.restart();
- }
- );
- }
- }
- });
- }
- }
- });
- } else {
- // tools.success('你已是最新版本')
- }
- }
- /**
- * uniapp html图片显示控制
- * @param str
- * @returns {*}
- */
- tools.imgDeal = function (str) {
- console.log(str)
- if(str===null || str===undefined){
- return '';
- }else {
- return str.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;"');
- }
- }
- /**
- * 获取平台类型 1:微信,2:支付宝
- * @returns {boolean|number}
- */
- tools.platformType = function () {
- let ua = window.navigator.userAgent.toLowerCase();
- if (ua.indexOf('micromessenger') != -1) {
- return 1;
- } else if (ua.indexOf('alipay') != -1) {
- return 2;
- } else {
- return 0;
- }
- }
- /**
- * 手机震动
- */
- tools.vibrate=function (){
- console.log('vibrate')
- // #ifndef H5
- let platform=uni.getSystemInfoSync().platform
- // #ifdef APP-PLUS
- if (platform === "ios") {
- let UIImpactFeedbackGenerator = plus.ios.importClass('UIImpactFeedbackGenerator');
- let impact = new UIImpactFeedbackGenerator();
- impact.prepare();
- impact.init(1);
- impact.impactOccurred();
- }
- if (platform === "android") {
- uni.vibrateShort();
- }
- // #endif
- //#endif
- }
- /**
- * 获取权限
- */
- tools.getAndroidPermission = async function(permissionName) {
- let ret = await permision.requestAndroidPermission(permissionName);
- console.log(ret)
- return ret;
- }
- /**
- * ios权限验证
- * @param permissionName
- * @returns {Promise<any>}
- */
- tools.getIosPermission = async function(permissionName) {
- let ret = await permision.judgeIosPermission(permissionName);
- console.log(ret)
- return ret;
- }
- /**
- * 获取开发平台
- * @returns {string}
- */
- tools.getPlatform = function () {
- let platForm = undefined;
- // #ifdef H5
- platForm = 'H5';
- //#endif
- // #ifdef APP-PLUS
- platForm = 'APP';
- //#endif
- // #ifdef APP-PLUS-NVUE
- platForm = 'APP';
- //#endif
- // #ifdef APP-NVUE
- platForm = 'APP';
- //#endif
- // #ifdef MP-WEIXIN
- platForm = 'MP-WEIXIN'; // 小程序
- //#endif
- // #ifdef MP-ALIPAY
- platForm = 'MP-ALIPAY';
- //#endif
- // #ifdef MP-BAIDU
- platForm = 'MP-BAIDU';
- //#endif
- // #ifdef MP-TOUTIAO
- platForm = 'MP-TOUTIAO';
- //#endif
- // #ifdef MP-LARK
- platForm = 'MP-LARK';
- //#endif
- // #ifdef MP-QQ
- platForm = 'MP-QQ';
- //#endif
- // #ifdef MP-KUAISHOU
- platForm = 'MP-KUAISHOU';
- //#endif
- // #ifdef QUICKAPP-WEBVIEW
- platForm = 'QUICKAPP-WEBVIEW';
- //#endif
- return platForm;
- }
- tools.leftClick = function () {
- let pages = getCurrentPages();
- if (pages.length > 1) {
- uni.navigateBack({
- delta: 1
- })
- } else {
- uni.reLaunch({
- url: '/pages/index/index'
- });
- }
- }
- tools.getDate = function (date) {
- let myDate = new Date();
- // let myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
- // let myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
- // let myToday = myDate.getDate(); //获取当前日(1-31)
- // let myDay = myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
- // let myHour = myDate.getHours(); //获取当前小时数(0-23)
- // let myMinute = myDate.getMinutes(); //获取当前分钟数(0-59)
- // let mySecond = myDate.getSeconds(); //获取当前秒数(0-59)
- return myDate.getFullYear() + '-' + (myDate.getMonth() + 1) + '-' + myDate.getDate()
- }
- tools.getDateArr = function (date) {
- let myDate = new Date(date);
- let myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
- let myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
- let myToday = myDate.getDate(); //获取当前日(1-31)
- return [myYear, myMonth>9?myMonth:'0'+myMonth , myToday>9?myToday:'0'+myToday]
- }
- tools.getRandFileName = function (filePath)
- {
- let extIndex = filePath.lastIndexOf('.');
- let extName = extIndex === -1 ? '' : filePath.substr(extIndex);
- return parseInt('' + Date.now() + Math.floor(Math.random() * 900 + 100), 10).toString(36) + extName;
- }
- /**
- * 自定义 获取指定日期到当前日期的 所有年 or 年月
- */
- tools.getCustomTimeList = (start,end,type)=>{
- let timeList = [];
- let s = start.split("-");
- let e = end.split("-");
- let min = new Date()
- let max = new Date()
- min.setFullYear(s[0], s[1]);
- max.setFullYear(e[0], e[1]);
- var curr = min;
- var str = "";
- while (curr <= max) {
- var yers = curr.getFullYear();
- var month = curr.getMonth();
- if(type === 'y-m'){
- if (month === 0) {
- str = (yers - 1) + "-" + 12;
- } else {
- str = yers + "-" + (month < 10 ? ("0" + month) : month);
- }
- timeList.push(str);
- curr.setMonth(month + 1);
- }else if(type === 'y'){
- if (month === 0) {
- str = (yers - 1)
- } else {
- str = yers
- }
- timeList.push(str);
- curr.setMonth(month + 1);
- }else{}
- }
- if(type === 'y-m'){
- return timeList.reverse()
- }else{
- let list = Array.from(new Set(timeList))
- return list.reverse()
- }
- }
- // 获取 当前 年-月 配合 getCustomTimeList 使用 获取end
- tools.getDateYM = ()=>{
- let DATE = new Date()
- let Y = DATE.getFullYear()
- let M = DATE.getMonth() + 1
- return Y + '-' + (M<10?'0'+M:M)
- }
- /**
- * 记录用户登录信息
- * @param data
- * @param type
- */
- tools.setLoginData = function (data) {
- uni.setStorageSync('user_id', data.user_id)
- uni.setStorageSync('token', data.access_token)
- uni.setStorageSync('tokenType', data.token_type)
- uni.setStorageSync('refreshToken', data.access_token)
- uni.setStorageSync('mobile', data.username)
- uni.setStorageSync('userId', data.user_id)
- tools.success('登陆成功')
- // setTimeout(() => {
- // if (data.status * 1 === 0) {
- // //审核状态跳转至待审核页面
- // uni.reLaunch({
- // url: '/pages/login/module/await-audit'
- // });
- // } else {
- // uni.reLaunch({
- // url: '/pages/index/home'
- // });
- // }
- // }, 1500)
- }
- tools.addQueryString=function (params) {
- let str = '';
- for (let Key in params) {
- str += Key + '=' + params[Key] + '&';
- }
- return '?' + str;
- //return '?' + str.substr(0, str.length -1); 严谨一些
- }
- tools.setCosToken=function (data){
- uni.setStorageSync('cosToken',data)
- }
- tools.delCosToken=function (data){
- uni.removeStorageSync('cosToken')
- }
- /**
- * 定位经纬度
- * @returns {Promise<unknown>}
- */
- tools.getLocation=async function (){
- return new Promise((resolve, reject)=>{
- //#ifdef APP-PLUS
- let locationData= uni.getStorageSync('locationData')
- console.log('locationData:',locationData)
- if(locationData){
- resolve(locationData);
- }else {
- console.log('执行获取')
- uni.getLocation({
- type: 'gcj02',
- success:async function (res) {
- console.log('当前位置的经度:' + res.longitude);
- console.log('当前位置的纬度:' + res.latitude);
- resolve({'longitude':res.longitude,'latitude':res.latitude});
- },
- fail:async function (e) {
- console.log(e)
- resolve( {'longitude':"121.631691",'latitude':'38.922691'});
- }
- });
- }
- //#endif
- //#ifdef H5
- resolve( {'longitude':"121.631691",'latitude':'38.922691'});
- //#endif
- })
- }
- /**
- * 计算距离
- * @returns {Promise<void>}
- */
- tools.getDistance=async function (lat1, lng1){
- let locationData=await tools.getLocation()
- let lat2=locationData.latitude
- let lng2=locationData.longitude
- let radLat1 = lat1*Math.PI / 180.0;
- let radLat2 = lat2*Math.PI / 180.0;
- let a = radLat1 - radLat2;
- let b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
- let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
- s = s *6378.137 ;// EARTH_RADIUS;
- s = Math.round(s * 10000) / 10000;
- return s;
- }
- /**
- * 查看大图
- * @param list
- * @param index
- */
- tools.lookBigImg = function (list, index) {
- uni.previewImage({
- current: index,//当前所点击预览的图片地址
- urls: list,//这就是当前行图片数据,注意一定要是数组格式
- indicator: 'number',
- loop: true
- });
- }
- /**
- * 计算年龄
- * @param birthYearMonthDay
- * @returns {number}
- */
- tools.getAge=function (birthYearMonthDay) {
- birthYearMonthDay=birthYearMonthDay.replace('-','/')
- //birthYearMonthDay必须为"1995/6/15"这种字符串格式,不可为"2020-6-15",这种格式在Safari中会报错
- const birthDate = new Date(birthYearMonthDay);
- const momentDate = new Date();
- momentDate.setHours(0, 0, 0, 0); //因为new Date()出来的时间是当前的时分秒。我们需要把时分秒重置为0。使后面时间比较更精确
- const thisYearBirthDate = new Date(
- momentDate.getFullYear(),
- birthDate.getMonth(),
- birthDate.getDate()
- );
- const aDate = thisYearBirthDate - birthDate;
- const bDate = momentDate - birthDate;
- let tempAge = momentDate.getFullYear() - birthDate.getFullYear();
- let age = null;
- if (bDate < aDate) {
- tempAge = tempAge - 1;
- age = tempAge < 0 ? 0 : tempAge;
- } else {
- age = tempAge;
- }
- return age;
- }
- /**
- * 获取costoken
- * @returns {{expiredTime}|any|undefined}
- */
- tools.getCosToken=function (){
- let cosToken= uni.getStorageSync('cosToken')
- if(!cosToken){
- return undefined
- }
- let time=new Date().getTime()
- if(cosToken.expiredTime && (cosToken.expiredTime*1000)-time >100000){
- return cosToken
- }else {
- return undefined
- }
- }
- /**
- * 封装文件结构
- * @param url
- * @param type
- * @returns {{serverSideEncryption: string, location, type: (string), version: string, hash: string}}
- */
- tools.setFileObj=function (url,type){
- url= url.replace('https://','')
- url= url.replace('http://','')
- url= url.replace('icoco-1317650740.cos.ap-guangzhou.myqcloud.com/','')
- let hash=tools.setHash(url)
- console.log('hash')
- return {
- "location":url,
- "hash":hash,
- "version":"1.0",
- "type":type===1?"PHOTO":"V",
- "serverSideEncryption":"AES256"
- }
- }
- tools.setHash=function (str){
- let sha256 = cryptoJs.SHA256(str);
- return sha256.toString();
- }
- export default tools
|