base.js 35 KB

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