const validate = require("./validate.js"); import __config from '@/config/env'; import api from '@/utils/api.js'; import Decimal from 'decimal.js'; const formatTime = date => { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hour = date.getHours(); const minute = date.getMinutes(); const second = date.getSeconds(); return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join( ':'); }; const formatNumber = n => { n = n.toString(); return n[1] ? n : '0' + n; }; //空值过滤器 const filterForm = form => { let obj = {}; Object.keys(form).forEach(ele => { if (!validate.validatenull(form[ele])) { obj[ele] = form[ele]; } }); return obj; }; //获取当前页面带参数的url const getCurrentPageUrlWithArgs = val => { const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; const url = currentPage.route; const options = currentPage.options; let urlWithArgs = `/${url}?`; for (let key in options) { const value = options[key]; urlWithArgs += `${key}=${value}&`; } urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1); return urlWithArgs; } /* 获取当前页面options参数对象 */ const getCurrentPageOptions = () => { const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; const url = currentPage.route; const options = currentPage.options; return options } //获取url中的参数 const getUrlParam = (path, name) => { var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i"); if (reg.test(path)) return unescape(RegExp.$2.replace(/\+/g, " ")); return ""; } //判断是否为微信浏览器中运行 const isWeiXinBrowser = () => { // #ifdef H5 // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息,这个属性可以用来判断浏览器类型 let ua = window.navigator.userAgent.toLowerCase() // 通过正则表达式匹配ua中是否含有MicroMessenger字符串 if (ua.match(/MicroMessenger/i) == 'micromessenger') { return true } else { return false } // #endif return false } //判断是否是小程序 const isMiniPg = () => { let isMiniPg = false //#ifdef MP-WEIXIN isMiniPg = true //#endif return isMiniPg } //获取客服端代码 const getClientCode = () => { let code = {} //#ifdef MP-WEIXIN code = { key: 'MP-WEIXIN', value: '微信小程序' } //#endif //#ifdef H5 //普通H5 code = { key: 'H5', value: '普通H5' } if (isWeiXinBrowser()) { //微信公众号H5 code = { key: 'H5-WX', value: '公众号H5' } } //#endif return code } //重置url中的参数 const resetPageUrl = (query) => { var ary = []; for (var p in query) { if (query.hasOwnProperty(p) && query[p]) { ary.push(encodeURIComponent(p) + '=' + encodeURIComponent(query[p])); } } if (ary.length > 0) { let url = "?" + ary.join('&'); history.replaceState(history.state, null, url); //替换页面显示url } } const imgUrlToBase64 = (imageUrl) => { return new Promise((resolve, reject) => { try { uni.downloadFile({ url: imageUrl + '?s=' + Math.random().toString(), success: res => { if (res.statusCode === 200) { // uni 如果是H5或者APP会自动转为base64返回 resolve(res.tempFilePath); } else { reject(res.errMsg); } }, fail(err) { reject(err); } }); } catch (e) { console.log(e) resolve(imageUrl); } }) } // 设置原生app的分享url为h5的地址url const setAppPlusShareUrl = query => { const pages = getCurrentPages(); const curPage = pages[pages.length - 1]; const userInfo = uni.getStorageSync('wx_login_user_info') const userCode = userInfo ? userInfo.userCode : '' let component_appid = "" if (query && query.componentAppId) { component_appid = "&component_appid=" + query.componentAppId } let fullPath = curPage.$page.fullPath //判断是否有问号 fullPath = fullPath.indexOf('?') != -1 ? fullPath + '&' : fullPath + '?' if (userCode) { return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId + '&sharer_user_code=' + userCode + component_appid; } else { return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId + component_appid } }; // 设置原生app的分享url为h5的地址url(用于分销,默认首页地址) const setAppPlusHomeShareUrl = query => { const userInfo = uni.getStorageSync('wx_login_user_info') const userCode = userInfo ? userInfo.userCode : '' let component_appid = "" if (query && query.componentAppId) { component_appid = "&component_appid=" + query.componentAppId } let fullPath = '/mp/views/home/index?' if (userCode) { return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId + '&sharer_user_code=' + userCode + component_appid; } else { return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId + component_appid } }; // 设置h5的分享地址url const setH5ShareUrl = val => { const userInfo = uni.getStorageSync('wx_login_user_info') const userCode = userInfo ? userInfo.userCode : '' let url = window.location.href // 如果没有 sharer_user_code 就添加,如果有就替换为自己的userCode if (userCode) { let index = url.indexOf('&sharer_user_code=') if (index == -1) { url = url + '&sharer_user_code=' + userCode; } else { let urlTemp = url.slice(0, index); url = urlTemp + '&sharer_user_code=' + userCode; } } return url } // 设置H5的分享url(用于分销,默认首页地址) const setH5HomeShareUrl = val => { const userInfo = uni.getStorageSync('wx_login_user_info') const userCode = userInfo ? userInfo.userCode : '' // 如果没有 sharer_user_code 就添加 let url = window.location.origin + window.location.search; if (userCode) { let index = url.indexOf('&sharer_user_code=') if (index == -1) { url = url + '&sharer_user_code=' + userCode; } else { let urlTemp = url.slice(0, index); url = urlTemp + '&sharer_user_code=' + userCode; } } return url } // 获取当前页面路由或 path const getCurPage = pages => { let curPage = pages[pages.length - 1]; return curPage.route } // 保存别人分享来的 userCode const saveSharerUserCode = options => { if (options.scene) { //接受二维码中参数 /** * 这里需要特别注意: * 由于腾讯限制了scenes的长度,导致传参的局限性,为尽可能的利用这有限的长度传参, * 故我们定义了scenes的参数格式,当一个页面需要传多个参数时,我们用“&”符号分割开来,第2位固定放分享人的user_code,这样可以最大限度减少长度占用 * 第1位一般放ID,第2位固定放分享人的user_code,比如菜品页面scenes为:goodspuId+&+sharer_user_code * 因为固定第2位放分享人的user_code,当有些页面无需传ID时,我们也需要用“&”拼一下,第一位随意用一个字符点位即可,比如页面scenes为:0+&+sharer_user_code */ let scenes = decodeURIComponent(options.scene).split('&'); if (scenes[1]) { uni.setStorageSync('sharer_user_code', scenes[1]); } } else { if (options.sharer_user_code) { uni.setStorageSync('sharer_user_code', ''); uni.setStorageSync('sharer_user_code', options.sharer_user_code); } } } // 如果有分享人则给data带上分享人的user_code const dataAddSharerUserCode = data => { let sharer_user_code = uni.getStorageSync('sharer_user_code') if (sharer_user_code) { data = Object.assign({ sharerUserCode: sharer_user_code }, data) } return data } //返回登录页面 const backLoginPage = data => { var pages = getCurrentPages(); // 获取页面栈 var currPage = pages[pages.length - 1]; // 当前页面 if (currPage) { let curParam = currPage.options // 拼接参数 let reUrl = '/' + currPage.route if (curParam != null) { // 拼接参数 let param = '' for (let key in curParam) { param += '&' + key + '=' + curParam[key] } param = param.substr(1) reUrl = reUrl + '?' + param reUrl = encodeURIComponent(reUrl) } uni.reLaunch({ url: '/pages/login/index?reUrl=' + reUrl }); } } /** * 拼接完整图片字符串 */ const spliceAssetsUrl = imgUrl => { let imgHostUrl = __config.imgHostUrl; if (!imgUrl) return imgHostUrl if (imgUrl.substr(0, 1) != "/") { imgUrl = `/${imgUrl}` } let allImgUrl = `${imgHostUrl}${imgUrl}` return allImgUrl; } /** * 拼接背景图片字符串 (url('xxxx/xxx.png')) */ const spliceBgImgUrl = imgUrl => { if (!imgUrl) return 'url()' let allImgUrl = spliceAssetsUrl(imgUrl) return 'url(' + allImgUrl + ')'; } //解析用户对象格式 const parseUser = userData => { let memberAccount = userData if (memberAccount) { // 复制属性名字 accountId memberAccount.memberInfo.accountId = memberAccount.memberInfo.id if (memberAccount.memberInfo) { memberAccount.memberInfo['mobile'] = memberAccount['mobile'] if (memberAccount.wxThirdUser) { memberAccount.memberInfo['openId'] = memberAccount.wxThirdUser['openId'] memberAccount.memberInfo['uuid'] = memberAccount.wxThirdUser['uuid'] memberAccount.memberInfo['unionId'] = memberAccount.wxThirdUser['unionId'] memberAccount.memberInfo['channelCode'] = memberAccount.wxThirdUser['channelCode'] memberAccount.memberInfo['blog'] = memberAccount.wxThirdUser['blog'] memberAccount.memberInfo['clientId'] = memberAccount.wxThirdUser['clientId'] } } } else { memberAccount = {} memberAccount['memberInfo'] = undefined console.error('[parseUser]用户登录信息memberAccount返回为null') } /* 删除无用的字段 */ //delete memberAccount.memberInfo.id delete memberAccount.memberInfo.$_createBy delete memberAccount.memberInfo.$_createTime delete memberAccount.memberInfo.$_updateBy delete memberAccount.memberInfo.$_updateTime delete memberAccount.memberInfo.delFlag delete memberAccount.memberInfo.params delete memberAccount.memberInfo.searchValue delete memberAccount.memberInfo.memberAccount uni.setStorageSync(__config.loginWxUserInfoKey, memberAccount.memberInfo) /* 返回解析后的用户信息 */ return memberAccount.memberInfo; } /** * 跳转页面 * @param {Object} page */ const navigateToPage = function(page, success) { if (!page) { return } const pages = getCurrentPages(); let curRoute = getCurPage(pages) console.info('[navigateToPage]_当前路由页面: ', curRoute) console.info('[navigateToPage]_将要跳转页面: ', page) if (page.substr(0, 1) == "/") { curRoute = `/${curRoute}` } if (curRoute == page) { console.log('[navigateToPage]_路由相同: 不进行跳转') return } uni.navigateTo({ url: page, success: (res) => { if (success) { success(res) } uni.$emit('reloadSocket') } }) } /** * 跳转页面 * @param {Object} page */ const reLaunchToPage = function(page, success) { if (!page) { return } const pages = getCurrentPages(); let curRoute = getCurPage(pages) console.info('[reLaunchToPage]_当前路由页面: ', curRoute) console.info('[reLaunchToPage]_将要跳转页面: ', page) if (page.substr(0, 1) == "/") { curRoute = `/${curRoute}` } // if (curRoute == page) { // console.log('[reLaunchToPage]_路由相同: 不进行跳转') // return // } uni.reLaunch({ url: page, success: (res) => { if (success) { success(res) } uni.$emit('reloadSocket') } }) } /** * 弹出普通提示窗 * @param {Object} title */ const showToast = function(title) { if (!title) { return } uni.showToast({ title: title, }) } /** * 加载网络字体文件 * @param {Object} family * @param {Object} source */ const loadFontFace = function(family, source) { uni.loadFontFace({ family: family, source: `url("${spliceAssetsUrl(source)}")`, success: function(res) { console.log(`load font ${family} from ${spliceAssetsUrl(source)} success!`) }, fail: function(err) { console.error(err) } }) } /** * px 转换 rpx * @param {Object} px */ const pxTorpx = function(px) { let deviceWidth = uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度 let rpx = (750 / deviceWidth) * Number(px) return Math.floor(rpx); }; /** * rpx 转换 px * @param {Object} rpx */ const rpxTopx = function(rpx) { let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度 let px = (deviceWidth / 750) * Number(rpx) return Math.floor(px); }; /** * 处理优惠卷方法 */ const couponProces = function(e,list){ if(list.type == 1 || list.types == 1){ // 满减卷 console.log(list) console.log(e) let price = new Decimal(e).sub(new Decimal(list.reduceAmount)).toFixed(2, Decimal.ROUND_HALF_UP) let lists = { price: price < 0 ? 0 : price, reduceAmount: price < 0 ? e : list.reduceAmount } return lists }else if(list.type == 2){ let lists = { price: new Decimal(e).mul(new Decimal(list.discount).div(new Decimal(10))).toFixed(2, Decimal.ROUND_HALF_UP), reduceAmount: new Decimal(e).sub(new Decimal(e).mul(new Decimal(list.discount).div(new Decimal(10))).toFixed(2, Decimal.ROUND_HALF_UP)) } return lists }else{ return false } }; /** * 处理第二份半价方法 */ const secondHalfPrice = function(e,shoppingCardList,spuIdsList){ let price = new Decimal(e) let reduceAmount = new Decimal(0) console.log(price) for (var i = 0; i < shoppingCardList.length; i++) { if(spuIdsList.includes(shoppingCardList[i].spuId)){ // 商品数量向下取整看有几份可第二份半价的 let length = new Decimal(shoppingCardList[i].quantity).div(2).toFixed(0, Decimal.ROUND_DOWN) // 计算出总共优惠多少这个商品 let prices = new Decimal(length).mul(new Decimal(shoppingCardList[i].goodsSku.salesPrice).div(2)) reduceAmount = reduceAmount.add(prices) } } price = price.sub(reduceAmount.toFixed(2, Decimal.ROUND_HALF_UP)) let lists = { price: price.toNumber(), reduceAmount: reduceAmount.toNumber().toFixed(2, Decimal.ROUND_HALF_UP) } console.log(lists) return lists }; /** * 根据比例计算rpx值 * @param {Object} rpxVal 比例为3时的值 * @param {Object} offset 偏移量,支持负数 */ const calcPixelRatio = function(rpxVal, offset = 0){ let defaultPR = new Decimal(3).div(new Decimal(rpxVal)).toNumber(); let devicePixelRatio = uni.$u.devicePixelRatio; if(devicePixelRatio == 3){ return rpxVal } if(devicePixelRatio == 1 || Number(rpxVal) <= 0){ return rpxVal + offset }else{ let newRpxVal = new Decimal(devicePixelRatio).div(new Decimal(defaultPR)).toNumber() let newRpxValAndOffset = new Decimal(newRpxVal).add(new Decimal(offset)).toNumber(); return newRpxValAndOffset } }; const getUuid = function(){ var s = []; var hexDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = ""; var uuid = s.join(""); return uuid; }; module.exports = { formatTime: formatTime, filterForm: filterForm, getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs, getUrlParam: getUrlParam, isWeiXinBrowser: isWeiXinBrowser, isMiniPg: isMiniPg, resetPageUrl: resetPageUrl, getClientCode: getClientCode, imgUrlToBase64: imgUrlToBase64, setAppPlusShareUrl: setAppPlusShareUrl, setH5ShareUrl: setH5ShareUrl, getCurPage: getCurPage, saveSharerUserCode: saveSharerUserCode, dataAddSharerUserCode: dataAddSharerUserCode, backLoginPage: backLoginPage, setAppPlusHomeShareUrl, setH5HomeShareUrl, spliceAssetsUrl, spliceBgImgUrl, parseUser, navigateToPage, reLaunchToPage, getCurrentPageOptions, showToast, loadFontFace, pxTorpx, rpxTopx, getUuid, couponProces, secondHalfPrice, calcPixelRatio };