util.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. import requestConfig from '../lib/requestConfig.js';
  2. import CryptoJS from '@/common/static/crypto-js.min.js';
  3. const config = require('../config.js');
  4. let setIntervalKey;
  5. const keys = "ELAB_ADLWROEMSAQ";
  6. const iv = "ELAB_LIDERT_WEDH";
  7. function formatNumber(n) {
  8. n = n.toString()
  9. return n[1] ? n : '0' + n
  10. }
  11. var util = {
  12. formatTime: function(date) {
  13. var year = date.getFullYear()
  14. var month = date.getMonth() + 1
  15. var day = date.getDate()
  16. var hour = date.getHours()
  17. var minute = date.getMinutes()
  18. var second = date.getSeconds()
  19. return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(
  20. ':')
  21. },
  22. formatCNTime: function(val) {
  23. const year = val.getFullYear();
  24. const month = val.getMonth() + 1;
  25. const day = val.getDate();
  26. const hour = val.getHours();
  27. const minute = val.getMinutes();
  28. const second = val.getSeconds();
  29. return year + '年' + (month > 9 ? month : '0' + month) + '月' + day + '日' + hour + '时' + (minute > 9 ?
  30. minute : '0' +
  31. minute) + '分' + second + '秒';
  32. },
  33. formatCNTime1: function(val) {
  34. const year = val.getFullYear();
  35. const month = val.getMonth() + 1;
  36. const day = val.getDate();
  37. const hour = val.getHours();
  38. const minute = val.getMinutes();
  39. const second = val.getSeconds();
  40. return year + '年' + (month > 9 ? month : '0' + month) + '月' + (day > 9 ? day : '0' + day) + '日';
  41. },
  42. buttonClicked(self, time) {
  43. self.setData({
  44. buttonClicked: false
  45. })
  46. setTimeout(function() {
  47. self.setData({
  48. buttonClicked: true
  49. })
  50. }, time)
  51. },
  52. formatTodayTime: function(val) {
  53. if (typeof val !== 'object') {
  54. console.log('时间格式不对,不予转换')
  55. return val
  56. }
  57. const year = val.getFullYear();
  58. const month = val.getMonth() + 1;
  59. const day = val.getDate();
  60. const hour = val.getHours();
  61. const minute = val.getMinutes();
  62. const second = val.getSeconds();
  63. if (month == new Date().getMonth() + 1 && day + 1 == new Date().getDate()) {
  64. return '昨天' + hour + ':' + (minute > 9 ? minute : '0' + minute);
  65. } else if (month == new Date().getMonth() + 1 && day == new Date().getDate()) {
  66. return hour + ':' + (minute > 9 ? minute : '0' + minute) + ':' + (second > 9 ? second : '0' +
  67. second);
  68. } else {
  69. return year + '-' + (month > 9 ? month : '0' + month) + '-' + (day > 9 ? day : '0' + day) + ' ' +
  70. hour + ':' + (
  71. minute > 9 ? minute : '0' + minute) + ':' + (second > 9 ? second : '0' + second);
  72. }
  73. },
  74. formatMinuteTime: function(val) {
  75. const year = val.getFullYear();
  76. const month = val.getMonth() + 1;
  77. const day = val.getDate();
  78. const hour = val.getHours();
  79. const minute = val.getMinutes();
  80. const second = val.getSeconds();
  81. return year + '.' + (month > 9 ? month : '0' + month) + '.' + (day > 9 ? day : '0' + day) + ' ' + hour +
  82. ':' + (
  83. minute > 9 ? minute : '0' + minute)
  84. },
  85. formatSucTime: function(val) {
  86. const year = val.getFullYear();
  87. const month = val.getMonth() + 1;
  88. const day = val.getDate();
  89. const hour = val.getHours();
  90. const minute = val.getMinutes();
  91. if (month == new Date().getMonth() + 1 && day + 1 == new Date().getDate()) {
  92. return '昨天' + hour + ':' + (minute > 9 ? minute : '0' + minute);
  93. } else if (month == new Date().getMonth() + 1 && day == new Date().getDate()) {
  94. return hour + ':' + (minute > 9 ? minute : '0' + minute);
  95. } else {
  96. return year + '-' + (month > 9 ? month : '0' + month) + '-' + day + ' ' + hour + ':' + (minute > 9 ?
  97. minute : '0' +
  98. minute);
  99. }
  100. },
  101. async sendScoreShare() {
  102. const app = getApp();
  103. const res = await requestConfig('intergralShare', {
  104. customerId: app.globalData.single.id,
  105. brandId: config.brandId,
  106. houseId: config.houseId || '',
  107. });
  108. },
  109. trackRequest(para, app = getApp()) {
  110. if ((para.type && para.type.includes('Error'))) {
  111. //所有报错埋点以及曝光埋点不再发送至服务器
  112. return
  113. }
  114. if (JSON.stringify(para.clkParams) === '"{}"' || JSON.stringify(para.clkParams) === "{}") {
  115. para.clkParams = '';
  116. }
  117. if (JSON.stringify(para.expand) === '"{}"' || JSON.stringify(para.expand) === "{}") {
  118. para.expand = '';
  119. }
  120. let _scene = (app.globalData.launchInfo && app.globalData.launchInfo.scene) ? app.globalData.launchInfo.scene :
  121. '';
  122. console.log("app.globalData.launchInfo:" + JSON.stringify(app.globalData.launchInfo));
  123. let _fromParam = app.globalData.exchangedFromChannel ? JSON.parse(app.globalData.exchangedFromChannel) : {};
  124. //上一个页面
  125. let lastPage = getCurrentPages()[getCurrentPages().length-2] ? getCurrentPages()[getCurrentPages().length-2].$vm : null;
  126. let _pvLastPageName = lastPage ? lastPage.pvCurPageName : '';//上一页面名称
  127. let _pvLastPageParams = (lastPage && lastPage.pvCurPageParams) ? lastPage.pvCurPageParams : '';//上一页面参数
  128. let _pvLastPagePath = lastPage ? (lastPage.route || lastPage.__route__) : '';//上一页面路径
  129. let currPage = getCurrentPages()[getCurrentPages().length-1] ? getCurrentPages()[getCurrentPages().length-1].$vm : null;
  130. let _route = currPage ? (currPage.route || currPage.__route__) : "";
  131. let _pvCurPageName = currPage ? currPage.pvCurPageName : '';//当前页面名称
  132. let pvCurPageParams = "";//字符串string对象
  133. if(para.pvCurPageParams){//调用的时候传递进来的-先转为对象
  134. pvCurPageParams = typeof para.pvCurPageParams === 'object' ? para.pvCurPageParams : JSON.parse(para.pvCurPageParams)
  135. }else{
  136. let _tmp = (currPage && currPage.pvCurPageParams) ? currPage.pvCurPageParams : '{}';//获取当前页面的参数
  137. pvCurPageParams = typeof _tmp === 'string' ? JSON.parse(_tmp) : JSON.parse(JSON.stringify(_tmp))
  138. }
  139. //在页面参数里面手动添加path参数
  140. pvCurPageParams.brandId = config.brandId || "";
  141. pvCurPageParams.path = _route;
  142. pvCurPageParams.pageId = currPage.pageId || "";
  143. pvCurPageParams.mobile = app.globalData.phone || "";
  144. pvCurPageParams.entryPageId = (lastPage && lastPage.pageId) ? lastPage.pageId : "";
  145. pvCurPageParams.entryPagePath = _pvLastPagePath;
  146. pvCurPageParams = JSON.stringify(pvCurPageParams);
  147. if(para.clkId==='clk_2cmina_18'){
  148. this.sendScoreShare()
  149. }
  150. if (JSON.stringify(pvCurPageParams) === '"{}"' || JSON.stringify(pvCurPageParams) === "{}") {
  151. pvCurPageParams = '';
  152. }
  153. _fromParam["scene"] = _scene;
  154. _fromParam["appName"] = app.globalData.systemInfo ? app.globalData.systemInfo.appName : (app.$vm.$options.globalData.systemInfo.appName ||
  155. "");
  156. _fromParam['eventtime'] = Date.now();
  157. let houseID = "";
  158. if (currPage && currPage.houseId) {
  159. houseID = currPage.houseId;
  160. }
  161. if (currPage && (currPage.route == 'pages/shareCard/shareCard' || currPage.__route__ ==
  162. 'pages/shareCard/shareCard')) {
  163. let enterPage = getCurrentPages()[getCurrentPages().length - 2] ? getCurrentPages()[getCurrentPages().length -
  164. 2].$vm :
  165. null;
  166. if (enterPage && enterPage.houseId) {
  167. houseID = enterPage.houseId;
  168. }
  169. }
  170. console.log("houseID:" + houseID);
  171. let data = {
  172. userAgent: '',
  173. browserName: '',
  174. browserVersion: app.globalData.systemInfo ? app.globalData.systemInfo.SDKVersion : app.$vm.$options.globalData.systemInfo.SDKVersion,
  175. platform: 'miniapp', //是否来自小程序的标志
  176. fromPlatform: '', //来源平台,需要汤勇提供接口解析fromChannel存放
  177. reserve1: app.globalData.terminal, //来源平台,抖音百度微信
  178. reserve2: app.globalData.selectCityName || app.globalData.defaultProductCityName, //当前所在城市
  179. fromParam: JSON.stringify(_fromParam), //转发者秘钥
  180. deviceType: app.globalData.systemInfo ? app.globalData.systemInfo.model : (app.$vm.$options.globalData.systemInfo.SDKVersion || ""), //设备系统信息
  181. ip: app.globalData.ip || '', //ip地址
  182. cookieId: '',
  183. openId: app.globalData.openid || '', //openid
  184. customerId: (app.globalData.single && app.globalData.single.id) ? app.globalData.single.id : '', //用户id
  185. brandUserId: (app.globalData.single && app.globalData.single.id) ? app.globalData.single.id : '', //用户id
  186. createTime: this.formatTime(new Date()), //发送埋点时间
  187. uploadTime: this.formatTime(new Date()), //发送埋点时间
  188. product: app.globalData.projectName, //当前所在项目中文名称
  189. project: houseID, //当前项目id
  190. eventId: para.eventId || '', //埋点ID
  191. eventName: para.eventName || '', //埋点ID
  192. expand: typeof para.expand === 'object' ? JSON.stringify(para.expand) : para.expand, //扩展字段
  193. imTalkId: para.imTalkId || '', //IM对话编号
  194. imTalkType: para.imTalkType || '', //IM对话类型
  195. eventModuleDes: para.eventModuleDes || '', //模块描述信息
  196. eventInnerModuleId: para.eventInnerModuleId || '', //事件内部模块信息
  197. adviserId: para.adviserId || '', //顾问id
  198. clkDesPage: para.clkDesPage || _pvCurPageName || '', //点击前往的页面名称
  199. clkId: para.clkId || '', //点击ID
  200. clkName: para.clkName || '',
  201. pvId: para.pvId || '', //PV埋点ID
  202. clkParams: typeof para.clkParams === 'object' ? JSON.stringify(para.clkParams) : para.clkParams, //点击参数
  203. pvPageStayTime: para.pvPageStayTime || '',
  204. pvCurPageName: para.pvCurPageName || _pvCurPageName || '', //当前页面名称
  205. pvCurPageParams: pvCurPageParams, //当前页面参数
  206. pvLastPageName: para.pvLastPageName || _pvLastPageName || '', //上一页页面名称
  207. pvLastPageParams: para.pvLastPageParams || _pvLastPageParams || '', //上一页页面参数
  208. pvPageLoadTime: para.pvPageLoadTime || '', //加载时间
  209. type: para.type || '', //埋点类型
  210. longitude: app.globalData.longitude || '', //经度
  211. latitude: app.globalData.latitude || '', //纬度
  212. brandId: config.brandId //集团id
  213. };
  214. let timeNow = new Date().getTime();
  215. let session = uni.getStorageSync('sessionNumber') || timeNow;
  216. let sessionTime = uni.getStorageSync('sessionTime') || timeNow;
  217. if (timeNow - sessionTime > 180000) {
  218. session = timeNow;
  219. // wx.setStorageSync('sessionNumber', session)
  220. uni.setStorage({
  221. key: "sessionNumber",
  222. data: session
  223. })
  224. } else {
  225. // wx.setStorageSync('sessionNumber', session)
  226. uni.setStorage({
  227. key: "sessionNumber",
  228. data: session
  229. })
  230. }
  231. // wx.setStorageSync('sessionTime', timeNow)
  232. uni.setStorage({
  233. key: "sessionTime",
  234. data: timeNow
  235. })
  236. data.session = data.brandUserId + '_' + session;
  237. app.globalData.session_id = data.session
  238. app.globalData.sessionTime = timeNow;
  239. // requestConfig('upload', data, true);
  240. let param = ["SEND" +
  241. "\nproject:" + "elab-marketing-system" +
  242. "\nmethod:" + 'POST' +
  243. "\npath:" + '/behavior/brandMiniWeb/upload' +
  244. "\ndestination:" + '/ws/remote/invoke' +
  245. "\n\n" + JSON.stringify(data) +
  246. "\u0000"
  247. ];
  248. app.wsSendOrder(param);//socket 消息发送
  249. },
  250. async shareToken(app) {
  251. const res = await requestConfig('sign', {
  252. customerId: app.globalData.single.id,
  253. houseId: config.houseId,
  254. userRole: 0
  255. });
  256. if (res && res.success && res.single) {
  257. app.globalData.shareToken = res.single || "";
  258. }
  259. },
  260. //此时此刻日期转化
  261. timesData: function(timestamp) {
  262. var date = new Date(timestamp);
  263. var Y = date.getFullYear() + '/';
  264. var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
  265. var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
  266. // var h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
  267. // var m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes());
  268. return Y + M + D;
  269. },
  270. //此时此刻日期转化格式
  271. dateFormat: function (timestamp) {
  272. var date = new Date(timestamp);
  273. var Y = date.getFullYear() + '年';
  274. var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
  275. var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日 ';
  276. var h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
  277. var m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
  278. var s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
  279. return Y + M + D + h + m + s;
  280. },
  281. //此时此刻日期转化格式
  282. dateFormats: function (timestamp) {
  283. var date = new Date(timestamp);
  284. var Y = date.getFullYear() + '年';
  285. var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
  286. var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日 ';
  287. return Y + M + D;
  288. },
  289. //此时此刻时间转化
  290. timestampToTime: function(timestamp) {
  291. var date = new Date(timestamp);
  292. var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
  293. var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
  294. return h + m;
  295. },
  296. formatDate:function (date, fmt) {
  297. if (/(y+)/.test(fmt)) {
  298. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  299. }
  300. let o = {
  301. 'M+': date.getMonth() + 1,
  302. 'd+': date.getDate(),
  303. 'h+': date.getHours(),
  304. 'm+': date.getMinutes(),
  305. 's+': date.getSeconds()
  306. }
  307. for (let k in o) {
  308. if (new RegExp(`(${k})`).test(fmt)) {
  309. let str = o[k] + ''
  310. fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str))
  311. }
  312. }
  313. return fmt
  314. },
  315. padLeftZero :function (str) {
  316. return ('00' + str).substr(str.length)
  317. },
  318. /**
  319. * 先从微信小程序获取当前位置的经纬度;
  320. * 再从腾讯地图依据经纬度获取当前的地理位置信息.
  321. * successBack:成功回调,包含地理位置信息
  322. * failBack:失败回调,包含失败的信息
  323. */
  324. getLocalPositionInformationFromTencent(successBack, failBack, isFirstIn, force) {
  325. const app = getApp(); //获取应用实例
  326. uni.getLocation({
  327. type: 'wgs84',
  328. success(res) {
  329. const latitude = res.latitude; //纬度,范围为 -90~90,负数表示南纬
  330. const longitude = res.longitude; //经度,范围为 -180~180,负数表示西经
  331. app.globalData.longitude = longitude;
  332. app.globalData.latitude = latitude;
  333. let getAddressUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," +
  334. longitude +
  335. "&key=AKWBZ-SVPC5-Z4WIT-Q2UOM-55O7O-76FV5&get_poi=1";
  336. wx.request({
  337. url: getAddressUrl,
  338. headers: {
  339. 'Content-Type': 'application/json'
  340. },
  341. success: async function(result) {
  342. let resultData = result.data.result;
  343. if (successBack) {
  344. successBack(resultData);
  345. }
  346. },
  347. fail: function(result) {
  348. if (failBack) {
  349. failBack(result);
  350. }
  351. }
  352. });
  353. },
  354. fail(res) {
  355. if (isFirstIn) {
  356. let para = {
  357. clkDesPage: '', //点击前往的页面名称
  358. type: 'CLK', //埋点类型
  359. clkId: 'clk_2cmina_137', //点击ID,固定
  360. clkName: "wechatauthorize-location", //点击名称
  361. clkParams: {
  362. "wx.authorize.scope": "wx.getLocation",
  363. "type": 'fail',
  364. },
  365. };
  366. util.trackRequest(para);
  367. console.log(res, 'ssssssssssssss')
  368. wx.showToast({
  369. title: '授权失败',
  370. duration: 3000,
  371. icon: 'none'
  372. });
  373. } else if (force) {
  374. wx.showToast({
  375. title: '授权失败',
  376. duration: 1500,
  377. icon: 'none'
  378. });
  379. }
  380. if (failBack) {
  381. failBack(res);
  382. }
  383. }
  384. });
  385. },
  386. /**
  387. * 获取微信地理位置信息
  388. * @param force 是否强授权
  389. * force=true: 只要调用就弹起授权弹窗
  390. * force=false: 若拒绝过授权,则不再弹起授权弹窗
  391. */
  392. getPosition(successBack, failBack, force = false) {
  393. wx.getSetting({
  394. success: (results) => {
  395. if (results.authSetting['scope.userLocation'] == undefined) { //该用户还没有弹起地理位置授权,可视为第一次进入小程序
  396. var para = {
  397. type: 'EXP', //埋点类型
  398. eventId: 'exp_2cmina_22', //点击ID,固定
  399. eventName: "diliweizhishouquan", //点击名称
  400. event_param: {
  401. "wx.authorize.scope": "wx.getLocation",
  402. },
  403. }
  404. // util.trackRequest(para);
  405. if (successBack) {
  406. successBack({
  407. firstIn: true
  408. });
  409. }
  410. } else {
  411. if (!results.authSetting['scope.userLocation']) {
  412. if (force) {
  413. wx.showModal({
  414. title: '请求授权当前位置',
  415. content: '是否开启地理位置授权,定位当前所在城市',
  416. cancelText: "下次再说",
  417. confirmText: "去开启",
  418. success: function(res) {
  419. if (res.cancel) {
  420. wx.showToast({
  421. title: '授权失败',
  422. icon: 'none',
  423. duration: 1000
  424. });
  425. if (failBack) {
  426. failBack();
  427. }
  428. } else if (res.confirm) {
  429. wx.openSetting({
  430. success: function(dataAu) {
  431. if (dataAu.authSetting[
  432. "scope.userLocation"] ==
  433. true) {
  434. //再次授权,调用wx.getLocation的API
  435. if (successBack) {
  436. successBack({
  437. firstIn: false
  438. });
  439. }
  440. } else {
  441. if (failBack) {
  442. failBack();
  443. }
  444. }
  445. },
  446. fail: function() {
  447. wx.showToast({
  448. title: '授权失败',
  449. icon: 'none',
  450. duration: 1000
  451. });
  452. }
  453. })
  454. }
  455. }
  456. })
  457. } else {
  458. console.log('上次登录的时候拒绝了授权')
  459. if (failBack) {
  460. failBack();
  461. }
  462. }
  463. } else {
  464. console.log('上次登录的时候允许了授权')
  465. if (successBack) {
  466. successBack({
  467. firstIn: false
  468. });
  469. }
  470. }
  471. }
  472. }
  473. })
  474. },
  475. /**
  476. * 检查目标城市是否有效;
  477. * 将目标城市和上次选择的城市进行比较;
  478. * currentCityName:当前定位的城市名称
  479. * currentCityCode:当前定位的城市code
  480. */
  481. async compareCurrentCityWithHistoryCity(currentCityName, currentCityCode, successBack, failBack, firstInAPP) {
  482. const that = this;
  483. const app = getApp();
  484. let param = {
  485. cityName: currentCityName,
  486. brandId: config.brandId,
  487. customerId: app.globalData.single.id || '',
  488. simplify: true
  489. };
  490. const res = await requestConfig('queryCityData', param);
  491. if (res.success && res.single) {
  492. if (res.single.inCityData) {
  493. if (!res.single.currentCity) {
  494. that.addCustomerCity(1, currentCityName, currentCityCode, successBack, failBack);
  495. } else if (res.single.currentCity.cityName == currentCityName) { //定位的城市和上次选择的城市一样
  496. app.globalData.selectCityCode = res.single.currentCity.cityCode;
  497. app.globalData.selectCityName = res.single.currentCity.cityName;
  498. if (successBack) {
  499. successBack();
  500. }
  501. } else {
  502. let currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[
  503. getCurrentPages().length - 1]
  504. .$vm : null;
  505. let currentRoute = currPage['route'];
  506. if (!app.globalData.cityChangeTips && currentRoute !=
  507. '/subPackage/pages/addressModule/addressModule') {
  508. app.globalData.cityChangeTips = true;
  509. /*wx.showModal({
  510. title: '是否切换城市',
  511. content: '您当前定位城市与产品系列城市不一致,是否切换至定位城市',
  512. cancelText:"取消",
  513. confirmText:"切换",
  514. success: function (modelRes) {
  515. if (modelRes.cancel) {//点击取消
  516. if(failBack){
  517. failBack();
  518. }
  519. } else if (modelRes.confirm) {//点击切换
  520. that.addCustomerCity(1,currentCityName,currentCityCode,successBack,failBack);
  521. }
  522. },
  523. })*/
  524. if (successBack) {
  525. successBack(true);
  526. }
  527. } else {
  528. if (failBack) {
  529. failBack();
  530. }
  531. }
  532. }
  533. } else {
  534. /* let re = await requestConfig('addCustomerCity',{
  535. city:currentCityName,
  536. brandId:config.brandId,
  537. customerId:app.globalData.single.id,
  538. cityCode:currentCityCode,
  539. citySource:1
  540. });*/
  541. /* app.globalData.selectCityCode = currentCityCode;
  542. app.globalData.selectCityName = currentCityName;*/
  543. if (firstInAPP) {
  544. wx.showToast({
  545. title: '定位城市暂未开放,先看看其他城市吧',
  546. duration: 2500,
  547. icon: 'none'
  548. });
  549. }
  550. if (failBack) {
  551. failBack();
  552. }
  553. }
  554. } else {
  555. wx.showToast({
  556. title: '网络连接出现问题',
  557. duration: 1500,
  558. icon: 'none'
  559. });
  560. if (failBack) {
  561. failBack();
  562. }
  563. }
  564. },
  565. /**
  566. * 添加客户城市位置
  567. * type:
  568. * 1:用户授权城市;
  569. * 2:选择定位城市.
  570. * currentCityName:当前城市名
  571. * currentCityCode:当前城市code
  572. */
  573. async addCustomerCity(type, currentCityName, currentCityCode, successBack, failBack) {
  574. const app = getApp(); //获取应用实例
  575. let re = await requestConfig('addCustomerCity', {
  576. city: currentCityName,
  577. brandId: config.brandId,
  578. customerId: app.globalData.single.id,
  579. cityCode: currentCityCode,
  580. citySource: type
  581. });
  582. if (re.success) {
  583. if (type == 1) {
  584. /*wx.showToast({
  585. title:`已为您切换至${currentCityName}!`,
  586. icon:'none',
  587. duration:1500
  588. });*/
  589. }
  590. app.globalData.selectCityCode = currentCityCode;
  591. app.globalData.selectCityName = currentCityName;
  592. if (successBack) {
  593. successBack();
  594. }
  595. } else {
  596. if (failBack) {
  597. failBack();
  598. }
  599. }
  600. },
  601. /**
  602. * 精确处理小数点 为了解决Elab房贷计算器跨平台浮点运算差值,写了此套算法
  603. * @param value 要处理的布尔数值
  604. * @param length 精确的小数点的位数
  605. * @param accurate 是否四舍五入
  606. * @returns {string}
  607. */
  608. handlePoint(value, length, accurate = false) {
  609. if (value.toString().split('.')[1] && (value.toString().split('.')[1]).length > length) {
  610. let startValue = value.toString().split('.')[0];
  611. let endValue = value.toString().split('.')[1];
  612. if (accurate) {
  613. let markValue = parseInt(endValue.toString().slice(length, length + 1));
  614. if (markValue >= 5) {
  615. endValue = endValue.toString().slice(0, length);
  616. endValue = parseInt(endValue) + 1;
  617. if (endValue.toString().length > length) {
  618. startValue = parseInt(startValue) + 1;
  619. endValue = endValue.toString().slice(1, length + 1);
  620. } else if (endValue.toString().length < length) {
  621. let markLength = length - endValue.toString().length;
  622. let str = '';
  623. for (let i = 0, len = markLength; i < len; i++) {
  624. str += '0';
  625. }
  626. endValue = str + endValue;
  627. }
  628. } else {
  629. endValue = endValue.toString().slice(0, length);
  630. }
  631. } else {
  632. endValue = endValue.toString().slice(0, length);
  633. }
  634. /*if (parseInt(endValue) == 0) {
  635. value = startValue;
  636. } else {
  637. value = startValue + '.' + endValue;
  638. }*/
  639. value = startValue + '.' + endValue;
  640. }
  641. return value;
  642. },
  643. getPageTheme(val){
  644. if (val ==-1){
  645. //浅色模式,白底黑字
  646. return {
  647. textColor1:'rgba(18,18,18,1)', //主文字颜色
  648. textColor2:'rgba(18,18,18,0.5)', //副文字颜色
  649. textColor3:'rgba(18,18,18,0.2)', //副文字颜色
  650. bgColor:'rgba(255,255,255,1)', //主背景颜色
  651. bgColor2:'rgba(255,255,255,1)', //副背景颜色
  652. bgColor3:'rgba(255,255,255,1)', //副背景颜色
  653. }
  654. }else if (val ==1){
  655. //深色模式,黑底白字
  656. return {
  657. textColor1:'rgba(255,255,255,1)',
  658. textColor2:'rgba(255,255,255,0.5)',
  659. textColor3:'rgba(255,255,255,0.2)',
  660. bgColor:'rgba(18,18,18,1)',
  661. bgColor2:'rgba(255,255,255,0.1)',
  662. bgColor3:'rgba(255,255,255,0.3)',
  663. }
  664. }else{
  665. //浅色模式,白底黑字,默认浅色模式
  666. return {
  667. textColor1:'rgba(18,18,18,1)', //主文字颜色
  668. textColor2:'rgba(18,18,18,0.5)', //副文字颜色
  669. textColor3:'rgba(18,18,18,0.2)', //副文字颜色
  670. bgColor:'rgba(255,255,255,1)', //主背景颜色
  671. bgColor2:'rgba(255,255,255,1)', //副背景颜色
  672. bgColor3:'rgba(255,255,255,1)', //副背景颜色
  673. }
  674. }
  675. },
  676. /**
  677. * 加密参数
  678. * @param content
  679. * @returns {string}
  680. * @constructor
  681. */
  682. AES_encrypt(content) {
  683. content = JSON.stringify(content);
  684. let param = CryptoJS.enc.Utf8.parse(content);
  685. let _key = CryptoJS.enc.Utf8.parse(keys);
  686. let _iv = CryptoJS.enc.Utf8.parse(iv);
  687. let encrypted = CryptoJS.AES.encrypt(param, _key, {
  688. mode: CryptoJS.mode.CBC,
  689. padding: CryptoJS.pad.Pkcs7,
  690. iv: _iv,
  691. });
  692. return encrypted.ciphertext.toString();
  693. },
  694. /**
  695. * 解密参数
  696. * @param content
  697. * @returns {string}
  698. * @constructor
  699. */
  700. AES_decrypt(content) {
  701. let receive = CryptoJS.enc.Hex.parse(content);
  702. receive = CryptoJS.enc.Base64.stringify(receive);
  703. let _key = CryptoJS.enc.Utf8.parse(keys);
  704. let _iv = CryptoJS.enc.Utf8.parse(iv);
  705. var decrypt = CryptoJS.AES.decrypt(receive, _key, {
  706. mode: CryptoJS.mode.CBC,
  707. padding: CryptoJS.pad.Pkcs7,
  708. iv:_iv
  709. });
  710. console.log("555555555555555",decrypt);
  711. return decrypt.toString(CryptoJS.enc.Utf8);
  712. },
  713. hexToRgba(hex, opacity) {
  714. if (!hex||!opacity){
  715. return hex
  716. }
  717. let RGBA;
  718. if (hex.includes('#')&&hex.length==7){
  719. RGBA = "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," +
  720. parseInt("0x" + hex.slice(5, 7)) + "," + opacity + ")";
  721. }else if (hex.includes('rgb(')){
  722. var values = hex
  723. .replace(/rgb?\(/, '')
  724. .replace(/\)/, '')
  725. .replace(/[\s+]/g, '')
  726. .split(',')
  727. return `rgba(${values[0]},${values[1]},${values[2]},${opacity})`
  728. }else if(hex.includes('rgba(')){
  729. var values = hex
  730. .replace(/rgba?\(/, '')
  731. .replace(/\)/, '')
  732. .replace(/[\s+]/g, '')
  733. .split(',')
  734. return `rgba(${values[0]},${values[1]},${values[2]},${opacity})`
  735. }else{
  736. return hex
  737. }
  738. return RGBA
  739. },
  740. getHexColor(color) {
  741. var values = color
  742. .replace(/rgba?\(/, '')
  743. .replace(/\)/, '')
  744. .replace(/[\s+]/g, '')
  745. .split(',')
  746. var a = parseFloat(values[3] || 1),
  747. r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
  748. g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
  749. b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
  750. return '#' +
  751. ('0' + r.toString(16)).slice(-2) +
  752. ('0' + g.toString(16)).slice(-2) +
  753. ('0' + b.toString(16)).slice(-2)
  754. },
  755. /**
  756. * 查询当前的城市
  757. * @returns {Promise<void>}
  758. */
  759. async querySelectCity() {
  760. var app = getApp(); //获取应用实例;
  761. if (app.globalData.selectCityName) {
  762. this.currentSelectCity = app.globalData.selectCityName;
  763. this.navbar.currentSelectCity = app.globalData.selectCityName;
  764. if(this.hasOwnProperty('cityName')){
  765. this.cityName = app.globalData.selectCityName;
  766. }
  767. }
  768. else{
  769. let cityRequestData = {
  770. brandId: config.brandId,
  771. customerId: (app.globalData.single && app.globalData.single.id) ? app.globalData.single.id : '',
  772. simplify: false,
  773. };
  774. const res = await requestConfig('queryCityData', cityRequestData, true);
  775. if (res.success && res.single && res.single.currentCity) {
  776. let mrak = false;
  777. for (let item of res.single.belongCityList) {
  778. if (item.cityName == res.single.currentCity.cityName || res.single.currentCity.cityCode ==
  779. item.cityCode) {
  780. mrak = true;
  781. break;
  782. }
  783. }
  784. console.log("mrakindex:" + mrak + app.globalData.defaultProductCityName);
  785. if (!mrak) { //当前所处城市不是集团所属城市时,取默认城市(初始化时获取默认城市的值)
  786. this.currentSelectCity = app.globalData.defaultProductCityName;
  787. this.navbar.currentSelectCity = app.globalData.defaultProductCityName;
  788. app.globalData.selectCityName = app.globalData.defaultProductCityName;
  789. }
  790. else{
  791. this.currentSelectCity = res.single.currentCity.cityName;
  792. this.navbar.currentSelectCity = res.single.currentCity.cityName;
  793. app.globalData.selectCityCode = res.single.currentCity.cityCode;
  794. app.globalData.selectCityName = res.single.currentCity.cityName;
  795. }
  796. } else { //不存在当前所属城市时,则取默认城市
  797. // #ifdef H5
  798. //如果不存在默认城市数据,有可能是接口还没返回,所以需要再次请求下数据
  799. if(!app.globalData.defaultProductCityName){
  800. await app.queryCityInfo()
  801. }
  802. // #endif
  803. this.currentSelectCity = app.globalData.defaultProductCityName;
  804. this.navbar.currentSelectCity = app.globalData.defaultProductCityName;
  805. app.globalData.selectCityName = app.globalData.defaultProductCityName;
  806. }
  807. }
  808. if(this.hasOwnProperty('cityName')){
  809. this.cityName = app.globalData.selectCityName;
  810. }
  811. if(this.hasOwnProperty('selectCityCode')){
  812. this.selectCityCode = app.globalData.selectCityCode;
  813. }
  814. },
  815. // 置地老业主认证
  816. async newAuthentication4Zd(pageId,fn,city='重庆') {
  817. var app = getApp(); //获取应用实例;
  818. if(pageId && pageId == '4213'){//需要修改为商城页面的实际页面id才能上线 4213
  819. app.checkAuthTotal(2, async(checkRes) => {
  820. this.showPhoneModel = checkRes.showPhoneModel;
  821. if (!checkRes.showPhoneModel) {
  822. var {single: { id = ''} = {}} = app.globalData;
  823. let data = {
  824. brandId: config.brandId,
  825. id: id,//用户id
  826. mobile: app.globalData.phone || "",
  827. city: city,
  828. };
  829. const res = await requestConfig('newAuthentication4Zd', data, true);
  830. if (res && res.success && res.list && res.list.length>0) {//是对应城市下的老业主
  831. console.log('***是对应城市下的老业主***', res.list);
  832. fn && typeof fn == 'function' && fn();
  833. }
  834. else{
  835. uni.showToast({
  836. title: '不是'+city+'区域老业主,不能参加活动',
  837. icon: 'none',
  838. duration: 1500,
  839. });
  840. return false;
  841. }
  842. }
  843. }, true);
  844. }
  845. else{
  846. fn && typeof fn == 'function' && fn();
  847. }
  848. },
  849. // websocket 返回的数据转义成object类型
  850. parseWSData(data) {
  851. if (data.startsWith("a[")) {
  852. let endLength = data.length - 6;
  853. let textData = data.substr(3, endLength);
  854. let request = textData.split("\\n\\n");
  855. let headerBody = request[0];
  856. let body = request[1];
  857. let headerArray = headerBody.split("\\n");
  858. let header = {};
  859. for (let i = 1; i < headerArray.length; i++) {
  860. let body = headerArray[i];
  861. let resultBody = body.split(":");
  862. header[resultBody[0]] = resultBody[1];
  863. }
  864. let result = {};
  865. result["command"] = headerArray[0];
  866. result["header"] = header;
  867. if (body) {
  868. try {
  869. result["body"] = JSON.parse(body.replaceAll("\\", ""));
  870. } catch (e) {
  871. result["body"] = body;
  872. }
  873. }
  874. return result;
  875. }
  876. return data;
  877. }
  878. };
  879. module.exports = util;