util.js
24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
var uri=require('uri.js')
function formatTime(date,type,connect) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
if(type==1){
if(connect){
return [year, month, day].map(formatNumber).join(connect)
}else{
return [year, month, day].map(formatNumber).join('/')
}
}else if(type==2){
return [month, day].map(formatNumber).join('/')
}else{
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
}
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
//时间戳转为时间
function unixtoTime(ns,format) {
var result;
var time = new Date(ns*1000);
//result=format || 'YYYY年MM月DD日 HH时II分SS秒 WW';
result=format || 'YYYY年MM月DD日';
//console.log(format);
result=result.toUpperCase();
result=result.replace('YYYY',time.getFullYear());
var m=time.getMonth()+1;
result=result.replace('MM',m>9?m:"0"+m);
var d=time.getDate();
result=result.replace('DD',d>9?d:'0'+d);
var hh=time.getHours();
result=result.replace('HH',hh>9?hh:'0'+hh);
var ii=time.getMinutes();
result=result.replace('II',ii>9?ii:'0'+ii);
var ss=time.getSeconds();
result=result.replace('SS',ss>9?ss:'0'+ss);
var week;
switch (time.getDay()) {
case 0:week="日";break
case 1:week="一";break
case 2:week="二";break
case 3:week="三";break
case 4:week="四";break
case 5:week="五";break
case 6:week="六";break
}
result=result.replace('WW',week);
if(format.indexOf('DAY')>0){
// 获取当天 0 点的时间戳
var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
var day1 = timeStamp+86400//今天结束
var day2 = day1+86400//明天结束
//console.log('ns<day.getTime()',ns,day1,day2)
if(ns<day1){
result=result.replace('DAY','今天');
}else{
if(ns<day2){
result=result.replace('DAY','明天');
}else{
result=result.replace('DAY','');
}
}
}
return result;
}
//时间转为时间戳
function timetouUnix(dasr,connect)
{
if(connect){
var newstr = dasr.replace(/-/g,connect);
}else{
var newstr = dasr.replace(/-/g,'/');
}
var date = new Date(newstr);
var time_str = date.getTime().toString();
return time_str.substr(0, 10);
}
//支付
function orderPay(charge){
var that=this;
console.log(charge);
var obj = JSON.parse(charge)
console.log('obj:',obj);
wx.requestPayment({
'timeStamp': obj.timeStamp,
'nonceStr': obj.nonceStr,
'package': obj.package,
'signType': 'MD5',
'paySign': obj.paySign,
'success':function(res){
console.log('success:',res);
},
'fail':function(res){
console.log('fail:',res);
},
'complete':function(res){
}
})
}
module.exports = {
formatTime: formatTime,
unixtoTime:unixtoTime,
timetouUnix:timetouUnix,
orderPay:orderPay,
cgi:function(act){
return uri.HOST__LINE+act //正式
//return uri.HOST__TEST+act //测试
},
wxApiIsUse:function(api){
if(wx.canIUse(api)){
return true;
}else{
this.alert('当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。');
}
},
openXcx:function(data){
if(this.wxApiIsUse('navigateToMiniProgram')){
wx.navigateToMiniProgram({
appId: data.appId,
path: data.path,
extraData: {
foo: 'bar'
},
envVersion: 'trial',
//envVersion: '',
success(res) {
// 打开成功
}
})
}
},
loading:function(flag){
if(flag=='clear' || flag=="clean"){
wx.hideNavigationBarLoading();
return;
}
wx.showNavigationBarLoading();
},
postSuccessFun:function(json,uri_code){
console.log("APP::postSuccessFun",uri_code,json);
},
postFailFun:function(json,uri_code){
console.log(json,uri_code);
},
getToken:function(n_function){
var token=this.cache(uri.CACHE__TOKEN);
console.log("token:",token);
if(!token) {
this.loginStart(n_function);
return;
}
return token;
},
asyn:function(act,data,uri_code,n_function){//静默方式,不带loading
data=data||{};
var that=this;
data.token=that.cache(uri.CACHE__TOKEN);
wx.request({
url: that.cgi(act),
method:'POST',
data: data,
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function(res) {
console.log('request==>',that.http_build_query(data,that.cgi(act))+'\nrequest.success',res.data);
that.loading('clear');
if(n_function){
that.loginStart(n_function);
}
/*if(typeof res.data!='string'){
if(res.data.code!=200&&res.data.code!=1000){
console.log(res.data.code==-1,res.data.code);
if(res.data.code==-1) {
that.loginStart(n_function);
return;
}else{
that.alert(res.data.message);
return;
}
}
}*/
that.postSuccessFun(res.data,uri_code);
},
fail: function(res) {
console.log('request==>',that.http_build_query(data,that.cgi(act))+'\nrequest.fail',res);
that.loading('clear');
that.toast(res.errMsg);
that.postFailFun(res.data,uri_code);
}
})
},
post:function(act,data,uri_code,is_load,n_function,header={'Content-Type': 'application/x-www-form-urlencoded'}){
console.log('act:',act)
if(is_load!='0'){
this.loading();
}
this.asyn(act,data,uri_code,n_function,header);
},
upload:function(filePath,fileIndex,uri_code,sellerid,type,file){
var that=this;
this.loading();
if(this.wxApiIsUse('uploadFile')){
wx.uploadFile({
url: that.cgi('Seller/Index/UploadImages'),
filePath: filePath,
name: 'file',
formData:{
sellerid:sellerid,
type:type
},
success: function(res){
that.loading('clear');
that.postSuccessFun(res.data,uri_code,fileIndex);
},
fail: function(res) {
that.loading('clear');
that.toast("上传失败,请重试");
that.postFailFun(res.data,uri_code,fileIndex);
}
});
}
},
uploading:function(filePath,fileIndex,dir,uri_code,file){
var that=this;
this.loading();
console.log(filePath,fileIndex,dir,uri_code);
if(this.wxApiIsUse('uploadFile')){
wx.uploadFile({
url: 'https://xt05.colorcun.com/?s=App.Cookbook.UpLoadFile',
filePath: filePath,
name: 'file',
formData:{
dir:dir
},
success: function(res){
console.log('上传成功')
console.log(res)
that.loading('clear');
that.postSuccessFun(res.data,uri_code,fileIndex);
},
fail: function(res) {
that.toast("上传失败,请重试");
that.postFailFun(res.data,uri_code,fileIndex);
}
});
}
},
uploadImg:function(filePath,fileIndex,uri_code){
var that=this;
if(this.wxApiIsUse('uploadFile')){
wx.uploadFile({
url: that.cgi('bargainimage'),
filePath: filePath,
name: 'path',
formData:{
'token': that.getToken()
},
success: function(res){
console.log(res);
res.data=JSON.parse(res.data);
if(res.data.code!=200){
if(res.data.code==-1) {
wx.navigateTo({url:'/pages/login/index'});
return;
}else{
that.alert(res.data.message);
}
}
console.log("res-code-data",uri_code,res.data);
that.postSuccessFun(res.data,uri_code,fileIndex);
},
fail:function(res){
console.log(res);
}
});
}
},
download:function(id,uri_code,width){
var that=this;
this.loading();
if(this.wxApiIsUse('downloadFile')){
wx.downloadFile({
url: that.cgi('download'),
success: function(res) {
console.log("res-code-data",uri_code,res);
wx.playVoice({
filePath: res.tempFilePath
})
that.postSuccessFun(id,uri_code,width,res.data);
}
});
}
},
alert:function(msg,success,cancel,title){
wx.showModal({
title:title?title:"提示信息",
content:msg,
showCancel:typeof cancel=='undefined'?false:true,
success:function(res){
if(res.confirm){
if(success) success();
}else{
if(cancel) cancel();
}
}
});
},
toast:function(title,icon='success'){
wx.showToast({
title:title,
icon:icon
})
},
showLoading:function(title){
wx.showLoading({
title: '加载中',
})
},
getCommonType:function(key){
var that=this;
var common = that.cache(uri.CACHE__COMMON) || {time:0};
var time=Date.now();
if(common.time<time-600000){
wx.request({
url: that.cgi('commontype'),
header: {
'Content-Type': 'application/json'
},
success: function(res) {
if(res.data.code==200){
common={data:res.data.data,time:time};
//wx.setStorageSync(uri.CACHE__COMMON,common);
that.cache(uri.CACHE__COMMON,common)
}
}
})
}
if(!key) return common.data;
common = that.cache(uri.CACHE__COMMON) || {time:0};
return common.data[key];
},
getCommonTag:function(key,v_id){
var that=this;
var tagsdata=this.cache(uri.CACHE__COMMONTAG);
if(!tagsdata){
wx.request({
url: that.cgi(uri.CGI__USER_TCOMMONTAG),
data:{
'token': that.getToken()
},
header: {
'Content-Type': 'application/json'
},
success: function(res) {
if(res.data.code==200){
that.cache(uri.CACHE__COMMONTAG,res.data.data);
}
}
})
}
tagsdata=this.cache(uri.CACHE__COMMONTAG);
var result;
if(v_id){
tagsdata[key].map(function(v){
if(v.id==v_id){
result=v.tag_name;
}
})
}else{
result=tagsdata[key];
}
return result;
},
cache:function(key,value){
if(value){
wx.setStorageSync(key,value);
}
return wx.getStorageSync(key);
},
remove:function(key){
if(key){
wx.removeStorage({key: key})
}
},
image:function(id,width=""){
var url=this.cgi(uri.CGI__DOWNLOAD+'/id/'+id);
if(width){
url+='/width/'+width;
}
return url;
},
avatar:function(id,t='pu'){
return this.cgi(uri.CGI__AVATAR +'/'+t+'/'+id);
},
trim:function(str){
return str.replace(/^([ ]+)/,"").replace(/([ ]+)$/,"");
},
clear:function(str){//去除html标签
return this.trim(str.replace(/<[^>]+>/ig,""));
},
clearHtml:function(html){//去除html中特殊字符
html=html.replace(/[\n\r\t]+/ig,'');
html=html.replace(/<html[^>]*>(.*)<body[^>]*>/ig,'');
html=html.replace(/<div[^>]*>(.*)<article[^>]*>/ig,'');
html=html.replace(/<\/article[^>]*>(.*)<\/div[^>]*>/ig,'');
html=html.replace(/<style[^>]*>(.*)<\/style>/ig,'');
html=html.replace(/<\/body.*/ig,'');
html=html.replace(/<!--[^>]+>/ig,'');
html=html.replace(/"/ig,'');
return html;
},
val:function(e){
return e.detail.value;
},
attr:function(e,key){
return e.currentTarget.dataset[key];
},
extend:function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
},
getToken:function(n_function){
var token=this.cache(uri.CACHE__TOKEN);
console.log("token:",token);
if(!token) {
this.loginStart(n_function);
return;
}
return token;
},
loginStart:function(n_function){
console.log("n_function:",n_function,1111);
var that=this;
wx.login({
success: function(login_res) {
if (login_res.code) {
console.log('success');
console.log('wx.login.res' , login_res);
that.cache(uri.CACHE__LOGINCODE,login_res.code);
wx.getUserInfo({
success: function(res) {
res.code=login_res.code;
console.log('wx.getProviderInfo.res' , res);
var data={
code:login_res.code,
encryptData:res.encryptData,
encryptedData:res.encryptedData,
iv:res.iv,
rawData:res.rawData,
signature:res.signature,
appid:'wxc359908817c7bdd9',
secret:'a14a8415a501ade9542968d8a6504820',
}
wx.request({
url: that.cgi(uri.CGI__USER_XCXLOGIN),
data: data,
header: {
'content-type': 'application/json'
},
success: function(res) {
that.cache('setting','success');
that.cache(uri.CACHE__LOGINCODE,login_res.code);
/*if(n_function){
var pagelength=getCurrentPages().length;
console.log("pagelength:",pagelength);
console.log("getCurrentPages:",getCurrentPages());
if(typeof getCurrentPages()[pagelength-1][n_function]()!='undefined'){
getCurrentPages()[pagelength-1][n_function]();
}
}*/
return;
}
})
},
fail:function(){
that.cache('loginfail','fail');
if(n_function){
var pagelength=getCurrentPages().length;
console.log('hahahah');
getCurrentPages()[pagelength-1].onShow();
}
}
});
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
},
//重新调起授权
userInfoHandler:function(etarget){
if(this.wxApiIsUse('button.open-type.getUserInfo')){
if(etarget.detail&& etarget.detail.errMsg=='getUserInfo:ok'){
return true
//this.dc_loginStart()
}
}
},
getAccess_token: function (a, s, n_tempmessage) {
var that = this;
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + a + '&secret=' + s, //仅为示例,并非真实的接口地址
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log('access_token!!!!console:', res)
console.log('access_token:', res.data.access_token)
that.sendMessage(res.data.access_token, n_tempmessage);
}
})
},
//模板消息
sendMessage: function (a_t, dd) {
var that = this;
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + a_t, //仅为示例,并非真实的接口地址
data: dd,
method: 'POST',
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log('发送模板消息:',res)
//that.sendMessuc(res);
}
})
},
//获取当前网络状态
getNetwork:function(){
var that=this;
if(this.wxApiIsUse('getNetworkType')){
wx.getNetworkType({
success: function(res) {
that.getNetworkSuccess(res.networkType);
},
fail:function(res){
that.toast('获取网络状况失败!');
}
})
}
},
getNetworkSuccess:function(network){
return network;
},
compare:function(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
},
getJsonLength:function(jsonData){
var jsonLength = 0;
for(var item in jsonData){
jsonLength++;
}
return jsonLength;
},
testPhone:function(phone){
if(!/^1[3-9][0-9]{9}$/.test(phone)){
this.alert("请输入正确的电话号码");
return false;
}
},
//加入卡包
addInCard:function(sellerid){
var that = this;
wx.request({
url: that.cgi(uri.CGI__USER_GETSIGNOPENCARD),
method:'GET',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data:{
sellerid:1,
},
success: function(res) {
console.log(res)
var cardExtstr = res.data.data.cardExt
var cardId = res.data.data.cardid
console.log('cardExtstr:',cardExtstr);
wx.addCard({
cardList: [
{
cardId: cardId,
cardExt: cardExtstr,
}
],
success: function(res) {
console.log('success:',res)
that.cache('cardList',res.cardList);
},
fail:function(res) {
console.log('fail:',res)
},
})
}
})
},
//保存图片
saveImage: function(url){
var that = this;
wx.downloadFile({
url:url,
success:function(res){
var path = res.tempFilePath
wx.saveImageToPhotosAlbum({
filePath: path,
success(res) {
},
//保存图片重新授权
fail(res) {
wx.openSetting({
success: (res) => {
res.authSetting = {
"scope.writePhotosAlbum": true
}
}
})
},
})
},
fail:function(res){
}
})
},
//根据source判断会员卡1 或优惠券2
sourceFrom:function(){
var source = this.cache('source')
console.log('source:',source)
var title = ''
if(source==1){
title = '会员卡'
}else{
title = '优惠券'
}
wx.setNavigationBarTitle({
title:title
})
return source
},
//返回会员卡 优惠券的开通进度
stepSetting:function(stepnum){
var source = this.cache('source')
var step = {
content:['会员卡开通','会员卡设置','发放确认','发放完成'],
step:[{id:'0'},{id:'1'},{id:'2'},{id:'3'}],
stepnum:stepnum
}
if(step&&source==2){
step.content[0] = '优惠券开通'
step.content[1] = '优惠券设置'
}
return step
},
setBarTitle:function(title){
wx.setNavigationBarTitle({
title:title
})
},
//小数规则:小数只能存在一个小数点并且至多保留两位小数 数字首位可以为0 第二位不能为0
limitDigit:function(value,firsezero){
if(value.length==1&value=='.'){
value = '0'+'.'
}
if(value=='00'){
value = '0'
}
value = value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
//firsezero存在 首位不能为0
if(firsezero){
if(value.indexOf(".")< 0 && value !=""){//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
value= parseFloat(value);
}
}
return value
},
//
isEOne : function(arr,value){
for(var i = 0,vlen = arr.length; i < vlen; i++){
if(arr[i] == value){
return i;
}
}
return -1;
},
linkTo:function(url,sellerid,code){
var path='pages/menu/'+url;
if(code!=''){
path+='?sellerid='+sellerid+'&code='+code
}
if(sellerid!=''){
path+='?sellerid='+sellerid
}
console.log(path)
wx.navigateToMiniProgram({
appId: 'wx52646daaa3f42a4f',
path: path,
envVersion: 'release',
success:function(res) {
console.log(path)
}
})
},
setting:function(){
if(wx.canIUse('openSetting')==true){
wx.openSetting({
success:function(res){
console.log(res.authSetting)
return res.authSetting
}
})
}
},
//获取设备信息
getsystem:function(){
try {
var res = wx.getSystemInfoSync()
return res;
} catch (e) {
return false
}
},
http_build_query(obj,url=''){
let ps=[]
for(let i in obj){
if(typeof obj[i]=='undefined' || obj[i]==null) continue;
ps.push(i+'='+obj[i].toString())
}
ps=ps.join('&');
if(!url){
return ps;
}
url+=(url.indexOf('?')>-1?'&':'?')+ps;
return url;
}
}