base.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. if (userAgent.match(/MicroMessenger/i)) {
  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. var 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(id){ // 删除购物车
  247. var _self = this;
  248. ShoppingApi.DeleteCartProducts({userId: this.userData.userId, productIds: id},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*120);
  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>200){
  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. var globalFot = new Vue({
  368. el: '#globalFot',
  369. data: {
  370. isShowIcon: true,
  371. },
  372. computed:{
  373. copyrightYear(){
  374. let date = new Date()
  375. return date.getFullYear()
  376. }
  377. },
  378. methods:{
  379. goSupplierLink() {
  380. window.location.href = '/supplier/attraction.html'
  381. },
  382. },
  383. mounted(){
  384. }
  385. })
  386. // 初始化效果
  387. $(function(){
  388. // PC,H5切换时刷新
  389. $(window).resize(function() {
  390. var flag = (isPC && $(window).width()<=768) || (!isPC && $(window).width()>768);
  391. if(flag){
  392. window.location.reload();
  393. }
  394. });
  395. // 导航分类
  396. if(isPC){
  397. jqClickShow(".baseHeadTop .cTab", ".baseHeadTop .cShow");
  398. jqSelect(".jqSelect");
  399. jqHoverShow(".classBtn", "#mainClassify");
  400. }else{
  401. jqMultipleShow("click", ".footLink .list", ".tab", ".con", true);
  402. $('body').on('click', '.baseHeadCenter .mClassBtn',function () {
  403. $('#mainClassify').show();
  404. fixedBody();
  405. }).on('click', '#mainClassify .close,#mainClassify .mClassBtn',function () {
  406. $('#mainClassify').hide();
  407. looseBody();
  408. }).on('click', '#mainClassify',function (e) {
  409. e.stopPropagation();
  410. });
  411. }
  412. // 登录弹窗
  413. function loginAert(content, btnTxt){
  414. $.confirm({
  415. useBootstrap: false,
  416. boxWidth: (isPC?'338px':'74.6vw'),
  417. title: false,
  418. content:'<div class="loginAlert">'+content+'</div>',
  419. closeIcon: true,
  420. animation: 'opacity',
  421. closeAnimation: 'opacity',
  422. animateFromElement: false,
  423. scrollToPreviousElement: false,
  424. buttons: {
  425. login: {
  426. text: btnTxt,
  427. btnClass: 'btn-confirm-login',
  428. action: function(){
  429. setBeforeUrl();
  430. window.location.href = '/login.html';
  431. }
  432. },
  433. close: {
  434. text: '取消',
  435. btnClass: 'btn-cancel-login'
  436. }
  437. }
  438. });
  439. }
  440. // 去登录弹窗
  441. $('body').on("click", '.toLogin',function () {
  442. //loginAert('<span>你还未登录</span><span>请登录后再进行购买</span>', '去登录');
  443. setBeforeUrl();
  444. window.location.href = '/login.html';
  445. });
  446. // 退出登录
  447. $('body').on("click", '.toLogOut',function () {
  448. localStorage.removeItem('userInfo');
  449. delBaseCookie("loginBeforePath");
  450. globalHead.loginStatus = false;
  451. window.location.href = "/index.html";
  452. });
  453. // 置顶
  454. $('#scrollTop').on("click", '.toTop',function () {
  455. $("html,body").animate({scrollTop:0},500);
  456. });
  457. // 热线
  458. if(!isPC){
  459. $('#scrollTop').on("click", '.phone',function () {
  460. $('#scrollTop').find('.phoneHover').show();
  461. fixedBody();
  462. }).on("click", '.phoneHover div',function (e) {
  463. e.stopPropagation();
  464. }).on("click", '.phoneHover,.phoneHover .close',function () {
  465. $('#scrollTop').find('.phoneHover').hide();
  466. looseBody();
  467. });
  468. $('body').on("click", '#centerNav .home',function () {
  469. if($('#centerNav').find('.home').hasClass("on")){
  470. $('#centerNav').find('.home').removeClass("on");
  471. $('#centerNav').find('.centerBox').slideUp();
  472. looseBody();
  473. }else{
  474. $('#centerNav').find('.home').addClass("on");
  475. $('#centerNav').find('.centerBox').slideDown();
  476. fixedBody();
  477. }
  478. }).on("click", '#centerNav .wrap',function (e) {
  479. e.stopPropagation();
  480. }).on("click", '#centerNav .centerBox',function () {
  481. $('#centerNav').find('.home').removeClass("on");
  482. $('#centerNav').find('.centerBox').slideUp();
  483. looseBody();
  484. });
  485. }
  486. // 侧边栏滚动判断
  487. $(window).scroll(function () {
  488. if($('body').attr("style") && $('body').attr("style").indexOf('fixed')>0){
  489. return false;
  490. }
  491. var scoll = Math.max($('html').scrollTop(), $('body').scrollTop());
  492. if(scoll >200){
  493. $('#scrollTop').show();
  494. }else {
  495. $('#scrollTop').hide();
  496. }
  497. });
  498. // 顶部搜索框
  499. $('#topSearch').on("click", '.searchBtn', function () {
  500. /*
  501. * 搜索类型 type
  502. * 0:产品 1:供应商 2:项目仪器 NaN:文章
  503. * 关键词 keyword
  504. * */
  505. var type = isPC ? $('#topSearch').find('[data-select]').attr("data-select") * 1 : $('#topSearch').find('select').val() * 1;
  506. var keyword = $.trim($('#topSearch').find('.keyword').val());
  507. var tip = isNaN(type) ? '请输入文章关键字!' : '请至少输入两个关键字!';
  508. if ((type === 0 && keyword.length < 2) || (!type && !keyword)) {
  509. $.confirm({
  510. useBootstrap: false,
  511. boxWidth: (isPC ? '300px' : '70%'),
  512. title: '提示',
  513. content: tip,
  514. closeIcon: true,
  515. animation: 'opacity',
  516. closeAnimation: 'opacity',
  517. animateFromElement: false,
  518. buttons: {
  519. close: {
  520. text: '确定',
  521. btnClass: 'btn-confirm'
  522. }
  523. }
  524. });
  525. return false;
  526. }
  527. if (type === 0) {
  528. // 产品
  529. window.location.href = '/product/list.html?keyword=' + encodeURIComponent(keyword);
  530. } else if (type === 1) {
  531. // 供应商
  532. if (!keyword) {
  533. window.location.href = '/supplier/list.html';
  534. } else {
  535. window.location.href = '/supplier/list.html?keyword=' + encodeURIComponent(keyword);
  536. }
  537. } else if (type === 2) {
  538. // 项目仪器
  539. if (!keyword) {
  540. window.location.href = '/equipment/list.html';
  541. } else {
  542. window.location.href = '/equipment/list.html?keyword=' + encodeURIComponent(keyword);
  543. }
  544. } else {
  545. // 文章
  546. window.location.href = '/info/search-1.html?keyword=' + encodeURIComponent(keyword);
  547. }
  548. // 搜索词统计
  549. BeautyArchiveApi.setSearchKeywords({keyword}, (res) => {
  550. if (res.code === 0) {
  551. console.log('搜索词统计成功')
  552. }
  553. })
  554. }).on('keyup', '.keyword', function (event) {
  555. // 搜索输入框 按回车键搜索
  556. var keyCode = event.keyCode || event.which;
  557. if (keyCode === 13) {
  558. $(this).parents('#topSearch').find('.searchBtn').trigger("click");
  559. }
  560. // 搜索词统计
  561. BeautyArchiveApi.setSearchKeywords({keyword}, (res) => {
  562. if (res.code === 0) {
  563. console.log('搜索词统计成功')
  564. }
  565. })
  566. }).on("click", '.hotKey .word', function () {
  567. // 点击热词 触发搜索
  568. $(this).parents('#topSearch').find('.keyword').val($(this).text());
  569. $(this).parents('#topSearch').find('.searchBtn').trigger("click");
  570. });
  571. // 支付弹框复制标识
  572. $('body').on("click", '.payAlert .copy',function () {
  573. var oInput = document.createElement('textarea');
  574. oInput.value = $(this).parents('.payAlert').find('.no').text();
  575. document.body.appendChild(oInput);
  576. oInput.select(); // 选择对象
  577. document.execCommand("Copy"); // 执行浏览器复制命令
  578. document.body.removeChild(oInput);
  579. CAIMEI.dialog('复制成功');
  580. });
  581. });
  582. /*function uuid() {
  583. var s = [];
  584. var hexDigits = "0123456789abcdef";
  585. for (var i = 0; i < 36; i++) {
  586. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  587. }
  588. s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  589. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  590. s[8] = s[13] = s[18] = s[23] = "-";
  591. return s.join("");
  592. }*/
  593. function setBeforeUrl(){
  594. var baseUrl = window.location.href;
  595. var flag = baseUrl.indexOf('/login.html')>0 || baseUrl.indexOf('/register.html')>0 || baseUrl.indexOf('/we_chat/redirect_uri.html')>0;
  596. if(!flag){
  597. setBaseCookie("loginBeforePath", baseUrl);
  598. }
  599. }
  600. // 公共方法
  601. function setBaseCookie(cname,cvalue,exdays){
  602. if (exdays) {
  603. var d = new Date();
  604. d.setTime(d.getTime()+(exdays*24*60*60*1000));
  605. var expires = "expires="+d.toGMTString();
  606. document.cookie = cname+"="+cvalue+"; path=/; "+expires;
  607. } else {
  608. document.cookie = cname+"="+cvalue+"; path=/";
  609. }
  610. }
  611. function getBaseCookie(cname){
  612. if (document.cookie) {
  613. var name = cname + "=";
  614. var ca = document.cookie.split(';');
  615. for(var i=0; i<ca.length; i++) {
  616. var c = ca[i].trim();
  617. if (c && c.indexOf(name)===0) {
  618. return c.substring(name.length,c.length);
  619. }
  620. }
  621. }
  622. return "";
  623. }
  624. function delBaseCookie(cname){
  625. var exp = new Date();
  626. exp.setTime(exp.getTime() - 1);
  627. var cval=getBaseCookie(cname);
  628. if(cval!=null) {
  629. document.cookie= cname + "="+cval+";expires="+exp.toGMTString();
  630. }
  631. }
  632. function getDateStr(dd, addCount) {
  633. dd.setDate(dd.getDate() + addCount);//获取addCount天后的日期
  634. var y = dd.getFullYear();
  635. var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);//获取当前月份的日期,不足10补0
  636. var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
  637. return y + "/" + m + "/" + d;
  638. }
  639. function jqClickShow(tab, con){
  640. $("body").on("click", tab, function(e){
  641. e.stopPropagation();
  642. if($(tab).hasClass("on")){
  643. $(tab).removeClass("on");
  644. $(con).slideUp("fast");
  645. }else{
  646. $(tab).addClass("on");
  647. $(con).slideDown("fast");
  648. }
  649. }).on("click", function(){
  650. $(tab).removeClass("on");
  651. $(con).slideUp("fast");
  652. });
  653. }
  654. function jqHoverShow(tab, con){
  655. $("body").on("mouseover", tab, function(e){
  656. e.stopPropagation();
  657. if($(tab).hasClass("on")){
  658. $(tab).removeClass("on");
  659. $(con).slideUp("fast");
  660. }else{
  661. $(tab).addClass("on");
  662. $(con).slideDown("fast");
  663. }
  664. }).on("mouseover", con, function(e){
  665. e.stopPropagation();
  666. }).on("mouseover", function(e){
  667. $(tab).removeClass("on");
  668. $(con).slideUp("fast");
  669. });
  670. }
  671. function jqMultipleShow(event, item, tab, con, stop){
  672. $("body").on(event, item+' '+tab, function(e){
  673. e.stopPropagation();
  674. $(this).parents(item).siblings(item).find(con).slideUp("fast");
  675. $(this).parents(item).siblings(item).removeClass("on");
  676. $(this).parents(item).siblings(item).find(tab).removeClass("on");
  677. if($(this).hasClass("on")){
  678. $(this).removeClass("on");
  679. $(this).parents(item).removeClass("on");
  680. $(this).parents(item).find(con).slideUp("fast");
  681. }else{
  682. $(this).addClass("on");
  683. $(this).parents(item).addClass("on");
  684. $(this).parents(item).find(con).slideDown("fast");
  685. }
  686. }).on(event, item+' '+con, function(e){
  687. e.stopPropagation();
  688. }).on(event, function(){
  689. if(stop){
  690. $(item+' '+tab).removeClass("on");
  691. $(item).removeClass("on");
  692. $(item+' '+con).slideUp("fast");
  693. }
  694. });
  695. }
  696. function jqSelect(selectBox){
  697. $("body").on("click", selectBox, function(e){
  698. e.stopPropagation();
  699. var select = $(this).find("select");
  700. var options = select.find("option");
  701. var list = "";
  702. for (var i=0; i<options.length; i++){
  703. list += '<li data-id="'+$(options[i]).val()+'">'+$(options[i]).text()+'</li>';
  704. if($(options[i]).val()===select.val()){
  705. $(this).find("[data-select]").text($(options[i]).text()).attr('data-select',$(options[i]).val());
  706. }
  707. }
  708. $(this).find("ul").html(list);
  709. $(this).find("ul").slideToggle("fast");
  710. }).on("click", selectBox + " li", function(e){
  711. e.stopPropagation();
  712. $(this).parent().prev().attr('data-select',$(this).attr("data-id")).text($(this).text());
  713. $(this).parents("pc").next().val($(this).attr("data-id"));
  714. $(this).parent().slideUp("fast");
  715. }).on("click", function(){
  716. $(selectBox).find("ul").slideUp("fast");
  717. });
  718. }
  719. //解决移动端滚动穿透
  720. function fixedBody(){
  721. var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  722. setTimeout(function(){
  723. document.body.style.cssText += 'position:fixed;top:-'+scrollTop+'px;';
  724. },10);
  725. }
  726. function looseBody() {
  727. var body = document.body;
  728. body.style.position = '';
  729. var top = body.style.top;
  730. document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top);
  731. body.style.top = '';
  732. }
  733. //url参数
  734. function getUrlParam(name) {
  735. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  736. var r = decodeURIComponent(window.location.search).substr(1).match(reg);
  737. if (r != null) {
  738. return (r[2])
  739. }
  740. return null;
  741. }
  742. function updateUrlParam(params) {
  743. var loca = window.location;
  744. var baseUrl = loca.origin + loca.pathname + "?";
  745. var query = loca.search.substr(1).toLowerCase();
  746. var queryArr = query.split("&");
  747. var keys = Object.keys(params);
  748. if (keys.length > 0) {
  749. var obj = {};
  750. for (var i = 0; i < queryArr.length; i++) {
  751. queryArr[i] = queryArr[i].split("=");
  752. obj[queryArr[i][0]] = queryArr[i][1]
  753. }
  754. for (var k = 0; k < keys.length; k++) {
  755. var name = keys[k];
  756. var value = params[name];
  757. obj[name.toLowerCase()] = value;
  758. }
  759. var url = baseUrl + JSON.stringify(obj).replace(/["\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
  760. return url;
  761. }
  762. }
  763. function setSearchProductList(list, userId, callback) {//处理搜索
  764. var productIdArr = [];
  765. var resultData = [];
  766. list.map(function (item) {
  767. resultData.push({
  768. productId: item.productId,
  769. name: item.name,
  770. image: item.image,
  771. unit: item.unit,
  772. brandName: item.brandName,
  773. priceFlag: item.priceFlag,
  774. priceGrade: item.priceGrade,
  775. actStatus: 0,
  776. priceLoaded: false,
  777. beautyActFlag:item.beautyActFlag,
  778. productType:item.productType
  779. });
  780. // 0公开价格 1不公开价格 2仅对会员机构公开
  781. if (item.priceFlag !== 1) {
  782. productIdArr.push(item.productId)
  783. }
  784. });
  785. if (userId && userId > 0) {
  786. setProductPrice(resultData, productIdArr.join(","), userId, callback);
  787. }else {
  788. setProductPrice(resultData, productIdArr.join(","), 0, callback);
  789. }
  790. return resultData;
  791. }
  792. function setProductPrice(productList, productIds, userId, callback){
  793. $.getJSON(coreServer+"/commodity/price/list",{
  794. userId: userId,
  795. productIds: productIds,
  796. source: 1
  797. }).done(function (r) {
  798. if (r.code === 0 && r.data) {
  799. var priceList = r.data;
  800. productList.map(function(product){
  801. priceList.map(function(item){
  802. if(product.productId*1 === item.productId){
  803. product.shopId = item.shopId;
  804. product.userIdentity = item.userIdentity;
  805. product.price = item.price;
  806. product.originalPrice = item.originalPrice;
  807. product.priceLoaded = true;
  808. product.ladderPriceFlag = item.ladderPriceFlag;
  809. product.actStatus =item.actStatus;
  810. product.couponsLogo =item.couponsLogo;
  811. product.promotions =item.promotions;
  812. product.svipPriceTag =item.svipPriceTag;
  813. product.svipPriceType =item.svipPriceType;
  814. product.svipProductFlag =item.svipProductFlag;
  815. }
  816. });
  817. });
  818. }
  819. return callback();
  820. }).fail(function(){
  821. return callback();
  822. })
  823. }
  824. // 登录后返回登录前页面
  825. function toBeforePath(){
  826. var loginBeforePath = getBaseCookie("loginBeforePath");
  827. if (loginBeforePath && loginBeforePath!='undefined' && loginBeforePath.indexOf('.html')>0) {
  828. delBaseCookie("loginBeforePath");
  829. window.location.href = loginBeforePath;
  830. }
  831. window.location.href = '/index.html';
  832. }
  833. function toLogin() {//去登录
  834. setBeforeUrl();
  835. window.location.href = '/login.html';
  836. }
  837. function upgrade () { //升级会员
  838. window.location.href='';
  839. }
  840. function toLogOut() {//登出
  841. localStorage.removeItem('userInfo');
  842. delBaseCookie("loginBeforePath");
  843. this.loginStatus = false;
  844. window.location.href = "/index.html";
  845. }
  846. /**
  847. * 至少保留两位小数
  848. * 10 => "10.00"
  849. * @param {number} num
  850. */
  851. function toFloat(num) {
  852. var temp = String(num).split('.');
  853. if (temp.length === 1 || temp[1].length < 2) {
  854. return Number(num).toFixed(2);
  855. }else{
  856. return Number(num);
  857. }
  858. }
  859. /** 表单输入框校验 */
  860. function verifyHandle(obj){
  861. if ($(obj).is(":hidden")) { return false; }
  862. var v = $.trim($(obj).val()).replace(/\s+/g,"");
  863. var reg = $(obj).attr("rule");
  864. var errorTxt = $(obj).siblings('.errTips').attr("tips");
  865. if ($.trim(v) === '') {
  866. if ($(obj).attr("placeholder") && $(obj).attr("placeholder").indexOf("请输入")>=0) {
  867. errorTxt = $(obj).attr("placeholder").split("请输入")[1]+'不能为空';
  868. } else {
  869. errorTxt = '不能为空';
  870. }
  871. setErrorTxt(obj, errorTxt);
  872. return false;
  873. }else if (typeof reg != "undefined") {
  874. reg = new RegExp(reg);
  875. if (!reg.test(v)) {
  876. setErrorTxt(obj, errorTxt);
  877. return false;
  878. }
  879. }
  880. clearErrorTxt(obj);
  881. }
  882. function setErrorTxt(obj, txt) {
  883. $(obj).parent().addClass("error").find('.checked').removeClass("show");
  884. $(obj).siblings('.errTips').text(txt).addClass("show");
  885. }
  886. function clearErrorTxt(obj) {
  887. $(obj).siblings('.errTips').removeClass("show");
  888. $(obj).parent().removeClass("error").find('.checked').addClass("show");
  889. }
  890. function clearAllErrorTxt(obj) {
  891. $(obj).siblings('.errTips').removeClass("show");
  892. $(obj).parent().removeClass("error");
  893. }
  894. // 提交时验证表单
  895. function verifyForm() {
  896. $("[needverify]:visible").each(function (index, ele) {
  897. if (!$(ele).siblings('.checked').hasClass("show")) {
  898. verifyHandle(ele);
  899. }
  900. });
  901. var len = $('.errTips.show:visible').length;
  902. return (len === 0);
  903. }
  904. // 单个验证表单
  905. function verifyCheack(ele) {
  906. if (!$(ele).siblings('.checked').hasClass("show")) {
  907. verifyHandle(ele);
  908. }
  909. var len = $(ele).siblings('.errTips.show:visible').length;
  910. return (len === 0);
  911. }
  912. // 公共信息提示弹框
  913. function alertInfo(txt,callback) {
  914. $.confirm({
  915. useBootstrap: false,
  916. boxWidth: (isPC?'300px':'70%'),
  917. title:'提示',
  918. content: txt,
  919. closeIcon: true,
  920. animation: 'opacity',
  921. closeAnimation: 'opacity',
  922. animateFromElement: false,
  923. buttons: {
  924. close: {
  925. text: '确定',
  926. btnClass: 'btn-confirm',
  927. action: function () {
  928. callback()
  929. }
  930. }
  931. }
  932. });
  933. }
  934. //公共吐司
  935. function dialog(txt,callback) {
  936. $.confirm({
  937. title: false,
  938. content: txt,
  939. boxWidth: (isPC?'300px':'70%'),
  940. autoClose: 'close|2000',
  941. useBootstrap:false,
  942. buttons: {
  943. close:{
  944. isHidden: true,
  945. action: function () {
  946. callback()
  947. }
  948. }
  949. }
  950. });
  951. }
  952. /** 时间格式化
  953. * @param {Date} date 标准时间格式 -> new Date()
  954. * @param {string} format 时间格式化的格式 'yyyy-MM-dd hh:mm:ss'
  955. * @returns {string} 格式化后的时间 '2017-01-01 01:00:00'
  956. */
  957. function dateFormat(date = new Date(), format = 'yyyy-MM-dd hh:mm:ss') {
  958. var o = {
  959. 'M+': date.getMonth() + 1, // month
  960. 'd+': date.getDate(), // day
  961. 'h+': date.getHours(), // hour
  962. 'm+': date.getMinutes(), // minute
  963. 's+': date.getSeconds(), // second
  964. 'q+': Math.floor((date.getMonth() + 3) / 3), // quarter
  965. S: date.getMilliseconds(), // millisecond
  966. };
  967. if (/(y+)/.test(format)) {
  968. format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  969. }
  970. for (var k in o) {
  971. if (new RegExp('(' + k + ')').test(format)) {
  972. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  973. }
  974. }
  975. return format
  976. }
  977. /**
  978. * @param {Array} actual
  979. * @returns {Array}
  980. */
  981. function cleanArray(actual) {
  982. const newArray = []
  983. for (let i = 0; i < actual.length; i++) {
  984. if (actual[i]) {
  985. newArray.push(actual[i])
  986. }
  987. }
  988. return newArray
  989. }
  990. /**
  991. * @param {Object} json
  992. * @returns {Array}
  993. */
  994. function param(json) {
  995. if (!json) return ''
  996. return cleanArray(
  997. Object.keys(json).map(key => {
  998. if (json[key] === undefined) return ''
  999. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  1000. })
  1001. ).join('&')
  1002. }
  1003. /**
  1004. * 防抖
  1005. */
  1006. function debounce(func, wait = 200, immediate = false) {
  1007. let timeout, result;
  1008. return function () {
  1009. const context = this;
  1010. const args = arguments;
  1011. if (timeout) clearTimeout(timeout);
  1012. if (immediate) {
  1013. const callNow = !timeout;
  1014. timeout = setTimeout(function () {
  1015. timeout = null;
  1016. }, wait);
  1017. if (callNow) result = func.apply(context, args);
  1018. } else {
  1019. timeout = setTimeout(function () {
  1020. func.apply(context, args);
  1021. }, wait);
  1022. }
  1023. return result;
  1024. };
  1025. }
  1026. /* 深度克隆 */
  1027. function deepClone(obj, cache = new WeakMap()) {
  1028. if (typeof obj !== 'object') return obj // 普通类型,直接返回
  1029. if (obj === null) return obj
  1030. if (cache.get(obj)) return cache.get(obj) // 防止循环引用,程序进入死循环
  1031. if (obj instanceof Date) return new Date(obj)
  1032. if (obj instanceof RegExp) return new RegExp(obj)
  1033. // 找到所属原型上的constructor,所属原型上的constructor指向当前对象的构造函数
  1034. let cloneObj = new obj.constructor()
  1035. cache.set(obj, cloneObj) // 缓存拷贝的对象,用于处理循环引用的情况
  1036. for (let key in obj) {
  1037. if (obj.hasOwnProperty(key)) {
  1038. cloneObj[key] = deepClone(obj[key], cache) // 递归拷贝
  1039. }
  1040. }
  1041. return cloneObj
  1042. }