util.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. function getdomain() {
  2. var app = getApp();
  3. var new_domain = app.siteInfo.uniacid + '_' + app.siteInfo.siteroot;
  4. var api = new_domain;
  5. return api;
  6. }
  7. function api() {
  8. var api = 'https://mall.shiziyu888.com/dan/';
  9. return api;
  10. }
  11. function check_login() {
  12. let token = wx.getStorageSync('token');
  13. let member_id = wx.getStorageSync('member_id');
  14. if (token && member_id != undefined && member_id.length > 0) {
  15. return true;
  16. } else {
  17. return false;
  18. }
  19. }
  20. /**
  21. * 检查登录状态
  22. * return promise [Boolean]
  23. */
  24. function check_login_new() {
  25. let token = wx.getStorageSync('token');
  26. let member_id = wx.getStorageSync('member_id');
  27. return new Promise(function (resolve, reject) {
  28. wx.checkSession({
  29. success() {
  30. console.log('checkSession 未过期');
  31. if (token && member_id != undefined && member_id.length > 0) {
  32. resolve(true)
  33. } else {
  34. resolve(false)
  35. }
  36. },
  37. fail() {
  38. console.log('checkSession 过期');
  39. resolve(false)
  40. }
  41. })
  42. })
  43. }
  44. /**
  45. * 检查跳转权限控制
  46. * return [Boolean]
  47. */
  48. function checkRedirectTo(url, needAuth) {
  49. let status = false;
  50. if (needAuth) {
  51. const needAuthUrl = [
  52. "/lionfish_comshop/moduleA/groupCenter/apply",
  53. "/lionfish_comshop/pages/supply/apply",
  54. "/lionfish_comshop/pages/user/charge",
  55. "/lionfish_comshop/pages/order/index",
  56. "/lionfish_comshop/moduleA/solitaire/index",
  57. "/lionfish_comshop/moduleA/vip/upgrade",
  58. "lionfish_comshop/moduleA/coupon/getCoupon"
  59. ];
  60. let idx = needAuthUrl.indexOf(url);
  61. if (idx !== -1) status = true;
  62. }
  63. return status;
  64. }
  65. /**
  66. * s_link: 回调链接
  67. * type:跳转方式 0 redirectTo, 1 switchTab
  68. */
  69. function login(s_link, type = 0) {
  70. var app = getApp();
  71. var share_id = wx.getStorageSync('share_id');
  72. if (share_id == undefined) {
  73. share_id = '0';
  74. }
  75. wx.login({
  76. success: function(res) {
  77. if (res.code) {
  78. console.log(res.code);
  79. app.util.request({
  80. 'url': 'entry/wxapp/user',
  81. 'data': {
  82. controller: 'user.applogin',
  83. 'code': res.code
  84. },
  85. dataType: 'json',
  86. success: function(res) {
  87. console.log(res);
  88. wx.setStorage({
  89. key: "token",
  90. data: res.data.token
  91. })
  92. wx.getUserInfo({
  93. success: function(msg) {
  94. var userInfo = msg.userInfo
  95. wx.setStorage({
  96. key: "userInfo",
  97. data: userInfo
  98. })
  99. console.log(msg.userInfo);
  100. app.util.request({
  101. 'url': 'entry/wxapp/user',
  102. 'data': {
  103. controller: 'user.applogin_do',
  104. 'token': res.data.token,
  105. share_id: share_id,
  106. nickName: msg.userInfo.nickName,
  107. avatarUrl: msg.userInfo.avatarUrl,
  108. encrypteddata: msg.encryptedData,
  109. iv: msg.iv
  110. },
  111. method: 'post',
  112. dataType: 'json',
  113. success: function(res) {
  114. wx.setStorage({
  115. key: "member_id",
  116. data: res.data.member_id
  117. })
  118. wx.showToast({
  119. title: '资料已更新',
  120. icon: 'success',
  121. duration: 2000,
  122. success: function() {
  123. //s_link
  124. if (s_link && s_link.length > 0){
  125. if (type == 1) {
  126. wx.switchTab({
  127. url: s_link,
  128. })
  129. } else {
  130. wx.redirectTo({
  131. url: s_link
  132. })
  133. }
  134. }
  135. }
  136. })
  137. }
  138. })
  139. },
  140. fail: function(msg) {
  141. // console.log(msg);
  142. }
  143. })
  144. }
  145. });
  146. } else {
  147. //console.log('获取用户登录态失败!' + res.errMsg)
  148. }
  149. }
  150. })
  151. }
  152. function login_prosime(needPosition=true, userInfo={}) {
  153. return new Promise(function (resolve, reject) {
  154. getCode().then(token=>{
  155. wxGetUserInfo(needPosition, token, userInfo).then(res=>{
  156. resolve(res)
  157. }).catch(res => {
  158. console.log(res);
  159. reject(res)
  160. });
  161. })
  162. })
  163. }
  164. function getCode() {
  165. return new Promise(function (resolve, reject) {
  166. var app = getApp();
  167. wx.login({
  168. success: function (res) {
  169. if (res.code) {
  170. console.log(res.code);
  171. app.util.request({
  172. url: 'entry/wxapp/user',
  173. data: {
  174. controller: 'user.applogin',
  175. code: res.code
  176. },
  177. dataType: 'json',
  178. success: function (res) {
  179. resolve(res.data.token);
  180. wx.setStorage({
  181. key: "token",
  182. data: res.data.token
  183. })
  184. }
  185. });
  186. } else {
  187. reject(res.errMsg)
  188. }
  189. }
  190. })
  191. })
  192. }
  193. function wxGetUserInfo(needPosition, token, userInfo) {
  194. return new Promise(function (resolve, reject) {
  195. var app = getApp();
  196. var share_id = wx.getStorageSync('share_id');
  197. if (share_id == undefined) { share_id = '0'; }
  198. var community = wx.getStorageSync('community');
  199. var community_id = community && (community.communityId || 0);
  200. community && wx.setStorageSync('lastCommunity', community);
  201. app.util.request({
  202. url: 'entry/wxapp/user',
  203. data: {
  204. controller: 'user.applogin_do',
  205. token,
  206. share_id: share_id,
  207. nickName: userInfo.nickName,
  208. avatarUrl: userInfo.avatarUrl,
  209. community_id
  210. },
  211. method: 'post',
  212. dataType: 'json',
  213. success: function (res) {
  214. let isblack = res.data.isblack || 0;
  215. let isparse_formdata = res.data.isparse_formdata || 0;
  216. if (isblack == 1) {
  217. app.globalData.isblack = 1;
  218. wx.removeStorageSync('token');
  219. wx.switchTab({
  220. url: '/lionfish_comshop/pages/index/index',
  221. })
  222. } else if (isparse_formdata == 1) {
  223. wx.setStorageSync('isparse_formdata', 1);
  224. wx.setStorage({
  225. key: "member_id",
  226. data: res.data.member_id
  227. })
  228. wx.reLaunch({
  229. url: '/lionfish_comshop/pages/index/index',
  230. })
  231. } else {
  232. wx.setStorage({
  233. key: "member_id",
  234. data: res.data.member_id
  235. })
  236. console.log('needPosition', needPosition)
  237. needPosition && getCommunityInfo();
  238. }
  239. resolve(res);
  240. },
  241. fail: (err)=>{
  242. reject(err);
  243. }
  244. })
  245. })
  246. }
  247. function stringToJson(data) {
  248. return JSON.parse(data);
  249. }
  250. function jsonToString(data) {
  251. return JSON.stringify(data);
  252. }
  253. function imageUtil(e) {
  254. var imageSize = {};
  255. var originalWidth = e.detail.width; //图片原始宽
  256. var originalHeight = e.detail.height; //图片原始高
  257. var originalScale = originalHeight / originalWidth; //图片高宽比
  258. //获取屏幕宽高
  259. wx.getSystemInfo({
  260. success: function(res) {
  261. var windowWidth = res.windowWidth;
  262. var windowHeight = res.windowHeight;
  263. var windowscale = windowHeight / windowWidth; //屏幕高宽比
  264. //console.log('windowWidth: ' + windowWidth)
  265. //console.log('windowHeight: ' + windowHeight)
  266. if (originalScale < windowscale) { //图片高宽比小于屏幕高宽比
  267. //图片缩放后的宽为屏幕宽
  268. imageSize.imageWidth = windowWidth;
  269. imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth;
  270. } else { //图片高宽比大于屏幕高宽比
  271. //图片缩放后的高为屏幕高
  272. imageSize.imageHeight = windowHeight;
  273. imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight;
  274. }
  275. }
  276. })
  277. //console.log('缩放后的宽: ' + imageSize.imageWidth)
  278. //console.log('缩放后的高: ' + imageSize.imageHeight)
  279. return imageSize;
  280. }
  281. const formatTime = date => {
  282. const year = date.getFullYear()
  283. const month = date.getMonth() + 1
  284. const day = date.getDate()
  285. const hour = date.getHours()
  286. const minute = date.getMinutes()
  287. const second = date.getSeconds()
  288. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  289. }
  290. const formatNumber = n => {
  291. n = n.toString()
  292. return n[1] ? n : '0' + n
  293. }
  294. //获取社区存本地
  295. const getCommunityInfo = function (param = {}) {
  296. // let community = wx.getStorageSync('community');
  297. let app = getApp();
  298. // let that = this;
  299. var token = wx.getStorageSync('token');
  300. return new Promise(function (resolve, reject) {
  301. // if (!community){
  302. app.util.request({
  303. url: 'entry/wxapp/index',
  304. data: {
  305. controller: 'index.load_history_community',
  306. token: token
  307. },
  308. dataType: 'json',
  309. success: function (res) {
  310. if (res.data.code == 0) {
  311. let history_communities = res.data.list;
  312. if (Object.keys(history_communities).length > 0 || history_communities.communityId != 0){
  313. wx.setStorageSync('community', history_communities);
  314. app.globalData.community = history_communities;
  315. resolve(history_communities);
  316. } else {
  317. resolve('');
  318. }
  319. } else if (res.data.code == 1){
  320. console.log(param)
  321. if (check_login() && param.communityId === void 0){
  322. wx.redirectTo({
  323. url: '/lionfish_comshop/pages/position/community',
  324. })
  325. resolve('');
  326. } else {
  327. resolve(param);
  328. }
  329. } else {
  330. // 未登录
  331. resolve('');
  332. }
  333. }
  334. })
  335. // } else {
  336. // resolve('')
  337. // }
  338. })
  339. }
  340. /**
  341. * 通过社区id获取社区信息
  342. * 单社区控制
  343. * data:该id社区信息
  344. * open_danhead_model:是否开启单社区
  345. * default_head_info: 自定义单社区信息
  346. */
  347. const getCommunityById = function (community_id){
  348. return new Promise(function (resolve, reject) {
  349. getApp().util.request({
  350. url: 'entry/wxapp/index',
  351. data: {
  352. controller: 'index.get_community_info',
  353. community_id
  354. },
  355. dataType: 'json',
  356. success: function (res) {
  357. if(res.data.code==0) resolve(res.data);
  358. }
  359. })
  360. })
  361. }
  362. /**
  363. * 历史社区
  364. */
  365. const addhistory = function (community, isNew = false) {
  366. var community_id = community.communityId;
  367. console.log('addhistory');
  368. var token = wx.getStorageSync('token');
  369. getApp().util.request({
  370. url: 'entry/wxapp/index',
  371. data: {
  372. controller: 'index.addhistory_community',
  373. community_id,
  374. token: token
  375. },
  376. dataType: 'json',
  377. success: function (res) {
  378. if (isNew) {
  379. console.log('新人 社区')
  380. app.util.request({
  381. url: 'entry/wxapp/index',
  382. data: {
  383. controller: 'index.get_community_info',
  384. community_id: community_id
  385. },
  386. dataType: 'json',
  387. success: function (result) {
  388. if (result.data.code == 0) {
  389. let community = result.data.data;
  390. app.globalData.community = community;
  391. app.globalData.changedCommunity = true;
  392. wx.setStorage({ key: "community", data: community })
  393. }
  394. }
  395. })
  396. }
  397. }
  398. })
  399. }
  400. /**
  401. * 获取wx的版本号
  402. */
  403. const getWxVersion = function () {
  404. return wx.getSystemInfoSync().SDKVersion
  405. }
  406. /**
  407. * 微信版本比较, v1 大于 v2,返回1,否则返回 0
  408. * @param {Object} v1
  409. * @param {Object} v2
  410. */
  411. const wxCompareVersion = function (v1, v2) {
  412. v1 = v1.split('.')
  413. v2 = v2.split('.')
  414. const len = Math.max(v1.length, v2.length)
  415. while (v1.length < len) {
  416. v1.push('0')
  417. }
  418. while (v2.length < len) {
  419. v2.push('0')
  420. }
  421. for (let i = 0; i < len; i++) {
  422. const num1 = parseInt(v1[i])
  423. const num2 = parseInt(v2[i])
  424. if (num1 > num2) {
  425. return 1
  426. } else if (num1 < num2) {
  427. return -1
  428. }
  429. }
  430. return 0
  431. }
  432. const addCart = function(option) {
  433. return new Promise((resolve, reject)=>{
  434. let token = wx.getStorageSync('token');
  435. getApp().util.request({
  436. url: 'entry/wxapp/user',
  437. data: {
  438. controller: 'car.add',
  439. token,
  440. ...option
  441. },
  442. dataType: 'json',
  443. method: 'POST',
  444. success: function(res) {
  445. if (res.data.code == 7) {
  446. let { has_image, pop_vipmember_buyimage } = res.data;
  447. if(has_image==1&&pop_vipmember_buyimage) {
  448. res.showVipModal = 1;
  449. res.data.pop_vipmember_buyimage = pop_vipmember_buyimage;
  450. resolve(res)
  451. } else {
  452. resolve(res)
  453. }
  454. } else {
  455. resolve(res)
  456. }
  457. },
  458. fail: function(res) {
  459. reject(res)
  460. }
  461. })
  462. })
  463. }
  464. const filterTel = function(shipping_tel) {
  465. if(shipping_tel) {
  466. var pat=/(\d{7})\d*(\d{0})/;
  467. return shipping_tel.replace(pat,'$1****$2');
  468. }
  469. return shipping_tel;
  470. }
  471. /*函数节流*/
  472. function throttle(fn, interval) {
  473. var enterTime = 0;//触发的时间
  474. var gapTime = interval || 300 ;//间隔时间,如果interval不传,则默认300ms
  475. return function() {
  476. var context = this;
  477. var backTime = new Date();//第一次函数return即触发的时间
  478. if (backTime - enterTime > gapTime) {
  479. fn.call(context,arguments);
  480. enterTime = backTime;//赋值给第一次触发的时间,这样就保存了第二次触发的时间
  481. }
  482. };
  483. }
  484. /*函数防抖*/
  485. function debounce(fn, interval) {
  486. var timer;
  487. var gapTime = interval || 1000;//间隔时间,如果interval不传,则默认1000ms
  488. return function() {
  489. clearTimeout(timer);
  490. var context = this;
  491. var args = arguments;//保存此处的arguments,因为setTimeout是全局的,arguments不是防抖函数需要的。
  492. timer = setTimeout(function() {
  493. fn.call(context,args);
  494. }, gapTime);
  495. };
  496. }
  497. const fileSystem = wx.getFileSystemManager()
  498. /**
  499. * 缓存图片
  500. */
  501. const getStorageImage = (web_image) => {
  502. return new Promise((resolve, reject)=>{
  503. let webImages = wx.getStorageSync('webImages') || []
  504. let webImage = webImages.find(y => y.web_path === web_image)
  505. if (webImage) {
  506. try {
  507. fileSystem.accessSync(webImage.local_path)
  508. resolve(webImage.local_path)
  509. return webImage.local_path
  510. } catch (e) {
  511. // let webImageIdx = webImages.findIndex(y => y.web_path === web_image)
  512. // webImages.splice(webImageIdx, 1)
  513. wx.setStorageSync('webImages', webImages)
  514. }
  515. resolve(web_image)
  516. } else {
  517. wx.downloadFile({
  518. url: web_image,
  519. success(res) {
  520. if (res.statusCode === 200) {
  521. let filePath = res.tempFilePath
  522. // let webImageStorage = wx.getStorageSync('webImages') || []
  523. let webImageStorage = []
  524. wx.getImageInfo({
  525. src: filePath,
  526. success (ret) {
  527. let windowWidth = getApp().globalData.systemInfo.windowWidth || 375;
  528. let h = ret.height;
  529. let w = ret.width;
  530. let height = h*windowWidth/w;
  531. let storage = {
  532. web_path: web_image,
  533. local_path: filePath,
  534. height,
  535. last_time: Date.parse(new Date()),
  536. }
  537. webImageStorage.push(storage)
  538. wx.setStorageSync('webImages', webImageStorage)
  539. resolve(web_image)
  540. },
  541. fail(err) {
  542. console.log(err)
  543. reject()
  544. }
  545. })
  546. } else {
  547. reject()
  548. }
  549. },
  550. fail() {
  551. reject()
  552. }
  553. })
  554. }
  555. // return web_image
  556. })
  557. }
  558. module.exports = {
  559. formatTime: formatTime,
  560. login: login,
  561. check_login: check_login,
  562. api: api,
  563. getdomain: getdomain,
  564. imageUtil: imageUtil,
  565. jsonToString: jsonToString,
  566. stringToJson: stringToJson,
  567. login_prosime,
  568. getCommunityInfo,
  569. check_login_new,
  570. checkRedirectTo,
  571. getCommunityById,
  572. addhistory,
  573. wxGetUserInfo,
  574. getWxVersion,
  575. wxCompareVersion,
  576. addCart,
  577. filterTel,
  578. throttle,
  579. debounce,
  580. getStorageImage
  581. }