base.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. const coreServer = $("#coreServer").val();
  2. const isPC = ($(window).width() > 768);
  3. let globalUserData = '';
  4. let GLOBAL_TOKEN = 'X-Token';
  5. let GLOBAL_USER_ID = 0; // 用户Id
  6. let GLOBAL_USER_IDENTITY = 0;//2-会员机构;3-供应商;4-普通机构
  7. let GLOBAL_SHOP_ID = 0; // 供应商Id
  8. let GLOBAL_VIP_FLAG = 0; // 超级会员标记
  9. let GLOBAL_CLUB_TYPE = 0; // 会员类型 1 医美机构 2 胜美机构
  10. let IDENTITY = 0; // 用户标记
  11. let isForbidTabs = true; //控制菜单
  12. let isShopIsOrder = false; //控制菜单
  13. if(localStorage.getItem('userInfo')){
  14. globalUserData = JSON.parse(localStorage.getItem('userInfo'));
  15. GLOBAL_TOKEN = globalUserData.token;
  16. GLOBAL_USER_ID = globalUserData.userId*1;
  17. GLOBAL_USER_IDENTITY = globalUserData.userIdentity*1;
  18. IDENTITY = globalUserData.userIdentity*1;
  19. GLOBAL_VIP_FLAG = globalUserData.vipFlag;
  20. GLOBAL_SHOP_ID = globalUserData.shopId*1;
  21. GLOBAL_CLUB_TYPE = globalUserData.firstClubType ? globalUserData.firstClubType : null;
  22. if (GLOBAL_USER_ID === 5261 || GLOBAL_USER_ID === 10947 || GLOBAL_USER_ID === 11579) {
  23. GLOBAL_USER_IDENTITY = 1;
  24. GLOBAL_VIP_FLAG = 1;
  25. IDENTITY = 1;
  26. }else if(GLOBAL_CLUB_TYPE === 1){
  27. IDENTITY = 5;
  28. }
  29. if(globalUserData.listingFee === 1){
  30. isForbidTabs = false;
  31. }
  32. if(globalUserData){
  33. isShopIsOrder = globalUserData.shopIsOrder;
  34. }
  35. } else {
  36. // const pathname = window.location.pathname;
  37. // const weChatLoginFlag = (Number(getBaseCookie("weChatAutoLogin")) === 1 || Number(getBaseCookie("weChatAutoLogin")) === 2);
  38. // if(pathname.indexOf('/product/auth/') === -1 && !weChatLoginFlag ){
  39. // const userAgent = navigator.userAgent.toLowerCase();
  40. // const isWechatLogin = window.location.href.indexOf('isDataBase') !== -1
  41. // if (userAgent.match(/MicroMessenger/i) && !isWechatLogin) {
  42. // // 微信浏览器自动授权登录
  43. // var urlForWeChat = 'https://www.caimei365.com/we_chat/redirect_uri.html';
  44. // $.get(coreServer+'/user/login/auth/link?mode=1&redirectUri='+urlForWeChat, function(r){
  45. // if(r.code===0 && r.data){
  46. // setBaseCookie("weChatAutoLogin", 1);
  47. // setBeforeUrl();
  48. // window.location.href = r.data;
  49. // }
  50. // });
  51. // }
  52. // }
  53. }
  54. // 头部
  55. const globalHead = new Vue({
  56. el: '#globalHead',
  57. data: {
  58. loginStatus: false,
  59. userData: {},
  60. classify: [],
  61. headCart: {
  62. cartList: [],
  63. cartCount: 0,
  64. productCount: 0,
  65. priceTotal: 0
  66. },
  67. noticeNum: 0,
  68. shopId: '',
  69. userIdentity: '',
  70. articleType: '',
  71. isFiexd: false,
  72. classifyIndex: 1,
  73. supplierLinks: [
  74. {
  75. title: '美业参谋',
  76. link: '/supplier/attraction.html',
  77. },
  78. {
  79. title: '供应商协议',
  80. link: '/help/1007.html',
  81. },
  82. {
  83. title: '商家登录',
  84. link: '/supplierlogin.html',
  85. },
  86. {
  87. title: '隐私政策',
  88. link: '/help/1013.html',
  89. },
  90. {
  91. title: '入驻流程',
  92. link: '/help/1044.html',
  93. },
  94. ], // 供应商链接
  95. activeLinks: [],
  96. },
  97. watch: {
  98. isFiexd: function (nVal, oVal) {
  99. // 防止跳动
  100. // if(nVal && isPC){
  101. // $("body").css('paddingTop', $("#globalHead").height() + "px");
  102. // }else{
  103. // $("body").css('paddingTop', "0px");
  104. // }
  105. },
  106. loginStatus: {
  107. handler(val) {
  108. if (val) {
  109. this.activeLinks = this.supplierLinks.filter((i, index) => index !== 2)
  110. } else {
  111. this.activeLinks = this.supplierLinks
  112. }
  113. },
  114. deep: true,
  115. immediate: true
  116. }
  117. },
  118. methods: {
  119. changeClassify: function (value) {
  120. this.classifyIndex = value;
  121. },
  122. // 初始化分类菜单效果
  123. initClassufyTab: function () {
  124. if (isPC) {
  125. setTimeout(function () {
  126. $('#mainClassify').slide({
  127. mainCell: ".clsCon",
  128. titCell: ".clsTab a",
  129. trigger: "mouseover"
  130. });
  131. $('#mainClassify_1').slide({
  132. mainCell: ".tabItem_right",
  133. titCell: ".tabItem_lift a",
  134. trigger: "mouseover"
  135. });
  136. $('#mainClassify_2').slide({
  137. mainCell: ".tabItem_right",
  138. titCell: ".tabItem_lift a",
  139. trigger: "mouseover"
  140. });
  141. $("#mainClassify_2 .tabItem_lift a").eq(0).trigger("mouseover");
  142. $("#mainClassify_1 .tabItem_lift a").eq(0).trigger("mouseover");
  143. }, 500);
  144. } else {
  145. setTimeout(function () {
  146. $('#mainClassify').slide({
  147. mainCell: ".clsCon",
  148. titCell: ".clsTab a",
  149. trigger: "click"
  150. });
  151. $('#mainClassify_1').slide({
  152. mainCell: ".tabItem_right",
  153. titCell: ".tabItem_lift a",
  154. trigger: "click"
  155. });
  156. $('#mainClassify_2').slide({
  157. mainCell: ".tabItem_right",
  158. titCell: ".tabItem_lift a",
  159. trigger: "click"
  160. });
  161. $("#mainClassify_2 .tabItem_lift a").eq(0).trigger("click");
  162. $("#mainClassify_1 .tabItem_lift a").eq(0).trigger("click");
  163. }, 500);
  164. }
  165. },
  166. // 头部购物车数据
  167. getHeadCart: function (userId) {
  168. var _self = this;
  169. ShoppingApi.getHeaderCartList({userId: userId}, function (response) {
  170. if (response.code === 0 && response.data) {
  171. var data = response.data;
  172. _self.headCart.cartList = data.list;
  173. _self.headCart.cartCount = data.list.length;
  174. _self.headCart.productCount = 0;
  175. _self.headCart.priceTotal = 0;
  176. data.list.map(function (item) {
  177. _self.headCart.productCount += item.number;
  178. _self.headCart.priceTotal += item.number * item.price;
  179. });
  180. } else if (r.code == -99) {
  181. CAIMEI.Storage.clear();
  182. location.href = "/login.html";
  183. }
  184. });
  185. },
  186. getAuthClubCount: function (clubId) {
  187. var _self = this;
  188. PublicApi.getAuthClubCount({commonId: clubId}, function (response) {
  189. if (response.code === 0 && response.data) {
  190. var data = response.data;
  191. if (data.count > 99) {
  192. _self.noticeNum = '99+'
  193. } else {
  194. _self.noticeNum = data.count
  195. }
  196. console.log('noticeNum', _self.noticeNum)
  197. } else {
  198. console.log('获取机构通知消息数量异常')
  199. }
  200. });
  201. },
  202. getAuthShopCount: function (shopId) {
  203. var _self = this;
  204. PublicApi.getAuthShopCount({commonId: shopId}, function (response) {
  205. if (response.code === 0 && response.data) {
  206. var data = response.data;
  207. if (data.count > 99) {
  208. _self.noticeNum = '99+'
  209. } else {
  210. _self.noticeNum = data.count
  211. }
  212. localStorage.setItem('noticeNum', _self.noticeNum)
  213. } else {
  214. console.log('获取供应商通知消息数量异常')
  215. }
  216. });
  217. },
  218. goMsgLinkFn: function (url) {
  219. var _self = this;
  220. if (_self.loginStatus) {
  221. window.location.href = url;
  222. } else {
  223. window.location.href = '/login.html';
  224. }
  225. },
  226. goSupplierLink() {
  227. window.location.href = '/supplier/attraction.html'
  228. },
  229. // 头部供应商跳转链接
  230. goHeaderLink(link) {
  231. if (link) {
  232. window.location.href = link
  233. }
  234. },
  235. goCartsLinkFn: function () {
  236. var _self = this;
  237. if (_self.loginStatus) {
  238. window.location.href = '/shopping/cart.html';
  239. } else {
  240. window.location.href = '/login.html';
  241. }
  242. },
  243. productDetailsFn: function (id) { // 跳转详情
  244. window.location.href = '/product-' + id + '.html';
  245. },
  246. DeleteCartProducts: function (skuId) { // 删除购物车
  247. const _self = this;
  248. ShoppingApi.DeleteCartProducts({userId: this.userData.userId, skuIds: skuId}, function (response) {
  249. if (response.code === 0) {
  250. _self.getHeadCart(_self.userData.userId);
  251. } else {
  252. CAIMEI.Alert(response.msg, '确定', false);
  253. }
  254. });
  255. },
  256. pageLinkSupplier: function () {//预览商品
  257. window.open('/supplier-' + this.shopId + '.html');
  258. },
  259. // 退出登录
  260. userLogOut: function () {
  261. localStorage.removeItem('userInfo');
  262. delBaseCookie("loginBeforePath");
  263. this.loginStatus = false;
  264. window.location.href = "/index.html";
  265. },
  266. showGlobalMenu: function () {
  267. if (!isPC) {
  268. $("#mGlobalMenu").show().find(".cShow").slideDown(500);
  269. }
  270. },
  271. hideGlobalMenu: function () {
  272. if (!isPC) {
  273. $("#mGlobalMenu").hide().find(".cShow").hide();
  274. }
  275. },
  276. // init auto-input complete
  277. initAuthInputComplete() {
  278. new AutoComplete({
  279. el: '.auto-input',
  280. callback: async function (keyword) {
  281. try {
  282. const res = await PublicApi.fetchQueryKeywordList({keyword: keyword});
  283. if (!res.data) return [];
  284. return res.data.map(item => item.keyword);
  285. } catch (e) {
  286. console.log(e);
  287. }
  288. },
  289. itemClick: function (keyword) {
  290. window.location.href = '/product/list.html?keyword=' + keyword + '&productFlag=1' + '&linkageFlag=1';
  291. }
  292. });
  293. },
  294. },
  295. created: function () {
  296. var _self = this;
  297. // 判断登录状态
  298. if (globalUserData.token) {
  299. this.loginStatus = true;
  300. this.userData = globalUserData;
  301. if (this.userData.userIdentity === 3) {
  302. // 获取头部通知消息数量
  303. setTimeout(function () {
  304. _self.getAuthShopCount(_self.userData.shopId);
  305. }, 1000);
  306. // 获取头部通知消息数量
  307. var timerShopCount = setInterval(function () {
  308. _self.getAuthShopCount(_self.userData.shopId);
  309. }, 1000 * 120);
  310. } else {
  311. setTimeout(function () {
  312. // 获取头部购物车数据
  313. _self.getHeadCart(_self.userData.userId);
  314. _self.getAuthClubCount(_self.userData.clubId);
  315. }, 1000);
  316. // 获取头部通知消息数量
  317. var timerClubCount = setInterval(function () {
  318. _self.getAuthClubCount(_self.userData.clubId);
  319. }, 1000 * 600);
  320. }
  321. }
  322. // 信息中心
  323. this.articleType = getUrlParam("type");
  324. },
  325. mounted: function () {
  326. var _self = this;
  327. // 初始化分类菜单效果
  328. this.initClassufyTab();
  329. var userData = JSON.parse(window.localStorage.getItem('userInfo'));
  330. if (userData != null) {
  331. this.userIdentity = userData.userIdentity;
  332. this.shopId = userData.shopId;
  333. }
  334. if ($(window).height() > 750) {
  335. $(window).on('scroll', function () {
  336. var scrollTop = $(this).scrollTop();
  337. if (scrollTop > 50) {
  338. _self.isFiexd = true;
  339. } else {
  340. _self.isFiexd = false;
  341. }
  342. })
  343. }
  344. // 判断导航菜单高亮-对比url
  345. setTimeout(function () {
  346. var path = window.location.pathname;
  347. var paramsArr = path.split(".")[0].split("-");
  348. var key = paramsArr[0].split("/")[1];
  349. var pageId = paramsArr.length >= 1 ? paramsArr[1] : '';
  350. if (key && key.length > 0) {
  351. $('.navBox li').each(function () {
  352. var href = $(this).find('a').attr("href");
  353. if (href.indexOf(path) >= 0) {
  354. $(this).find('a').addClass('on');
  355. return false;
  356. } else if (key != 'product' && key != 'info' && href.indexOf('/' + key) >= 0) {
  357. $(this).find('a').addClass('on');
  358. return false;
  359. }
  360. });
  361. }
  362. }, 500);
  363. this.initAuthInputComplete();
  364. }
  365. });
  366. // 底部
  367. const globalFot = new Vue({
  368. el: '#globalFot',
  369. mixins: [cmAiMixins],
  370. data: {
  371. isShowIcon: true,
  372. },
  373. computed: {
  374. copyrightYear() {
  375. let date = new Date()
  376. return date.getFullYear()
  377. }
  378. },
  379. methods: {
  380. goSupplierLink() {
  381. window.location.href = '/supplier/attraction.html'
  382. },
  383. },
  384. mounted() {
  385. }
  386. });
  387. // 初始化效果
  388. $(function(){
  389. // PC,H5切换时刷新
  390. $(window).resize(function() {
  391. var flag = (isPC && $(window).width()<=768) || (!isPC && $(window).width()>768);
  392. if(flag){
  393. window.location.reload();
  394. }
  395. });
  396. // 导航分类
  397. if(isPC){
  398. jqClickShow(".baseHeadTop .cTab", ".baseHeadTop .cShow");
  399. jqSelect(".jqSelect");
  400. jqHoverShow(".classBtn", "#mainClassify");
  401. }else{
  402. jqMultipleShow("click", ".footLink .list", ".tab", ".con", true);
  403. $('body').on('click', '.baseHeadCenter .mClassBtn',function () {
  404. $('#mainClassify').show();
  405. fixedBody();
  406. }).on('click', '#mainClassify .close,#mainClassify .mClassBtn',function () {
  407. $('#mainClassify').hide();
  408. looseBody();
  409. }).on('click', '#mainClassify',function (e) {
  410. e.stopPropagation();
  411. });
  412. }
  413. // 登录弹窗
  414. function loginAert(content, btnTxt){
  415. $.confirm({
  416. useBootstrap: false,
  417. boxWidth: (isPC?'338px':'74.6vw'),
  418. title: false,
  419. content:'<div class="loginAlert">'+content+'</div>',
  420. closeIcon: true,
  421. animation: 'opacity',
  422. closeAnimation: 'opacity',
  423. animateFromElement: false,
  424. scrollToPreviousElement: false,
  425. buttons: {
  426. login: {
  427. text: btnTxt,
  428. btnClass: 'btn-confirm-login',
  429. action: function(){
  430. setBeforeUrl();
  431. window.location.href = '/login.html';
  432. }
  433. },
  434. close: {
  435. text: '取消',
  436. btnClass: 'btn-cancel-login'
  437. }
  438. }
  439. });
  440. }
  441. // 去登录弹窗
  442. $('body').on("click", '.toLogin',function () {
  443. //loginAert('<span>你还未登录</span><span>请登录后再进行购买</span>', '去登录');
  444. setBeforeUrl();
  445. window.location.href = '/login.html';
  446. });
  447. // 退出登录
  448. $('body').on("click", '.toLogOut',function () {
  449. localStorage.removeItem('userInfo');
  450. delBaseCookie("loginBeforePath");
  451. globalHead.loginStatus = false;
  452. window.location.href = "/index.html";
  453. });
  454. // 置顶
  455. $('#scrollTop').on("click", '.toTop',function () {
  456. $("html,body").animate({scrollTop:0},500);
  457. });
  458. // 热线
  459. if(!isPC){
  460. $('#scrollTop').on("click", '.phone',function () {
  461. $('#scrollTop').find('.phoneHover').show();
  462. fixedBody();
  463. }).on("click", '.phoneHover div',function (e) {
  464. e.stopPropagation();
  465. }).on("click", '.phoneHover,.phoneHover .close',function () {
  466. $('#scrollTop').find('.phoneHover').hide();
  467. looseBody();
  468. });
  469. $('body').on("click", '#centerNav .home',function () {
  470. if($('#centerNav').find('.home').hasClass("on")){
  471. $('#centerNav').find('.home').removeClass("on");
  472. $('#centerNav').find('.centerBox').slideUp();
  473. looseBody();
  474. }else{
  475. $('#centerNav').find('.home').addClass("on");
  476. $('#centerNav').find('.centerBox').slideDown();
  477. fixedBody();
  478. }
  479. }).on("click", '#centerNav .wrap',function (e) {
  480. e.stopPropagation();
  481. }).on("click", '#centerNav .centerBox',function () {
  482. $('#centerNav').find('.home').removeClass("on");
  483. $('#centerNav').find('.centerBox').slideUp();
  484. looseBody();
  485. });
  486. }
  487. // 侧边栏滚动判断
  488. $(window).scroll(function () {
  489. if($('body').attr("style") && $('body').attr("style").indexOf('fixed')>0){
  490. return false;
  491. }
  492. var scoll = Math.max($('html').scrollTop(), $('body').scrollTop());
  493. if(scoll >200){
  494. $('#scrollTop').show();
  495. }else {
  496. $('#scrollTop').hide();
  497. }
  498. });
  499. // 顶部搜索框
  500. $('#topSearch').on("click", '.searchBtn', function () {
  501. /*
  502. * 搜索类型 type
  503. * 0:产品 1:供应商 2:项目仪器 NaN:文章
  504. * 关键词 keyword
  505. * */
  506. const type = isPC ? $('#topSearch').find('[data-select]').attr("data-select") * 1 : $('#topSearch').find('select').val() * 1;
  507. const keyword = $.trim($('#topSearch').find('.keyword').val());
  508. const tips = isNaN(type) ? '请输入文章关键词' : '请输入搜索关键词';
  509. if ((type === 0 && keyword.length < 2) || (!type && !keyword)) {
  510. CAIMEI.dialog(tips,true,function () {});
  511. return false;
  512. }
  513. if (type === 0) {
  514. // 产品
  515. window.location.href = '/product/list.html?keyword=' + encodeURIComponent(keyword);
  516. } else if (type === 1) {
  517. // 供应商
  518. if (!keyword) {
  519. window.location.href = '/supplier/list.html';
  520. } else {
  521. window.location.href = '/supplier/list.html?keyword=' + encodeURIComponent(keyword);
  522. }
  523. } else if (type === 2) {
  524. // 项目仪器
  525. if (!keyword) {
  526. window.location.href = '/equipment/list.html';
  527. } else {
  528. window.location.href = '/equipment/list.html?keyword=' + encodeURIComponent(keyword);
  529. }
  530. } else {
  531. // 文章
  532. window.location.href = '/info/search-1.html?keyword=' + encodeURIComponent(keyword);
  533. }
  534. }).on('keyup', '.keyword', function (event) {
  535. // 搜索输入框 按回车键搜索
  536. var keyCode = event.keyCode || event.which;
  537. if (keyCode === 13) {
  538. $(this).parents('#topSearch').find('.searchBtn').trigger("click");
  539. }
  540. }).on("click", '.hotKey .word', function () {
  541. // 点击热词 触发搜索
  542. $(this).parents('#topSearch').find('.keyword').val($(this).text());
  543. $(this).parents('#topSearch').find('.searchBtn').trigger("click");
  544. });
  545. // 支付弹框复制标识
  546. $('body').on("click", '.payAlert .copy',function () {
  547. var oInput = document.createElement('textarea');
  548. oInput.value = $(this).parents('.payAlert').find('.no').text();
  549. document.body.appendChild(oInput);
  550. oInput.select(); // 选择对象
  551. document.execCommand("Copy"); // 执行浏览器复制命令
  552. document.body.removeChild(oInput);
  553. CAIMEI.dialog('复制成功');
  554. });
  555. });
  556. /*function uuid() {
  557. var s = [];
  558. var hexDigits = "0123456789abcdef";
  559. for (var i = 0; i < 36; i++) {
  560. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  561. }
  562. s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  563. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  564. s[8] = s[13] = s[18] = s[23] = "-";
  565. return s.join("");
  566. }*/
  567. function setBeforeUrl(){
  568. var baseUrl = window.location.href;
  569. var flag = baseUrl.indexOf('/login.html')>0 || baseUrl.indexOf('/register.html')>0 || baseUrl.indexOf('/we_chat/redirect_uri.html')>0;
  570. if(!flag){
  571. setBaseCookie("loginBeforePath", baseUrl);
  572. }
  573. }
  574. // 公共方法
  575. function setBaseCookie(cname,cvalue,exdays){
  576. if (exdays) {
  577. var d = new Date();
  578. d.setTime(d.getTime()+(exdays*24*60*60*1000));
  579. var expires = "expires="+d.toGMTString();
  580. document.cookie = cname+"="+cvalue+"; path=/; "+expires;
  581. } else {
  582. document.cookie = cname+"="+cvalue+"; path=/";
  583. }
  584. }
  585. function getBaseCookie(cname){
  586. if (document.cookie) {
  587. var name = cname + "=";
  588. var ca = document.cookie.split(';');
  589. for(var i=0; i<ca.length; i++) {
  590. var c = ca[i].trim();
  591. if (c && c.indexOf(name)===0) {
  592. return c.substring(name.length,c.length);
  593. }
  594. }
  595. }
  596. return "";
  597. }
  598. function delBaseCookie(cname){
  599. var exp = new Date();
  600. exp.setTime(exp.getTime() - 1);
  601. var cval=getBaseCookie(cname);
  602. if(cval!=null) {
  603. document.cookie= cname + "="+cval+";expires="+exp.toGMTString();
  604. }
  605. }
  606. function getDateStr(dd, addCount) {
  607. dd.setDate(dd.getDate() + addCount);//获取addCount天后的日期
  608. var y = dd.getFullYear();
  609. var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);//获取当前月份的日期,不足10补0
  610. var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
  611. return y + "/" + m + "/" + d;
  612. }
  613. function jqClickShow(tab, con){
  614. $("body").on("click", tab, function(e){
  615. e.stopPropagation();
  616. if($(tab).hasClass("on")){
  617. $(tab).removeClass("on");
  618. $(con).slideUp("fast");
  619. }else{
  620. $(tab).addClass("on");
  621. $(con).slideDown("fast");
  622. }
  623. }).on("click", function(){
  624. $(tab).removeClass("on");
  625. $(con).slideUp("fast");
  626. });
  627. }
  628. function jqHoverShow(tab, con){
  629. $("body").on("mouseover", tab, function(e){
  630. e.stopPropagation();
  631. if($(tab).hasClass("on")){
  632. $(tab).removeClass("on");
  633. $(con).slideUp("fast");
  634. }else{
  635. $(tab).addClass("on");
  636. $(con).slideDown("fast");
  637. }
  638. }).on("mouseover", con, function(e){
  639. e.stopPropagation();
  640. }).on("mouseover", function(e){
  641. $(tab).removeClass("on");
  642. $(con).slideUp("fast");
  643. });
  644. }
  645. function jqMultipleShow(event, item, tab, con, stop){
  646. $("body").on(event, item+' '+tab, function(e){
  647. e.stopPropagation();
  648. $(this).parents(item).siblings(item).find(con).slideUp("fast");
  649. $(this).parents(item).siblings(item).removeClass("on");
  650. $(this).parents(item).siblings(item).find(tab).removeClass("on");
  651. if($(this).hasClass("on")){
  652. $(this).removeClass("on");
  653. $(this).parents(item).removeClass("on");
  654. $(this).parents(item).find(con).slideUp("fast");
  655. }else{
  656. $(this).addClass("on");
  657. $(this).parents(item).addClass("on");
  658. $(this).parents(item).find(con).slideDown("fast");
  659. }
  660. }).on(event, item+' '+con, function(e){
  661. e.stopPropagation();
  662. }).on(event, function(){
  663. if(stop){
  664. $(item+' '+tab).removeClass("on");
  665. $(item).removeClass("on");
  666. $(item+' '+con).slideUp("fast");
  667. }
  668. });
  669. }
  670. function jqSelect(selectBox){
  671. $("body").on("click", selectBox, function(e){
  672. e.stopPropagation();
  673. var select = $(this).find("select");
  674. var options = select.find("option");
  675. var list = "";
  676. for (var i=0; i<options.length; i++){
  677. list += '<li data-id="'+$(options[i]).val()+'">'+$(options[i]).text()+'</li>';
  678. if($(options[i]).val()===select.val()){
  679. $(this).find("[data-select]").text($(options[i]).text()).attr('data-select',$(options[i]).val());
  680. }
  681. }
  682. $(this).find("ul").html(list);
  683. $(this).find("ul").slideToggle("fast");
  684. }).on("click", selectBox + " li", function(e){
  685. e.stopPropagation();
  686. $(this).parent().prev().attr('data-select',$(this).attr("data-id")).text($(this).text());
  687. $(this).parents("pc").next().val($(this).attr("data-id"));
  688. $(this).parent().slideUp("fast");
  689. }).on("click", function(){
  690. $(selectBox).find("ul").slideUp("fast");
  691. });
  692. }
  693. //解决移动端滚动穿透
  694. function fixedBody(){
  695. var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  696. setTimeout(function(){
  697. document.body.style.cssText += 'position:fixed;top:-'+scrollTop+'px;';
  698. },10);
  699. }
  700. function looseBody() {
  701. var body = document.body;
  702. body.style.position = '';
  703. var top = body.style.top;
  704. document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top);
  705. body.style.top = '';
  706. }
  707. //url参数
  708. function getUrlParam(name) {
  709. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  710. var r = decodeURIComponent(window.location.search).substr(1).match(reg);
  711. if (r != null) {
  712. return (r[2])
  713. }
  714. return null;
  715. }
  716. function updateUrlParam(params) {
  717. var loca = window.location;
  718. var baseUrl = loca.origin + loca.pathname + "?";
  719. var query = loca.search.substr(1).toLowerCase();
  720. var queryArr = query.split("&");
  721. var keys = Object.keys(params);
  722. if (keys.length > 0) {
  723. var obj = {};
  724. for (var i = 0; i < queryArr.length; i++) {
  725. queryArr[i] = queryArr[i].split("=");
  726. obj[queryArr[i][0]] = queryArr[i][1]
  727. }
  728. for (var k = 0; k < keys.length; k++) {
  729. var name = keys[k];
  730. var value = params[name];
  731. obj[name.toLowerCase()] = value;
  732. }
  733. var url = baseUrl + JSON.stringify(obj).replace(/["\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
  734. return url;
  735. }
  736. }
  737. function setSearchProductList(list, userId, callback) {//处理搜索
  738. var productIdArr = [];
  739. var resultData = [];
  740. list.map(function (item) {
  741. resultData.push({
  742. productId: item.productId,
  743. name: item.name,
  744. image: item.image,
  745. unit: item.unit,
  746. brandName: item.brandName,
  747. priceFlag: item.priceFlag,
  748. priceGrade: item.priceGrade,
  749. actStatus: 0,
  750. priceLoaded: false,
  751. beautyActFlag:item.beautyActFlag,
  752. productType:item.productType
  753. });
  754. // 0公开价格 1不公开价格 2仅对会员机构公开
  755. if (item.priceFlag !== 1) {
  756. productIdArr.push(item.productId)
  757. }
  758. });
  759. if (userId && userId > 0) {
  760. setProductPrice(resultData, productIdArr.join(","), userId, callback);
  761. }else {
  762. setProductPrice(resultData, productIdArr.join(","), 0, callback);
  763. }
  764. return resultData;
  765. }
  766. function setProductPrice(productList, productIds, userId, callback){
  767. $.getJSON(coreServer+"/commodity/price/list",{
  768. userId: userId,
  769. productIds: productIds,
  770. source: 1
  771. }).done(function (r) {
  772. if (r.code === 0 && r.data) {
  773. var priceList = r.data;
  774. productList.map(function(product){
  775. priceList.map(function(item){
  776. if(product.productId*1 === item.productId){
  777. product.shopId = item.shopId;
  778. product.userIdentity = item.userIdentity;
  779. product.price = item.price;
  780. product.originalPrice = item.originalPrice;
  781. product.priceLoaded = true;
  782. product.ladderPriceFlag = item.ladderPriceFlag;
  783. product.actStatus =item.actStatus;
  784. product.couponsLogo =item.couponsLogo;
  785. product.promotions =item.promotions;
  786. product.svipPriceTag =item.svipPriceTag;
  787. product.svipPriceType =item.svipPriceType;
  788. product.svipProductFlag =item.svipProductFlag;
  789. }
  790. });
  791. });
  792. }
  793. return callback();
  794. }).fail(function(){
  795. return callback();
  796. })
  797. }
  798. // 登录后返回登录前页面
  799. function toBeforePath(){
  800. var loginBeforePath = getBaseCookie("loginBeforePath");
  801. if (loginBeforePath && loginBeforePath!=='undefined' && loginBeforePath.indexOf('.html')>0) {
  802. delBaseCookie("loginBeforePath");
  803. window.location.href = loginBeforePath;
  804. }
  805. window.location.href = '/index.html';
  806. }
  807. function toLogin() {//去登录
  808. setBeforeUrl();
  809. window.location.href = '/login.html';
  810. }
  811. function upgrade () { //升级会员
  812. window.location.href='';
  813. }
  814. function toLogOut() {//登出
  815. localStorage.removeItem('userInfo');
  816. delBaseCookie("loginBeforePath");
  817. this.loginStatus = false;
  818. window.location.href = "/index.html";
  819. }
  820. /**
  821. * 至少保留两位小数
  822. * 10 => "10.00"
  823. * @param {number} num
  824. */
  825. function toFloat(num) {
  826. var temp = String(num).split('.');
  827. if (temp.length === 1 || temp[1].length < 2) {
  828. return Number(num).toFixed(2);
  829. }else{
  830. return Number(num);
  831. }
  832. }
  833. /** 表单输入框校验 */
  834. function verifyHandle(obj){
  835. if ($(obj).is(":hidden")) { return false; }
  836. var v = $.trim($(obj).val()).replace(/\s+/g,"");
  837. var reg = $(obj).attr("rule");
  838. var errorTxt = $(obj).siblings('.errTips').attr("tips");
  839. if ($.trim(v) === '') {
  840. if ($(obj).attr("placeholder") && $(obj).attr("placeholder").indexOf("请输入")>=0) {
  841. errorTxt = $(obj).attr("placeholder").split("请输入")[1]+'不能为空';
  842. } else {
  843. errorTxt = '不能为空';
  844. }
  845. setErrorTxt(obj, errorTxt);
  846. return false;
  847. }else if (typeof reg != "undefined") {
  848. reg = new RegExp(reg);
  849. if (!reg.test(v)) {
  850. setErrorTxt(obj, errorTxt);
  851. return false;
  852. }
  853. }
  854. clearErrorTxt(obj);
  855. }
  856. function setErrorTxt(obj, txt) {
  857. $(obj).parent().addClass("error").find('.checked').removeClass("show");
  858. $(obj).siblings('.errTips').text(txt).addClass("show");
  859. }
  860. function clearErrorTxt(obj) {
  861. $(obj).siblings('.errTips').removeClass("show");
  862. $(obj).parent().removeClass("error").find('.checked').addClass("show");
  863. }
  864. function clearAllErrorTxt(obj) {
  865. $(obj).siblings('.errTips').removeClass("show");
  866. $(obj).parent().removeClass("error");
  867. }
  868. // 提交时验证表单
  869. function verifyForm() {
  870. $("[needverify]:visible").each(function (index, ele) {
  871. if (!$(ele).siblings('.checked').hasClass("show")) {
  872. verifyHandle(ele);
  873. }
  874. });
  875. var len = $('.errTips.show:visible').length;
  876. return (len === 0);
  877. }
  878. // 单个验证表单
  879. function verifyCheack(ele) {
  880. if (!$(ele).siblings('.checked').hasClass("show")) {
  881. verifyHandle(ele);
  882. }
  883. var len = $(ele).siblings('.errTips.show:visible').length;
  884. return (len === 0);
  885. }
  886. // 公共信息提示弹框
  887. function alertInfo(txt,callback) {
  888. $.confirm({
  889. useBootstrap: false,
  890. boxWidth: (isPC?'300px':'70%'),
  891. title:'提示',
  892. content: txt,
  893. closeIcon: true,
  894. animation: 'opacity',
  895. closeAnimation: 'opacity',
  896. animateFromElement: false,
  897. buttons: {
  898. close: {
  899. text: '确定',
  900. btnClass: 'btn-confirm',
  901. action: function () {
  902. callback()
  903. }
  904. }
  905. }
  906. });
  907. }
  908. //公共吐司
  909. function dialog(txt,callback) {
  910. $.confirm({
  911. title: false,
  912. content: txt,
  913. boxWidth: (isPC?'300px':'70%'),
  914. autoClose: 'close|2000',
  915. useBootstrap:false,
  916. buttons: {
  917. close:{
  918. isHidden: true,
  919. action: function () {
  920. callback()
  921. }
  922. }
  923. }
  924. });
  925. }
  926. /** 时间格式化
  927. * @param {Date} date 标准时间格式 -> new Date()
  928. * @param {string} format 时间格式化的格式 'yyyy-MM-dd hh:mm:ss'
  929. * @returns {string} 格式化后的时间 '2017-01-01 01:00:00'
  930. */
  931. function dateFormat(date = new Date(), format = 'yyyy-MM-dd hh:mm:ss') {
  932. var o = {
  933. 'M+': date.getMonth() + 1, // month
  934. 'd+': date.getDate(), // day
  935. 'h+': date.getHours(), // hour
  936. 'm+': date.getMinutes(), // minute
  937. 's+': date.getSeconds(), // second
  938. 'q+': Math.floor((date.getMonth() + 3) / 3), // quarter
  939. S: date.getMilliseconds(), // millisecond
  940. };
  941. if (/(y+)/.test(format)) {
  942. format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  943. }
  944. for (var k in o) {
  945. if (new RegExp('(' + k + ')').test(format)) {
  946. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  947. }
  948. }
  949. return format
  950. }
  951. /**
  952. * @param {Array} actual
  953. * @returns {Array}
  954. */
  955. function cleanArray(actual) {
  956. const newArray = []
  957. for (let i = 0; i < actual.length; i++) {
  958. if (actual[i]) {
  959. newArray.push(actual[i])
  960. }
  961. }
  962. return newArray
  963. }
  964. /**
  965. * @param {Object} json
  966. * @returns {Array}
  967. */
  968. function param(json) {
  969. if (!json) return ''
  970. return cleanArray(
  971. Object.keys(json).map(key => {
  972. if (json[key] === undefined) return ''
  973. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  974. })
  975. ).join('&')
  976. }
  977. /**
  978. * 防抖
  979. */
  980. function debounce(func, wait = 200, immediate = false) {
  981. let timeout, result;
  982. return function () {
  983. const context = this;
  984. const args = arguments;
  985. if (timeout) clearTimeout(timeout);
  986. if (immediate) {
  987. const callNow = !timeout;
  988. timeout = setTimeout(function () {
  989. timeout = null;
  990. }, wait);
  991. if (callNow) result = func.apply(context, args);
  992. } else {
  993. timeout = setTimeout(function () {
  994. func.apply(context, args);
  995. }, wait);
  996. }
  997. return result;
  998. };
  999. }
  1000. /* 深度克隆 */
  1001. function deepClone(obj, cache = new WeakMap()) {
  1002. if (typeof obj !== 'object') return obj // 普通类型,直接返回
  1003. if (obj === null) return obj
  1004. if (cache.get(obj)) return cache.get(obj) // 防止循环引用,程序进入死循环
  1005. if (obj instanceof Date) return new Date(obj)
  1006. if (obj instanceof RegExp) return new RegExp(obj)
  1007. // 找到所属原型上的constructor,所属原型上的constructor指向当前对象的构造函数
  1008. let cloneObj = new obj.constructor()
  1009. cache.set(obj, cloneObj) // 缓存拷贝的对象,用于处理循环引用的情况
  1010. for (let key in obj) {
  1011. if (obj.hasOwnProperty(key)) {
  1012. cloneObj[key] = deepClone(obj[key], cache) // 递归拷贝
  1013. }
  1014. }
  1015. return cloneObj
  1016. }