common.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. var mobile = {};
  2. var dictMap = {};
  3. var paramMap = {};
  4. var user={};
  5. var company="";
  6. var shareUser="";
  7. var share={"title":"想不想花1分钱抢东西?来这里就会有,手慢无!",
  8. "link":"http://www.3water.cn/buying/mobile/index.jsp",
  9. "imgUrl":"http://www.3water.cn/buying/static/mobile/image/logo.png",
  10. "desc":"点击查看详情"};
  11. $(function() {
  12. pushHistory();
  13. });
  14. function pushHistory() {
  15. window.addEventListener("popstate", function(e) {
  16. self.location.reload();
  17. }, false);
  18. var state = {
  19. title : "",
  20. url : "#"
  21. };
  22. window.history.replaceState(state, "", "#");
  23. };
  24. $(document).ready(function () {
  25. if(window.history.length<2){
  26. //$(".mui-action-back").hide();
  27. }
  28. addLog();
  29. getTicket();
  30. $(".home-btn").on("tap",function(){
  31. location.href=base+"/mobile/index.jsp";
  32. });
  33. });
  34. function addLog(){
  35. if(mobile.getUrlVars("company")){
  36. company = mobile.getUrlVars("company");
  37. sessionStorage.setItem("company",mobile.getUrlVars("company"));
  38. }else if(sessionStorage.getItem("company")){
  39. company = sessionStorage.getItem("company");
  40. }
  41. if(mobile.getUrlVars("shareUser")){
  42. shareUser = mobile.getUrlVars("shareUser");
  43. sessionStorage.setItem("shareUser",mobile.getUrlVars("shareUser"));
  44. }else if(sessionStorage.getItem("shareUser")){
  45. shareUser = sessionStorage.getItem("shareUser");
  46. }
  47. var url = location.href.replace('#','');
  48. if(url.indexOf("?")!=-1){
  49. if(url.indexOf("shareUser")!=-1){
  50. url = mobile.changeUrlParam(url,"shareUser",user.openid);
  51. }else{
  52. url+="&shareUser="+user.openid;
  53. }
  54. }else{
  55. url+="?shareUser="+user.openid;
  56. }
  57. if(company){
  58. if(url.indexOf("?")!=-1){
  59. url+="&company="+company;
  60. }else{
  61. url+="?company="+company;
  62. }
  63. }
  64. share.link = url;
  65. var page = window.location.pathname;
  66. var id = mobile.getUrlVars("id");
  67. mobile.ajaxPost(base+"/userViewLog/save",{id:id,page:page,company:company,shareUser:shareUser},function(json){},"");
  68. }
  69. //获取微信js参数
  70. function getTicket(){
  71. mobile.ajaxPost(base+"/wechat/getTicket",{url:window.location.href},function(data){
  72. wx.config({
  73. debug: false,
  74. appId:data.appId,
  75. timestamp: data.timestamp,
  76. nonceStr: data.nonceStr,
  77. signature: data.signature,
  78. jsApiList: [
  79. 'onMenuShareTimeline',
  80. 'onMenuShareAppMessage',
  81. 'getLocation',
  82. 'openLocation'
  83. ]
  84. });
  85. },"");
  86. }
  87. //分享
  88. wx.ready(function(){
  89. wx.onMenuShareTimeline({
  90. title: share.title, // 分享标题
  91. link: share.link, // 分享链接
  92. imgUrl: share.imgUrl, // 分享图标
  93. success: function () {
  94. if(typeof share.callback=='function'){
  95. share.callback('1');
  96. }
  97. saveShareLog("10");
  98. },
  99. cancel: function () {
  100. alert('取消分享');
  101. }
  102. });
  103. wx.onMenuShareAppMessage({
  104. title: share.title, // 分享标题
  105. desc: share.desc, // 分享描述
  106. link: share.link, // 分享链接
  107. imgUrl: share.imgUrl, // 分享图标
  108. type: 'link', // 分享类型,music、video或link,不填默认为link
  109. success: function () {
  110. if(typeof share.callback=='function'){
  111. share.callback('2');
  112. }
  113. saveShareLog("20");
  114. },
  115. cancel: function () {
  116. alert('取消分享');
  117. }
  118. });
  119. });
  120. function saveShareLog(type) {
  121. var page = window.location.pathname;
  122. var id = mobile.getUrlVars("id");
  123. mobile.ajaxPost(base+"/userShareLog/save",{id:id,page:page,type:type},function(json){},"");
  124. }
  125. /**
  126. * 获取购物车数量
  127. */
  128. mobile.getCartNum = function () {
  129. mobile.ajaxPost(base+'/userCart/getNum',{},function(json){
  130. if(json.data!=0){
  131. $('.mui-bar-tab .icon-gouwuche .mui-badge').html(json.data);
  132. $('.mui-bar-tab .icon-gouwuche .mui-badge').removeClass('mui-hidden');
  133. }else{
  134. $('.mui-bar-tab .icon-gouwuche .mui-badge').addClass('mui-hidden');
  135. }
  136. });
  137. };
  138. /**
  139. * flag 当子窗口取不到是否不取父窗口的值,默认取父窗口
  140. */
  141. mobile.getUrlVars = function (name, flag) {
  142. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  143. var r = window.location.search.substr(1).match(reg);
  144. //modify by zhengwei
  145. if (flag) {
  146. if (r == null) {
  147. r = window.parent.location.search.substr(1).match(reg);
  148. }
  149. }
  150. if (r != null) return decodeURI(r[2]);
  151. return null;
  152. };
  153. /**
  154. * form赋值
  155. */
  156. mobile.toForm = function (data) {
  157. if(data){
  158. $.each(data,function(key,value){
  159. if($('#'+key)){
  160. $('#'+key).val(mobile.nullToSpace(value));
  161. }
  162. });
  163. }
  164. }
  165. //把null转为空
  166. mobile.nullToSpace = function (param) {
  167. if (param == null || typeof param == 'undefined') {
  168. param = '';
  169. }
  170. return param;
  171. }
  172. //把null转为0
  173. mobile.nullToZore = function (param) {
  174. if (param == null || typeof param == 'undefined') {
  175. param = 0;
  176. }
  177. return param;
  178. }
  179. /**
  180. * 增加天数
  181. */
  182. mobile.addDate = function(date,days){
  183. var a = new Date(date)
  184. a = a.valueOf();
  185. a = a + days * 24 * 60 * 60 * 1000
  186. a = new Date(a)
  187. return a;
  188. }
  189. /**
  190. * 获取星期
  191. */
  192. mobile.getWeek = function(date){
  193. var str = "星期";
  194. var week = date.getDay();
  195. switch (week) {
  196. case 0 :
  197. str += "日";
  198. break;
  199. case 1 :
  200. str += "一";
  201. break;
  202. case 2 :
  203. str += "二";
  204. break;
  205. case 3 :
  206. str += "三";
  207. break;
  208. case 4 :
  209. str += "四";
  210. break;
  211. case 5 :
  212. str += "五";
  213. break;
  214. case 6 :
  215. str += "六";
  216. break;
  217. }
  218. return str;
  219. }
  220. /**
  221. * 检查手机号码
  222. */
  223. mobile.checkMobile = function (phone){
  224. var reg= /(^1[3|4|5|7|8|9][0-9]{9}$)/;
  225. return reg.test(phone);
  226. }
  227. //ajax post
  228. mobile.ajaxPost = function (url, params, callback,msg) {
  229. var index=null;
  230. $.ajax({
  231. type:"POST",
  232. url:url,
  233. data:params,
  234. dataType:"json",
  235. timeout:60000,
  236. beforeSend:function(){
  237. if(msg!=""){
  238. if(msg){
  239. index=layer.open({type: 3,shadeClose:false,content: msg});
  240. }else{
  241. index=layer.open({type: 3,shadeClose:false,content: '加载中...'});
  242. }
  243. }
  244. },
  245. success:function(data){
  246. if(msg!=""){
  247. layer.close(index);
  248. }
  249. if(typeof callback=='function'){
  250. callback(data);
  251. }
  252. },
  253. error:function(XMLHttpRequest, textStatus, errorThrown){
  254. if(msg!=""){
  255. layer.close(index);
  256. }
  257. switch (XMLHttpRequest.status){
  258. case(500):
  259. layer.open({content: "服务异常",time: 3});
  260. break;
  261. case(408):
  262. layer.open({content: "请求超时",time: 3});
  263. break;
  264. case(0):
  265. layer.open({content: "网络连接异常",time: 3});
  266. break;
  267. default:
  268. layer.open({content: "请求错误,请稍后再试",time: 3});
  269. }
  270. },
  271. complete: function (XHR, TS) { XHR = null; }
  272. });
  273. };
  274. //保留两位小数
  275. mobile.toDecimal = function (x) {
  276. var f = parseFloat(x);
  277. if (isNaN(f)) {
  278. return;
  279. }
  280. f = Math.round(x * 100) / 100;
  281. return f;
  282. }
  283. mobile.getWeekDay = function (){
  284. var str = "";
  285. var week = new Date().getDay();
  286. if (week == 0) {
  287. str = "星期日";
  288. } else if (week == 1) {
  289. str = "星期一";
  290. } else if (week == 2) {
  291. str = "星期二";
  292. } else if (week == 3) {
  293. str = "星期三";
  294. } else if (week == 4) {
  295. str = "星期四";
  296. } else if (week == 5) {
  297. str = "星期五";
  298. } else if (week == 6) {
  299. str = "星期六";
  300. }
  301. return str;
  302. }
  303. //日期格式化
  304. Date.prototype.format = function (fmt) {
  305. var o = {
  306. "M+": this.getMonth() + 1, //月份
  307. "d+": this.getDate(), //日
  308. "h+": this.getHours(), //小时
  309. "m+": this.getMinutes(), //分
  310. "s+": this.getSeconds(), //秒
  311. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  312. "S": this.getMilliseconds() //毫秒
  313. };
  314. if (/(y+)/.test(fmt))
  315. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  316. for (var k in o)
  317. if (new RegExp("(" + k + ")").test(fmt))
  318. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  319. return fmt;
  320. }
  321. //数组移除
  322. Array.prototype.removeAt = function (Index) {
  323. if (isNaN(Index) || Index > this.length) {
  324. return false;
  325. }
  326. for (var i = 0, n = 0; i < this.length; i++) {
  327. if (this[i] != this[Index]) {
  328. this[n++] = this[i]
  329. }
  330. }
  331. this.length -= 1
  332. }
  333. //数组是否包含某项
  334. Array.prototype.contains = function (needle) {
  335. for (i in this) {
  336. if (this[i] == needle)
  337. return true;
  338. }
  339. return false;
  340. }
  341. /**
  342. * 根据字典类型获取items
  343. * @param d_key
  344. * @returns
  345. */
  346. mobile.getDictMap = function (d_key) {
  347. if (dictMap[d_key]) {
  348. return dictMap[d_key];
  349. }
  350. };
  351. /**
  352. * 根据系统参数
  353. * @param code
  354. * @returns
  355. */
  356. mobile.getParam = function (code) {
  357. if (paramMap[code]) {
  358. return paramMap[code];
  359. } else {
  360. return "";
  361. }
  362. };
  363. /**
  364. * 根据代码和字典类型获取下拉选项的名称item{value:'1',label:'测试'}
  365. * @param d_key
  366. * @param code
  367. * @returns
  368. */
  369. mobile.getDictVal = function (key, code) {
  370. var items = dictMap[key];
  371. if (items && items.length > 0) {
  372. for (var i = 0; i < items.length; i++) {
  373. var item = items[i];
  374. if (item.dict_code == code) {
  375. return item.dict_name;
  376. break;
  377. }
  378. }
  379. }
  380. return "";
  381. }
  382. mobile.fileUploader = function(filePicker,callback,params){
  383. //添加删除事件结束
  384. var imgUploadUrl = base+'/common/upload';
  385. if(typeof params!='undefined'){
  386. imgUploadUrl = imgUploadUrl+"?"+params;
  387. }
  388. var opt={
  389. auto: true,
  390. // swf文件路径
  391. swf: base+'/static/frame/webuploader/Uploader.swf',
  392. // 文件接收服务端。
  393. server : imgUploadUrl,
  394. // 内部根据当前运行是创建,可能是input元素,也可能是flash.
  395. pick : {
  396. id : '#'+filePicker,
  397. multiple : false
  398. },
  399. //fileSingleSizeLimit: 5*1024*1024, //最大5M
  400. // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
  401. resize : false,
  402. multiple : false,
  403. duplicate :true
  404. };
  405. if(typeof options!='undefined'){
  406. opt = $.extend(opt,options);
  407. }
  408. var uploader = WebUploader.create(opt);
  409. // 文件上传过程中提示。
  410. uploader.on( 'uploadProgress', function( file, percentage ) {
  411. //layer.msg
  412. });
  413. uploader.on( 'uploadError', function( file ) {
  414. layer.msg("上传失败");
  415. uploader.reset();
  416. });
  417. uploader.onError = function( code ) {
  418. switch(code){
  419. case 'F_EXCEED_SIZE':
  420. layer.msg('文件大小超出最大值');
  421. break;
  422. case 'Q_EXCEED_NUM_LIMIT':
  423. layer.msg('超过最大上传数量');
  424. break;
  425. case 'Q_EXCEED_SIZE_LIMIT':
  426. layer.msg('文件大小超出最大值');
  427. break;
  428. case 'Q_TYPE_DENIED':
  429. layer.msg('文件类型不允许');
  430. break;
  431. default:
  432. layer.msg('未知错误:'+code);
  433. break;
  434. }
  435. };
  436. //如果服务器端返回的code不为0,那么也是没有成功,会触发uploadError事件
  437. uploader.on("uploadAccept", function(file,data){
  438. if(!data.success){
  439. return false;
  440. }
  441. });
  442. // 文件上传成功,给item添加成功class, 用样式标记上传成功。
  443. uploader.on( 'uploadSuccess', function(file,data) {
  444. if(typeof callback=='function'){
  445. callback(data);
  446. }
  447. uploader.reset();
  448. });
  449. // 完成上传完了,成功或者失败,先删除进度条。
  450. uploader.on( 'uploadComplete', function(file,data) {
  451. });
  452. }
  453. /**
  454. * 加载图片
  455. * @param fileList 容器ID
  456. * @param data 数组类型或者字符串
  457. * @param width 图片宽度
  458. * @param height 图片高度
  459. */
  460. mobile.loadImage = function(fileList,data,width,height,editFlag){
  461. if(!width){//如果没有设置,默认为100px
  462. width=100;
  463. }
  464. if(!height){
  465. height=100;
  466. }
  467. var $list = $('#'+fileList);
  468. var arr=[];
  469. if(typeof(data) == "string"){
  470. var $li = $(
  471. '<div class="file-item thumbnail">' +
  472. '<img src="'+data+'" style="width:'+width+'px;height:'+height+'px;">' +
  473. '</div>'
  474. );
  475. if(editFlag){
  476. var $btns = $('<div class="file-panel" style="height:0px;">' +
  477. '<span class="cancel">删除</span>' +
  478. '</div>').appendTo( $li );
  479. }
  480. if(data.indexOf("flag=true")==-1){
  481. data +="&flag=true";
  482. }
  483. arr.push(data);
  484. $list.append( $li );
  485. }else{
  486. $.each(data,function(id,item){
  487. if(typeof(item) == "string"){
  488. var $li = $(
  489. '<div class="file-item thumbnail">' +
  490. '<img src="'+item+'" style="width:'+width+'px;height:'+height+'px;">' +
  491. '</div>'
  492. );
  493. if(item.indexOf("flag=true")==-1){
  494. item +="&flag=true";
  495. }
  496. arr.push(item);
  497. }else{
  498. var $li = $(
  499. '<div class="file-item thumbnail">' +
  500. '<img src="'+item.imgUrl+'" style="width:'+width+'px;height:'+height+'px;">' +
  501. '<div class="info">"'+item.imgName+'"</div>' +
  502. '</div>'
  503. );
  504. if(item.imgUrl.indexOf("flag=true")==-1){
  505. item.imgUrl +="&flag=true";
  506. }
  507. arr.push(item.imgUrl);
  508. }
  509. if(editFlag){
  510. var $btns = $('<div class="file-panel" style="height:0px;">' +
  511. '<span class="cancel">删除</span>' +
  512. '</div>').appendTo( $li );
  513. }
  514. $list.append( $li );
  515. });
  516. }
  517. $list.find("img").on('click',function(){
  518. web.showImage(arr,$(this).parent().index());
  519. });
  520. }
  521. /**
  522. * 上传图片
  523. * @param fileList 容器ID
  524. * @param filePicker 上传按钮ID
  525. * @param callback 返回方法
  526. * @param options 自定义上传
  527. * @param params 参数
  528. */
  529. mobile.imageUploader = function(fileList,filePicker,callback,options,params){
  530. $('#'+fileList).on('mouseover','.file-item',function(){
  531. $(this).find('.file-panel').css('height','30px');
  532. });
  533. $('#'+fileList).on('mouseout','.file-item',function(){
  534. $(this).find('.file-panel').css('height','0');
  535. });
  536. $('#'+fileList).on('click','.cancel',function(){
  537. $(this).parents('.file-item').remove();
  538. });
  539. //添加删除事件结束
  540. var imgUploadUrl = base+'/common/upload';
  541. if(typeof params!='undefined'){
  542. imgUploadUrl = imgUploadUrl+"?"+params;
  543. }
  544. var opt={
  545. auto: true,
  546. // swf文件路径
  547. swf: base+'/static/frame/webuploader/Uploader.swf',
  548. // 文件接收服务端。
  549. server : imgUploadUrl,
  550. // 内部根据当前运行是创建,可能是input元素,也可能是flash.
  551. pick : {
  552. id : '#'+filePicker,
  553. multiple : true
  554. },
  555. fileSingleSizeLimit: 5*1024*1024, //最大5M
  556. // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
  557. resize : false,
  558. duplicate :true,
  559. fileNumLimit:10,
  560. accept : {
  561. title : 'Images',
  562. extensions : 'jpg,jpeg,png',
  563. mimeTypes : 'image/jpg,image/jpeg,image/png'
  564. }
  565. };
  566. if(typeof options!='undefined'){
  567. opt = $.extend(opt,options);
  568. }
  569. if(!opt.thumbnailWidth){//如果没有设置,默认为100px
  570. opt.thumbnailWidth=100;
  571. }
  572. if(!opt.thumbnailHeight){
  573. opt.thumbnailHeight=100;
  574. }
  575. var $list = $('#'+fileList);
  576. var uploader = WebUploader.create(opt);
  577. uploader.on( 'fileQueued', function( file ) {
  578. if($list.find('.image-item').length>=opt.maxLength){
  579. layer.open({content:'最多上传'+opt.maxLength+'张图片',time:3});
  580. uploader.cancelFile( file );
  581. return;
  582. }
  583. var $li = $(
  584. '<div class="image-item">'+
  585. '<div class="image-close">X</div>'+
  586. '</div>'
  587. );
  588. $list.append( $li );
  589. // 创建缩略图
  590. // 如果为非图片文件,可以不用调用此方法。
  591. // thumbnailWidth x thumbnailHeight 为 100 x 100
  592. uploader.makeThumb( file, function( error, src ) {
  593. if ( error ) {
  594. $img.replaceWith('<span>不能预览</span>');
  595. return;
  596. }
  597. $li.css("background-image","url("+src+")");
  598. }, opt.thumbnailWidth, opt.thumbnailHeight);
  599. });
  600. // 文件上传过程中创建进度条实时显示。
  601. uploader.on( 'uploadProgress', function( file, percentage ) {
  602. var $li = $( '#'+file.id );
  603. var $percent = $li.find('.progress span');
  604. // 避免重复创建
  605. if ( !$percent.length ) {
  606. $percent = $('<p class="progress"><span></span></p>')
  607. .appendTo( $li )
  608. .find('span');
  609. }
  610. $percent.css( 'width', percentage * 100 + '%' );
  611. });
  612. uploader.on( 'uploadError', function( file ,reason) {
  613. var $li = $( '#'+file.id );
  614. var $error = $li.find('div.error');
  615. // 避免重复创建
  616. if ( !$error.length ) {
  617. $error = $('<div class="error"></div>').appendTo( $li );
  618. }
  619. $error.text('上传失败');
  620. });
  621. uploader.onError = function( code ) {
  622. switch(code){
  623. case 'F_EXCEED_SIZE':
  624. layer.msg('文件大小超出最大值');
  625. break;
  626. case 'Q_EXCEED_NUM_LIMIT':
  627. layer.msg('超过最大上传数量');
  628. break;
  629. case 'Q_EXCEED_SIZE_LIMIT':
  630. layer.msg('文件大小超出最大值');
  631. break;
  632. case 'Q_TYPE_DENIED':
  633. layer.msg('文件类型不允许');
  634. break;
  635. default:
  636. layer.msg('未知错误:'+code);
  637. break;
  638. }
  639. };
  640. //如果服务器端返回的code不为0,那么也是没有成功,会触发uploadError事件
  641. uploader.on("uploadAccept", function(file,data){
  642. if(!data.success){
  643. return false;
  644. }
  645. });
  646. // 文件上传成功,给item添加成功class, 用样式标记上传成功。
  647. uploader.on( 'uploadSuccess', function(file,data) {
  648. if(typeof callback=='function'){
  649. callback(data);
  650. }
  651. });
  652. // 完成上传完了,成功或者失败,先删除进度条。
  653. uploader.on( 'uploadComplete', function(file,data) {
  654. $( '#'+file.id ).find('.progress').remove();
  655. });
  656. }
  657. /**
  658. * 上传图片
  659. * @param fileList 容器ID
  660. * @param filePicker 上传按钮ID
  661. * @param callback 返回方法
  662. * @param options 自定义上传
  663. * @param params 参数
  664. */
  665. mobile.tip=function(obj,msg,icon,top){
  666. if(!top){
  667. top="50%"
  668. }
  669. if(!icon){
  670. icon="icon-zanwushuju"
  671. }
  672. $(""+obj+"").append('<div class="center" style="top:'+top+'">'+
  673. '<div class="mui-icon iconfont '+icon+' fs44 mb10"></div><div class="fs14">'+msg+'</div></div>');
  674. }
  675. mobile.changeUrlParam=function (url, param, val){
  676. var pattern = param+'=([^&]*)';
  677. var replaceText = param+'='+val;
  678. return url.match(pattern) ? url.replace(eval('/('+ param+'=)([^&]*)/gi'), replaceText) : (url.match('[\?]') ? url+'&'+replaceText : url+'?'+replaceText);
  679. }