base.js 33 KB

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