base.js 29 KB

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