util.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. const validate = require("./validate.js");
  2. import __config from '@/config/env';
  3. import api from '@/utils/api.js';
  4. import Decimal from 'decimal.js';
  5. const formatTime = date => {
  6. const year = date.getFullYear();
  7. const month = date.getMonth() + 1;
  8. const day = date.getDate();
  9. const hour = date.getHours();
  10. const minute = date.getMinutes();
  11. const second = date.getSeconds();
  12. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(
  13. ':');
  14. };
  15. const formatNumber = n => {
  16. n = n.toString();
  17. return n[1] ? n : '0' + n;
  18. };
  19. //空值过滤器
  20. const filterForm = form => {
  21. let obj = {};
  22. Object.keys(form).forEach(ele => {
  23. if (!validate.validatenull(form[ele])) {
  24. obj[ele] = form[ele];
  25. }
  26. });
  27. return obj;
  28. };
  29. //获取当前页面带参数的url
  30. const getCurrentPageUrlWithArgs = val => {
  31. const pages = getCurrentPages();
  32. const currentPage = pages[pages.length - 1];
  33. const url = currentPage.route;
  34. const options = currentPage.options;
  35. let urlWithArgs = `/${url}?`;
  36. for (let key in options) {
  37. const value = options[key];
  38. urlWithArgs += `${key}=${value}&`;
  39. }
  40. urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
  41. return urlWithArgs;
  42. }
  43. /* 获取当前页面options参数对象 */
  44. const getCurrentPageOptions = () => {
  45. const pages = getCurrentPages();
  46. const currentPage = pages[pages.length - 1];
  47. const url = currentPage.route;
  48. const options = currentPage.options;
  49. return options
  50. }
  51. //获取url中的参数
  52. const getUrlParam = (path, name) => {
  53. var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
  54. if (reg.test(path))
  55. return unescape(RegExp.$2.replace(/\+/g, " "));
  56. return "";
  57. }
  58. //判断是否为微信浏览器中运行
  59. const isWeiXinBrowser = () => {
  60. // #ifdef H5
  61. // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息,这个属性可以用来判断浏览器类型
  62. let ua = window.navigator.userAgent.toLowerCase()
  63. // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
  64. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  65. return true
  66. } else {
  67. return false
  68. }
  69. // #endif
  70. return false
  71. }
  72. //判断是否是小程序
  73. const isMiniPg = () => {
  74. let isMiniPg = false
  75. //#ifdef MP-WEIXIN
  76. isMiniPg = true
  77. //#endif
  78. return isMiniPg
  79. }
  80. //获取客服端代码
  81. const getClientCode = () => {
  82. let code = {}
  83. //#ifdef MP-WEIXIN
  84. code = {
  85. key: 'MP-WEIXIN',
  86. value: '微信小程序'
  87. }
  88. //#endif
  89. //#ifdef H5
  90. //普通H5
  91. code = {
  92. key: 'H5',
  93. value: '普通H5'
  94. }
  95. if (isWeiXinBrowser()) {
  96. //微信公众号H5
  97. code = {
  98. key: 'H5-WX',
  99. value: '公众号H5'
  100. }
  101. }
  102. //#endif
  103. return code
  104. }
  105. //重置url中的参数
  106. const resetPageUrl = (query) => {
  107. var ary = [];
  108. for (var p in query) {
  109. if (query.hasOwnProperty(p) && query[p]) {
  110. ary.push(encodeURIComponent(p) + '=' + encodeURIComponent(query[p]));
  111. }
  112. }
  113. if (ary.length > 0) {
  114. let url = "?" + ary.join('&');
  115. history.replaceState(history.state, null, url); //替换页面显示url
  116. }
  117. }
  118. const imgUrlToBase64 = (imageUrl) => {
  119. return new Promise((resolve, reject) => {
  120. try {
  121. uni.downloadFile({
  122. url: imageUrl + '?s=' + Math.random().toString(),
  123. success: res => {
  124. if (res.statusCode === 200) {
  125. // uni 如果是H5或者APP会自动转为base64返回
  126. resolve(res.tempFilePath);
  127. } else {
  128. reject(res.errMsg);
  129. }
  130. },
  131. fail(err) {
  132. reject(err);
  133. }
  134. });
  135. } catch (e) {
  136. console.log(e)
  137. resolve(imageUrl);
  138. }
  139. })
  140. }
  141. // 设置原生app的分享url为h5的地址url
  142. const setAppPlusShareUrl = query => {
  143. const pages = getCurrentPages();
  144. const curPage = pages[pages.length - 1];
  145. const userInfo = uni.getStorageSync('wx_login_user_info')
  146. const userCode = userInfo ? userInfo.userCode : ''
  147. let component_appid = ""
  148. if (query && query.componentAppId) {
  149. component_appid = "&component_appid=" + query.componentAppId
  150. }
  151. let fullPath = curPage.$page.fullPath
  152. //判断是否有问号
  153. fullPath = fullPath.indexOf('?') != -1 ? fullPath + '&' : fullPath + '?'
  154. if (userCode) {
  155. return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId +
  156. '&sharer_user_code=' + userCode + component_appid;
  157. } else {
  158. return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId +
  159. component_appid
  160. }
  161. };
  162. // 设置原生app的分享url为h5的地址url(用于分销,默认首页地址)
  163. const setAppPlusHomeShareUrl = query => {
  164. const userInfo = uni.getStorageSync('wx_login_user_info')
  165. const userCode = userInfo ? userInfo.userCode : ''
  166. let component_appid = ""
  167. if (query && query.componentAppId) {
  168. component_appid = "&component_appid=" + query.componentAppId
  169. }
  170. let fullPath = '/mp/views/home/index?'
  171. if (userCode) {
  172. return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId +
  173. '&sharer_user_code=' + userCode + component_appid;
  174. } else {
  175. return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId +
  176. component_appid
  177. }
  178. };
  179. // 设置h5的分享地址url
  180. const setH5ShareUrl = val => {
  181. const userInfo = uni.getStorageSync('wx_login_user_info')
  182. const userCode = userInfo ? userInfo.userCode : ''
  183. let url = window.location.href
  184. // 如果没有 sharer_user_code 就添加,如果有就替换为自己的userCode
  185. if (userCode) {
  186. let index = url.indexOf('&sharer_user_code=')
  187. if (index == -1) {
  188. url = url + '&sharer_user_code=' + userCode;
  189. } else {
  190. let urlTemp = url.slice(0, index);
  191. url = urlTemp + '&sharer_user_code=' + userCode;
  192. }
  193. }
  194. return url
  195. }
  196. // 设置H5的分享url(用于分销,默认首页地址)
  197. const setH5HomeShareUrl = val => {
  198. const userInfo = uni.getStorageSync('wx_login_user_info')
  199. const userCode = userInfo ? userInfo.userCode : ''
  200. // 如果没有 sharer_user_code 就添加
  201. let url = window.location.origin + window.location.search;
  202. if (userCode) {
  203. let index = url.indexOf('&sharer_user_code=')
  204. if (index == -1) {
  205. url = url + '&sharer_user_code=' + userCode;
  206. } else {
  207. let urlTemp = url.slice(0, index);
  208. url = urlTemp + '&sharer_user_code=' + userCode;
  209. }
  210. }
  211. return url
  212. }
  213. // 获取当前页面路由或 path
  214. const getCurPage = pages => {
  215. let curPage = pages[pages.length - 1];
  216. return curPage.route
  217. }
  218. // 保存别人分享来的 userCode
  219. const saveSharerUserCode = options => {
  220. if (options.scene) {
  221. //接受二维码中参数
  222. /**
  223. * 这里需要特别注意:
  224. * 由于腾讯限制了scenes的长度,导致传参的局限性,为尽可能的利用这有限的长度传参,
  225. * 故我们定义了scenes的参数格式,当一个页面需要传多个参数时,我们用“&”符号分割开来,第2位固定放分享人的user_code,这样可以最大限度减少长度占用
  226. * 第1位一般放ID,第2位固定放分享人的user_code,比如菜品页面scenes为:goodspuId+&+sharer_user_code
  227. * 因为固定第2位放分享人的user_code,当有些页面无需传ID时,我们也需要用“&”拼一下,第一位随意用一个字符点位即可,比如页面scenes为:0+&+sharer_user_code
  228. */
  229. let scenes = decodeURIComponent(options.scene).split('&');
  230. if (scenes[1]) {
  231. uni.setStorageSync('sharer_user_code', scenes[1]);
  232. }
  233. } else {
  234. if (options.sharer_user_code) {
  235. uni.setStorageSync('sharer_user_code', '');
  236. uni.setStorageSync('sharer_user_code', options.sharer_user_code);
  237. }
  238. }
  239. }
  240. // 如果有分享人则给data带上分享人的user_code
  241. const dataAddSharerUserCode = data => {
  242. let sharer_user_code = uni.getStorageSync('sharer_user_code')
  243. if (sharer_user_code) {
  244. data = Object.assign({
  245. sharerUserCode: sharer_user_code
  246. }, data)
  247. }
  248. return data
  249. }
  250. //返回登录页面
  251. const backLoginPage = data => {
  252. var pages = getCurrentPages(); // 获取页面栈
  253. var currPage = pages[pages.length - 1]; // 当前页面
  254. if (currPage) {
  255. let curParam = currPage.options
  256. // 拼接参数
  257. let reUrl = '/' + currPage.route
  258. if (curParam != null) {
  259. // 拼接参数
  260. let param = ''
  261. for (let key in curParam) {
  262. param += '&' + key + '=' + curParam[key]
  263. }
  264. param = param.substr(1)
  265. reUrl = reUrl + '?' + param
  266. reUrl = encodeURIComponent(reUrl)
  267. }
  268. uni.reLaunch({
  269. url: '/pages/login/index?reUrl=' + reUrl
  270. });
  271. }
  272. }
  273. /**
  274. * 拼接完整图片字符串
  275. */
  276. const spliceAssetsUrl = imgUrl => {
  277. let imgHostUrl = __config.imgHostUrl;
  278. if (!imgUrl)
  279. return imgHostUrl
  280. if (imgUrl.substr(0, 1) != "/") {
  281. imgUrl = `/${imgUrl}`
  282. }
  283. let allImgUrl = `${imgHostUrl}${imgUrl}`
  284. return allImgUrl;
  285. }
  286. /**
  287. * 拼接背景图片字符串 (url('xxxx/xxx.png'))
  288. */
  289. const spliceBgImgUrl = imgUrl => {
  290. if (!imgUrl)
  291. return 'url()'
  292. let allImgUrl = spliceAssetsUrl(imgUrl)
  293. return 'url(' + allImgUrl + ')';
  294. }
  295. //解析用户对象格式
  296. const parseUser = userData => {
  297. let memberAccount = userData
  298. if (memberAccount) {
  299. // 复制属性名字 accountId
  300. memberAccount.memberInfo.accountId = memberAccount.memberInfo.id
  301. if (memberAccount.memberInfo) {
  302. memberAccount.memberInfo['mobile'] = memberAccount['mobile']
  303. if (memberAccount.wxThirdUser) {
  304. memberAccount.memberInfo['openId'] = memberAccount.wxThirdUser['openId']
  305. memberAccount.memberInfo['uuid'] = memberAccount.wxThirdUser['uuid']
  306. memberAccount.memberInfo['unionId'] = memberAccount.wxThirdUser['unionId']
  307. memberAccount.memberInfo['channelCode'] = memberAccount.wxThirdUser['channelCode']
  308. memberAccount.memberInfo['blog'] = memberAccount.wxThirdUser['blog']
  309. memberAccount.memberInfo['clientId'] = memberAccount.wxThirdUser['clientId']
  310. }
  311. }
  312. } else {
  313. memberAccount = {}
  314. memberAccount['memberInfo'] = undefined
  315. console.error('[parseUser]用户登录信息memberAccount返回为null')
  316. }
  317. /* 删除无用的字段 */
  318. //delete memberAccount.memberInfo.id
  319. delete memberAccount.memberInfo.$_createBy
  320. delete memberAccount.memberInfo.$_createTime
  321. delete memberAccount.memberInfo.$_updateBy
  322. delete memberAccount.memberInfo.$_updateTime
  323. delete memberAccount.memberInfo.delFlag
  324. delete memberAccount.memberInfo.params
  325. delete memberAccount.memberInfo.searchValue
  326. delete memberAccount.memberInfo.memberAccount
  327. uni.setStorageSync(__config.loginWxUserInfoKey, memberAccount.memberInfo)
  328. /* 返回解析后的用户信息 */
  329. return memberAccount.memberInfo;
  330. }
  331. /**
  332. * 跳转页面
  333. * @param {Object} page
  334. */
  335. const navigateToPage = function(page, success) {
  336. if (!page) {
  337. return
  338. }
  339. const pages = getCurrentPages();
  340. let curRoute = getCurPage(pages)
  341. console.info('[navigateToPage]_当前路由页面: ', curRoute)
  342. console.info('[navigateToPage]_将要跳转页面: ', page)
  343. if (page.substr(0, 1) == "/") {
  344. curRoute = `/${curRoute}`
  345. }
  346. if (curRoute == page) {
  347. console.log('[navigateToPage]_路由相同: 不进行跳转')
  348. return
  349. }
  350. uni.navigateTo({
  351. url: page,
  352. success: (res) => {
  353. if (success) {
  354. success(res)
  355. }
  356. uni.$emit('reloadSocket')
  357. }
  358. })
  359. }
  360. /**
  361. * 跳转页面
  362. * @param {Object} page
  363. */
  364. const reLaunchToPage = function(page, success) {
  365. if (!page) {
  366. return
  367. }
  368. const pages = getCurrentPages();
  369. let curRoute = getCurPage(pages)
  370. console.info('[reLaunchToPage]_当前路由页面: ', curRoute)
  371. console.info('[reLaunchToPage]_将要跳转页面: ', page)
  372. if (page.substr(0, 1) == "/") {
  373. curRoute = `/${curRoute}`
  374. }
  375. // if (curRoute == page) {
  376. // console.log('[reLaunchToPage]_路由相同: 不进行跳转')
  377. // return
  378. // }
  379. uni.reLaunch({
  380. url: page,
  381. success: (res) => {
  382. if (success) {
  383. success(res)
  384. }
  385. uni.$emit('reloadSocket')
  386. }
  387. })
  388. }
  389. /**
  390. * 弹出普通提示窗
  391. * @param {Object} title
  392. */
  393. const showToast = function(title) {
  394. if (!title) {
  395. return
  396. }
  397. uni.showToast({
  398. title: title,
  399. })
  400. }
  401. /**
  402. * 加载网络字体文件
  403. * @param {Object} family
  404. * @param {Object} source
  405. */
  406. const loadFontFace = function(family, source) {
  407. uni.loadFontFace({
  408. family: family,
  409. source: `url("${spliceAssetsUrl(source)}")`,
  410. success: function(res) {
  411. console.log(`load font ${family} from ${spliceAssetsUrl(source)} success!`)
  412. },
  413. fail: function(err) {
  414. console.error(err)
  415. }
  416. })
  417. }
  418. /**
  419. * px 转换 rpx
  420. * @param {Object} px
  421. */
  422. const pxTorpx = function(px) {
  423. let deviceWidth = uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
  424. let rpx = (750 / deviceWidth) * Number(px)
  425. return Math.floor(rpx);
  426. };
  427. /**
  428. * rpx 转换 px
  429. * @param {Object} rpx
  430. */
  431. const rpxTopx = function(rpx) {
  432. let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
  433. let px = (deviceWidth / 750) * Number(rpx)
  434. return Math.floor(px);
  435. };
  436. /**
  437. * 处理优惠卷方法
  438. */
  439. const couponProces = function(e,list){
  440. if(list.type == 1 || list.types == 1){
  441. // 满减卷
  442. console.log(list)
  443. console.log(e)
  444. let price = new Decimal(e).sub(new Decimal(list.reduceAmount)).toFixed(2, Decimal.ROUND_HALF_UP)
  445. let lists = {
  446. price: price < 0 ? 0 : price,
  447. reduceAmount: price < 0 ? e : list.reduceAmount
  448. }
  449. return lists
  450. }else if(list.type == 2){
  451. let lists = {
  452. price: new Decimal(e).mul(new Decimal(list.discount).div(new Decimal(10))).toFixed(2, Decimal.ROUND_HALF_UP),
  453. reduceAmount: new Decimal(e).sub(new Decimal(e).mul(new Decimal(list.discount).div(new Decimal(10))).toFixed(2, Decimal.ROUND_HALF_UP))
  454. }
  455. return lists
  456. }else{
  457. return false
  458. }
  459. };
  460. /**
  461. * 处理第二份半价方法
  462. */
  463. const secondHalfPrice = function(e,shoppingCardList,spuIdsList){
  464. let price = new Decimal(e)
  465. let reduceAmount = new Decimal(0)
  466. console.log(price)
  467. for (var i = 0; i < shoppingCardList.length; i++) {
  468. if(spuIdsList.includes(shoppingCardList[i].spuId)){
  469. // 商品数量向下取整看有几份可第二份半价的
  470. let length = new Decimal(shoppingCardList[i].quantity).div(2).toFixed(0, Decimal.ROUND_DOWN)
  471. // 计算出总共优惠多少这个商品
  472. let prices = new Decimal(length).mul(new Decimal(shoppingCardList[i].goodsSku.salesPrice).div(2))
  473. reduceAmount = reduceAmount.add(prices)
  474. }
  475. }
  476. price = price.sub(reduceAmount.toFixed(2, Decimal.ROUND_HALF_UP))
  477. let lists = {
  478. price: price.toNumber(),
  479. reduceAmount: reduceAmount.toNumber().toFixed(2, Decimal.ROUND_HALF_UP)
  480. }
  481. console.log(lists)
  482. return lists
  483. };
  484. /**
  485. * 根据比例计算rpx值
  486. * @param {Object} rpxVal 比例为3时的值
  487. * @param {Object} offset 偏移量,支持负数
  488. */
  489. const calcPixelRatio = function(rpxVal, offset = 0){
  490. let defaultPR = new Decimal(3).div(new Decimal(rpxVal)).toNumber();
  491. let devicePixelRatio = uni.$u.devicePixelRatio;
  492. if(devicePixelRatio == 3){
  493. return rpxVal
  494. }
  495. if(devicePixelRatio == 1 || Number(rpxVal) <= 0){
  496. return rpxVal + offset
  497. }else{
  498. let newRpxVal = new Decimal(devicePixelRatio).div(new Decimal(defaultPR)).toNumber()
  499. let newRpxValAndOffset = new Decimal(newRpxVal).add(new Decimal(offset)).toNumber();
  500. return newRpxValAndOffset
  501. }
  502. };
  503. const getUuid = function(){
  504. var s = [];
  505. var hexDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  506. for (var i = 0; i < 36; i++) {
  507. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  508. }
  509. s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  510. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  511. s[8] = s[13] = s[18] = s[23] = "";
  512. var uuid = s.join("");
  513. return uuid;
  514. };
  515. module.exports = {
  516. formatTime: formatTime,
  517. filterForm: filterForm,
  518. getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs,
  519. getUrlParam: getUrlParam,
  520. isWeiXinBrowser: isWeiXinBrowser,
  521. isMiniPg: isMiniPg,
  522. resetPageUrl: resetPageUrl,
  523. getClientCode: getClientCode,
  524. imgUrlToBase64: imgUrlToBase64,
  525. setAppPlusShareUrl: setAppPlusShareUrl,
  526. setH5ShareUrl: setH5ShareUrl,
  527. getCurPage: getCurPage,
  528. saveSharerUserCode: saveSharerUserCode,
  529. dataAddSharerUserCode: dataAddSharerUserCode,
  530. backLoginPage: backLoginPage,
  531. setAppPlusHomeShareUrl,
  532. setH5HomeShareUrl,
  533. spliceAssetsUrl,
  534. spliceBgImgUrl,
  535. parseUser,
  536. navigateToPage,
  537. reLaunchToPage,
  538. getCurrentPageOptions,
  539. showToast,
  540. loadFontFace,
  541. pxTorpx,
  542. rpxTopx,
  543. getUuid,
  544. couponProces,
  545. secondHalfPrice,
  546. calcPixelRatio
  547. };