buyFreeCoupon.js
50.6 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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
// pack-activity/pack/buyFreeCoupon.js
import util from '../../utils/util';
import App from '../../utils/api';
// import {monidata} from './aa';
Page({
/**
* 页面的初始数据
*/
data: {
options: {},
available: '1', //输入金额够优惠券最低消费1 不够0
couponArr: [], //所有券列表
finalList: [], //勾选的券列表
dataStr: Date.now() * 1 / 1000,
discountPrice: '', //优惠价格
actualPrice: '', //实付价格
inputValue: '', //输入的金额
canSolt: {}, //当前时间是哪个餐段、节假日
totalPrice: '', //送券的总金额
couponSwitch: false, //本单使用优惠券开关
consumeSwitch: false, //本单使用消费金开关
purePhoneNumber: '', //手机号
coexist: '0', //1可以同时使用券和消费金 0不可同时使用
ratio: '', //消费金支付占实际消费金额的百分比
consumeDiscount: '0.00', //消费金抵扣金额
consumePrice: '', //个人消费金余额
remainingConsume: '', //抵扣后剩余消费金余额
totalConsumePrice: 0, //赠送的消费金金额
noConfiguration: '', //配置消费金 0未配置 1已配置
returnData: '', //赠送消费金配置
isReturn: '', //赠送消费金的开关
},
sid: '', //扫码进入带的参数商家id
couponModal: '',
giveCouponModal: '',
consumeModal: '',
myToast:'',
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
this.couponModal = this.selectComponent("#couponModal");
this.giveCouponModal = this.selectComponent("#giveCouponModal");
this.consumeModal = this.selectComponent("#consumeModal");
if (options.sid) {
this.sid = options.sid
this.getSellerDetailFun(options.sid)
}
},
// 检测用户是否绑定手机号
getCheckUserHavePhone() {
App.Wechat.CheckUserHavePhone({
openid: getApp().openid,
}).then((json) => {
if (json.ret == 200) {
let data = json.data;
if (data) {
this.setData({
purePhoneNumber: data.phone,
})
this.getUserInfo()
} else {
this.setData({
purePhoneNumber: '',
})
}
}
})
},
// 获取用户在商家&所有消费金
getUserInfo() {
App.Activity.GetConsumeBySeller({
openid: getApp().openid,
sellerid: this.sid,
}).then((json) => {
if (json.ret == 200) {
let data = json.data;
if (data && data.length > 0) {
let obj = data[0]
console.log('获取用户在商家的消费金----', obj);
this.setData({
consumePrice: obj.balance ? (obj.balance * 1).toFixed(2) : '0.00',
remainingConsume: obj.balance ? (obj.balance * 1).toFixed(2) : '0.00',
consumeDiscount: '0.00', //消费金抵扣金额
})
} else {
this.setData({
consumePrice: '0.00',
remainingConsume: '0.00',
consumeDiscount: '0.00', //消费金抵扣金额
})
}
}
})
},
// 获取商家消费金规则
getConsumeConfigFun() {
App.Activity.GetConsumeConfig({
sellerid: this.sid,
}).then(res => {
if (res && res.data) {
let data = res.data;
let together = util.determine(data.together_json);
let returnData = util.determine(data.return_json);
returnData.ladder_data = returnData.ladder_data ? util.determine(returnData.ladder_data) : {};
console.log('111配置---',together);
console.log('222顾客支付后返消费金---',returnData);
this.setData({
noConfiguration: '1', //配置为1 未配置为0
coexist: together.is_coexist,
ratio: together.ratio_data ? together.ratio_data : '100',
couponSwitch: true,
consumeSwitch: together.is_coexist == '1' ? true : false,
returnData,
isReturn: data.is_return,
})
} else {
this.setData({
noConfiguration: '0', //配置为1 未配置为0
couponSwitch: true,
consumeSwitch: false,
returnData: null,
isReturn: '0',
})
}
})
},
// 使用券或者消费金的开关
switchChange(event) {
let type = event.currentTarget.dataset.type;
if (type == '1') {
this.setData({
couponSwitch: event.detail.value,
})
if (this.data.coexist == '0' && event.detail.value) {
this.setData({
consumeSwitch: false,
})
}
}
if (type == '2') {
this.setData({
consumeSwitch: event.detail.value,
})
if (this.data.coexist == '0' && event.detail.value) {
this.setData({
couponSwitch: false,
})
}
}
// 开或者关闭使用优惠券
if (this.data.couponSwitch) {
this.colationData()
}
if (!this.data.couponSwitch) {
this.getCoupon()
let val = parseFloat(this.data.inputValue);
let discountPrice = 0;
let actualPrice = (val - this.data.consumeDiscount - discountPrice).toFixed(2)
this.setData({
discountPrice: 0,
actualPrice: actualPrice > 0 ? actualPrice : '0.01'
})
}
// 开或者关闭使用消费金
if (this.data.consumeSwitch) {
let val = parseFloat(this.data.inputValue);
if (!val) return
let consumeDiscount = this.calculateConsumeGold(val);
let discountPrice = this.data.couponSwitch ? this.data.discountPrice : 0
let actualPrice = (val - consumeDiscount - discountPrice).toFixed(2)
let remainingConsume = (this.data.consumePrice * 1 - consumeDiscount).toFixed(2)
this.setData({
consumeDiscount,
actualPrice: actualPrice > 0 ? actualPrice : '0.01',
remainingConsume: remainingConsume
})
}
if (!this.data.consumeSwitch) {
let val = parseFloat(this.data.inputValue);
if (!val) return
let discountPrice = this.data.couponSwitch ? this.data.discountPrice : 0
let consumeDiscount = this.data.consumeSwitch ? this.data.consumeDiscount : 0
let actualPrice = (val - consumeDiscount - discountPrice).toFixed(2)
this.setData({
consumeDiscount: '0.00',
actualPrice: actualPrice > 0 ? actualPrice : '0.01',
remainingConsume: this.data.consumePrice,
})
}
},
// 按比例计算出的最大可用消费金
calculateConsumeGold(val) {
let ratio = this.data.ratio;
let consumePrice = parseFloat(this.data.consumePrice);
const maxByRatio = val * (ratio / 100).toFixed(2);
let availableConsumeGold = Math.min(val, maxByRatio).toFixed(2) * 1;
if (availableConsumeGold > consumePrice) availableConsumeGold = consumePrice
return availableConsumeGold;
},
// 打开优惠券弹框
showCouponModal() {
this.couponModal.showModal()
},
// 关闭优惠券弹框
closeCouponModal() {
this.couponModal.closeModal()
},
// 打开送券送消费金弹框
showgiveCouponModal() {
this.giveCouponModal.showModal()
},
// 打开消费金弹框
showConsumeModal() {
this.consumeModal.showModal()
},
// 关闭消费金弹框
closeConsumeModal() {
this.consumeModal.closeModal()
},
// 关闭优惠券弹框
closegiveCouponModal() {
this.giveCouponModal.closeModal()
this.getUserInfo()
},
// 跳转登录页
gotoLogin(event) {
wx.navigateTo({
url: util.http_build_query({
types: event.currentTarget.dataset.types
}, '/pages/customer/login')
})
},
// 获取店铺名称
getSellerDetailFun(sid) {
App.Customer.GetSellerDetail({
sid
}).then(res => {
let data = res.data;
this.setData({
seller: {
seller_image: data.seller_image,
sellername: data.sellername,
sid: data.id
}
})
// 判断当前时间餐段、节假日
this.getSellerDailyFun(data.daily)
})
},
// 赠送券
giftCouponsFun(priceSum,orderid) {
App.Activity.GetActivityConfig({
sellerid: this.data.seller.sid,
}).then(res => {
if (res.ret == 200) {
let data = res.data;
priceSum = parseFloat(priceSum)
// 满减
if (data.full_reduction && data.full_reduction == '1') {
let fullData = data.full_reduction_data ? util.determine(data.full_reduction_data) : ''
let coupons = fullData.coupons ? util.determine(fullData.coupons) : '';
const now = Math.floor(Date.now() / 1000);
console.log('满减---',{...fullData},{...coupons},now);
// 在送券活动开始的有效期之内
if (now >= parseInt(fullData.stime) && now <= parseInt(fullData.etime)) {
// rule 1每满门槛均发放(满50送一张券,金额是100送2张)
// rule 0仅发放一次(每次满足金额一个券只发一张)
if (fullData.rule == '1') {
const price = parseFloat(fullData.price)
const amount = parseInt(priceSum / price)
if (coupons.length > 0 && amount > 0) this.getCouponFun(coupons, '1', amount,orderid)
} else {
if (coupons.length > 0 && amount > 0) this.getCouponFun(coupons, '1', 1,orderid)
}
}
}
// 阶梯
if (data.stairs && data.stairs == '1') {
let stairsData = data.stairs_data ? util.determine(data.stairs_data) : ''
let ladder_data = stairsData.ladder_data ? util.determine(stairsData.ladder_data) : '';
const now = Math.floor(Date.now() / 1000);
console.log('阶梯---',{...stairsData},{...ladder_data},now);
// 在送券活动开始的有效期之内
if (now >= parseInt(stairsData.stime) && now <= parseInt(stairsData.etime)) {
let obj = this.findObjectByNum(ladder_data, priceSum)
console.log('在送券活动开始的有效期之内',{...obj});
if (obj && obj.coupons) {
let coupons = obj.coupons ? util.determine(obj.coupons) : '';
this.getCouponFun(coupons, '2', '1',orderid)
}
}
}
}
})
},
getCouponFun(coupons, type, amount,orderid) {
console.log('送的券coupons---', coupons, type, amount,orderid);
let str = coupons.map(item => item.id).join(',');
App.Activity.GetActivityById({
id: str,
}).then(res => {
if (res.ret == 200) {
let list = res.data;
let couponArr = [];
list.forEach(item => {
item.aexpiration = item.aexpiration ? util.determine(item.aexpiration) : '';
// 如果送券的数量大于剩余券的数量,设置送券的数量=剩余券的数量
if (type == '1' && amount > item.grant_last && item.grant_last > 0) {
item.amountA = item.grant_last
} else {
item.amountA = amount
}
console.log('券信息---',{...item});
// 只留下开启状态 && 在券的有效期内 && 可领取数量大于0的
if (item.is_open == '1' && (this.data.dataStr < item.etime * 1 || item.aexpiration.valid_forever == '1') && ((type == '1' && item.grant_last >= item.amountA) || (type == '2' && item.grant_last > 0))) {
console.log('可领取的券', item.aname, {
...item
});
couponArr.push({
...item
})
}
})
if (couponArr.length > 0) {
let result = [];
let ids = '';
let totalPrice = 0;
if (amount) {
couponArr.forEach(item => {
for (let i = 0; i < item.amountA; i++) {
result.push(item.id);
}
});
ids = result.join(",")
} else {
ids = coupons.map(item => item.id).join(',')
}
totalPrice = couponArr.reduce((sum, item) => sum + item.price * item.amountA, 0);
this.setData({
totalPrice,
})
this.setcouponFun(ids,orderid)
}
}
})
},
setcouponFun(str,orderid) {
console.log('领取券方法ids---', str,orderid);
App.Activity.SetActivityAsReserve({
aid: str,
orderid,
}).then((json) => {
if (json.ret != 200) {
wx.showToast({
title: res.msg,
duration: 2000,
mask: true
})
}
})
},
// 获取所有优惠券列表
getCoupon() {
App.Activity.ActivityListByOpenid({
sellerid: this.sid
}).then(res => {
if (res.ret == 200 && res.data && res.data.length > 0) {
let list = res.data
// console.log('listlistlist',JSON.stringify(list));
// list= list.concat(monidata)
list.forEach(detail => {
detail.exp_date = detail.exp_date ? util.determine(detail.exp_date) : '';
detail.arule = detail.arule ? util.determine(detail.arule) : '';
detail.expiration_date = detail.expiration_date ? util.determine(detail.expiration_date) : '';
detail.aexpiration = detail.aexpiration ? util.determine(detail.aexpiration) : '';
if (detail.arule) {
detail.accumulationShow = detail.arule.is_accumulation
}
if (detail.exp_date && detail.exp_date.week_data) {
let mor = this.hasConsecutiveSelect(detail.exp_date.week_data, '1').rArr.join('、')
let noon = this.hasConsecutiveSelect(detail.exp_date.week_data, '2').rArr.join('、')
let nig = this.hasConsecutiveSelect(detail.exp_date.week_data, '3').rArr.join('、')
if (mor) mor = '早餐:' + mor
if (noon) noon = '午餐:' + noon
if (nig) nig = '晚餐:' + nig
detail.morText = mor;
detail.noonText = noon;
detail.nigText = nig;
}
detail.checked = false;
detail.showCpupon = '0';
// 获取使用券的有效期
detail.cdate = detail.cdate * 1;
detail.useStime = '';
detail.useEtime = '';
let condition = detail.aexpiration
if (condition.valid_forever === '0' && condition.stime && condition.etime) {
detail.useStime = condition.stime;
detail.useEtime = condition.etime;
}
if (condition.valid_forever === '1') {
detail.foreverText = '永久有效';
}
if (condition.valid_forever === '0' && condition.today) {
let obj = this.setTimeRange(detail.cdate, 0, parseInt(condition.today) - 1);
detail.useStime = obj.useStime;
detail.useEtime = obj.useEtime;
}
if (condition.valid_forever === '0' && condition.tomorrow) {
let obj = this.setTimeRange(detail.cdate, 1, condition.tomorrow * 1);
detail.useStime = obj.useStime;
detail.useEtime = obj.useEtime;
}
if (condition.valid_forever === '0' && condition.sday && condition.eday) {
let obj = this.setTimeRange(detail.cdate, parseInt(condition.sday) - 1, parseInt(condition.eday) - 1);
detail.useStime = obj.useStime;
detail.useEtime = obj.useEtime;
}
if((detail.useStime>0 && detail.useEtime>0) || condition.valid_forever === '1') {
detail.endDateStr = condition.valid_forever == '1' ? '永久有效' : (util.unixtoTime(detail.useStime, 'YYYY-MM-DD') + '至' + util.unixtoTime(detail.useEtime, 'YYYY-MM-DD'));
}
})
list = list.filter(item => {
return (this.data.dataStr < (item.useEtime * 1) || item.aexpiration.valid_forever == '1');
})
list.sort((a, b) => {
return (a.etime * 1) - (b.etime * 1)
})
let couponArr = list
this.setData({
couponArr
})
}
})
},
// 勾选券
checkboxChange(e) {
console.log('checkbox发生change事件,携带value值为:', e.detail.value)
const list = this.data.couponArr
const values = e.detail.value
let arr = []
let currentCoupon = '0'; //没选券 为0 可叠加券1 不可叠加券2
let inputValue = parseFloat(this.data.inputValue)
let val = 0; //勾选的券 优惠金额的和
let descStr = 0; //勾选的券 每满金额的和
for (let i = 0, lenI = list.length; i < lenI; ++i) {
list[i].checked = false;
for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
if (list[i].activity_id === values[j]) {
val += parseFloat(list[i].price)
if (!list[i].desc || list[i].desc == 0) {
descStr += parseFloat(list[i].price)
} else {
descStr += parseFloat(list[i].desc)
}
arr.push({
...list[i]
})
list[i].checked = true
if (list[i].accumulationShow == '1') {
currentCoupon = '1'
break
} else {
currentCoupon = '2'
break
}
}
}
}
let remaining = inputValue - val; //剩余金额
console.log('没选券为0可叠加券1不可叠加券2', currentCoupon, remaining);
//没选券 所有可选的打开
if (currentCoupon == '0') {
list.forEach(item => {
if (item.canCheck == "1") {
item.showCpupon = '1';
}
})
}
//选的不可叠加券 其他所有的可叠加券都不可选
if (currentCoupon == '2') {
list.map((item) => {
if (item.checked) {
item.showCpupon = '1'
} else {
item.showCpupon = '0'
}
})
}
//选的可叠加券 其他所有的不可叠加券都不可选
if (currentCoupon == '1') {
list.forEach(item => {
if (item.checked || (item.accumulationShow == "1" && (inputValue - descStr) >= parseFloat(item.desc) && parseFloat(item.price) <= (inputValue - val))) {
item.showCpupon = '1';
} else {
item.showCpupon = '0';
}
})
}
this.setData({
couponArr: list
})
},
// 输入金额
bindKeyInput(e) {
console.log('输入金额,bindchange携带value值为:', e.detail.value);
let list = this.data.couponArr;
// 所有的券重置
list.forEach(i => {
i.checked = false;
i.showCpupon = '0'
})
this.setData({
inputValue: e.detail.value,
couponArr: list
})
if (e.detail.value == '') {
this.setData({
discountPrice: '',
actualPrice: '',
consumeDiscount: '',
remainingConsume: this.data.consumePrice
})
} else {
if (this.data.couponSwitch) {
this.colationData()
}
if (this.data.consumeSwitch && !this.data.couponSwitch) {
let val = parseFloat(this.data.inputValue);
let consumeDiscount = this.calculateConsumeGold(val);
let actualPrice = (val - consumeDiscount - this.data.discountPrice).toFixed(2)
let remainingConsume = (this.data.consumePrice * 1 - consumeDiscount).toFixed(2)
this.setData({
consumeDiscount,
actualPrice: actualPrice > 0 ? actualPrice : '0.01',
remainingConsume: remainingConsume
})
}
}
},
// 点确认选择
checkCertificate() {
this.closeCouponModal()
let list = this.data.couponArr;
list = list.filter(i => {
return i.checked
})
let price = 0;
list.forEach(i => {
price += parseFloat(i.price)
})
console.log('优惠金额----', price);
let val = parseFloat(this.data.inputValue);
let actualPrice = (val - price - this.data.consumeDiscount).toFixed(2)
price = price.toFixed(2)
this.setData({
discountPrice: price,
actualPrice: actualPrice > 0 ? actualPrice : 0.01,
})
console.log('点确认选择后', list);
},
// 处理显示券可用、不可用的列表
async colationData() {
let list = this.data.couponArr;
list = await this.filterCoupons(list);
let obj = await this.findBestCoupons(list);
list = obj.arr
console.log('处理过后的券数据', list);
list.sort((a, b) => b.canCheck - a.canCheck);
list.sort((a, b) => b.showCpupon - a.showCpupon);
if (this.data.consumeSwitch) {
let amount = parseFloat(this.data.inputValue);
let num = (amount - this.data.discountPrice).toFixed(2);
let val = parseFloat(num);
let consumeDiscount = this.calculateConsumeGold(val);
let actualPrice = (amount - consumeDiscount - this.data.discountPrice).toFixed(2)
let remainingConsume = (this.data.consumePrice * 1 - consumeDiscount).toFixed(2)
this.setData({
consumeDiscount,
actualPrice: actualPrice > 0 ? actualPrice : '0.01',
remainingConsume: remainingConsume
})
}
this.setData({
couponArr: list,
finalList: obj.finalList
})
},
// 付款
confirmPayment: util.throttle(function () {
let that = this;
let actualPrice = this.data.actualPrice
if (actualPrice <= 0) {
return
}
let str = this.data.finalList.map(item => item.activity_id).join(',');
console.log('核销所勾选的券传参', str);
let params = {
sellerid: this.data.seller.sid,
price: actualPrice,
}
if (this.data.consumeDiscount) {
params.consume = this.data.consumeDiscount;
params.phone = this.data.purePhoneNumber;
}
if (str) {
params.activity_id = str;
}
App.PayOnline.CombineTransactionsByNewActivity(params).then(res => {
console.log('付款信息', res.data);
if (res.ret != '200') {
wx.showToast({
title: res.msg,
duration: 1000,
icon: 'none',
})
}
if (res.ret == '200') {
wx.requestPayment({
timeStamp: res.data.timeStamp + '',
nonceStr: res.data.nonceStr,
package: res.data.package,
signType: res.data.signType,
paySign: res.data.paySign,
success(ress) {
if (ress.errMsg == 'requestPayment:ok') {
that.giftCouponsFun(actualPrice,res.data.orderid) //送券
that.giftConsumeFun(actualPrice, res.data.orderid) //送消费金
setTimeout(() => {
console.log('送券金额----', that.data.totalPrice);
console.log('送消费金----', that.data.totalConsumePrice);
if (that.data.totalPrice > 0 || that.data.totalConsumePrice > 0) {
wx.reLaunch({
url: util.http_build_query({
totalPrice: that.data.totalPrice,
totalConsumePrice: that.data.totalConsumePrice,
}, '/pack-activity/pack/paySuccess')
})
}
}, 1000);
console.log('支付成功', ress);
return
}
that.payFail()
console.log('支付失败11', ress);
return that.myToast.showToast('支付失败,请重新下单', 2000)
},
fail(ress) {
that.payFail()
console.log('支付失败22', ress);
return that.myToast.showToast('支付失败,请重新下单', 2000)
},
})
}
})
},3000),
payFail() {
this.setData({
inputValue: '',
finalList: [],
couponArr: [],
discountPrice: '0.00',
actualPrice: '',
consumeDiscount: '0.00', //消费金抵扣金额
})
this.getCoupon()
this.getUserInfo()
},
giftConsumeFun(priceSum, orderid) {
let isReturn = this.data.isReturn;
let data = this.data.returnData;
const now = Math.floor(Date.now() / 1000);
let totalConsumePrice = 0;
if (isReturn == '1' && data && now >= parseInt(data.stime) && now <= parseInt(data.etime)) {
priceSum = parseFloat(priceSum)
// 按百分比 is_ratio 1按比例 0按阶梯 ladder_data
if (data.is_ratio == '1' && data.ratio_data) {
totalConsumePrice = priceSum * (data.ratio_data / 100).toFixed(2);
console.log('送消费金百分比----', totalConsumePrice);
}
// 阶梯
if (data.is_ratio == '0' && data.ladder_data) {
totalConsumePrice = this.calculateGiftAmount(priceSum, data.ladder_data)
console.log('送消费金阶梯----', totalConsumePrice);
}
if (totalConsumePrice > 0) this.getConsumeFun(totalConsumePrice)
this.setData({
totalConsumePrice: (totalConsumePrice * 1).toFixed(2)
})
}
},
// 为用户增加消费金
getConsumeFun(amount) {
App.Activity.SetConsumeByOpenid({
phone: this.data.purePhoneNumber,
openid: getApp().openid,
amount,
sellerid: this.data.seller.sid
}).then(res => {
if (res.data == '0') {
wx.showToast({
title: '消费金领取失败!',
duration: 1000,
icon: 'none',
mask: true
});
}
})
},
calculateGiftAmount(priceSum, ladder_data) {
if (!ladder_data || ladder_data.length === 0) {
return 0; // 没有阶梯数据,返回0
}
// 将阶梯数据按 give_price 从大到小排序,确保匹配最高阶梯
const sortedLadder = [...ladder_data].sort((a, b) =>
parseFloat(b.give_price) - parseFloat(a.give_price)
);
// 遍历排序后的阶梯,找到第一个满足条件的
for (let i = 0; i < sortedLadder.length; i++) {
const ladder = sortedLadder[i];
const threshold = parseFloat(ladder.give_price);
if (priceSum >= threshold) {
return ladder.back_price;
}
}
return 0; // 不满足任何阶梯条件
},
// 核销所勾选的券
writeOff() {
console.log('勾选的券', this.data.finalList);
if (this.data.finalList.length > 0) {
let str = this.data.finalList.map(item => item.activity_id).join(',');
console.log('核销所勾选的券传参', str);
App.Activity.SetActivityStatus({
id: str,
}).then(res => {
if (res.ret == '200') {
console.log('核销成功', str);
this.setData({
inputValue: '',
finalList: [],
couponArr: [],
discountPrice: '0.00',
actualPrice: '',
})
this.getCoupon()
}
})
}
},
// 判断券开启、有效期结束时间、领取后有效天数、领取当天可用、不可用日期
filterCoupons(list) {
const currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
let obj = this.data.canSolt
console.log('当前餐段、是不是法定节假日', {
...obj
});
const isTimestampInRange = (startTimestamp, endTimestamp) => {
const currentTimestamp = Math.floor(Date.now() / 1000);
return currentTimestamp >= startTimestamp && currentTimestamp <= endTimestamp;
};
list.forEach(coupon => {
// 判断当前时间在不在 券的有效期内
const isUseDate = isTimestampInRange(coupon.useStime, coupon.useEtime);
let selectedValue = true;
let str = true
if (coupon.exp_date && coupon.exp_date.week_data && coupon.exp_date.week_data.length > 0) {
let today = new Date(); // 获取今天是星期几(0-6,0表示周日)
let dayOfWeek = today.getDay();
let arr = coupon.exp_date.week_data
let todayArr = arr[dayOfWeek];
let legalHolidayValue = arr[arr.length - 1];
if (obj.can === "晚餐") {
selectedValue = todayArr.selectNig;
} else if (obj.can === "午餐") {
selectedValue = todayArr.selectNoon;
} else if (obj.can === "早餐") {
selectedValue = todayArr.selectMor;
}
selectedValue = !selectedValue
// console.log(coupon.aname, coupon.exp_date.week_show, `今天是 ${todayArr.title},选择值为: ${selectedValue}`);
// 根据 isshow 判断法定假日是否可用
if (obj.isshow === "1") {
if (obj.can === "晚餐") {
str = legalHolidayValue.selectNig;
} else if (obj.can === "午餐") {
str = legalHolidayValue.selectNoon;
} else if (obj.can === "早餐") {
str = legalHolidayValue.selectMor;
}
str = !str
}
// console.log(coupon.aname, '法定节假期', `,选择值为: ${str}`);
}
let availableDate = true;
if (str || selectedValue) {
availableDate = true
}
if (!str || !selectedValue) {
availableDate = false
}
if ((str && !selectedValue) || (!str && selectedValue)) {
availableDate = false
}
coupon.isOk = (isUseDate || coupon.aexpiration.valid_forever == '1') && (availableDate || coupon.exp_date.week_show == '无') ? '1' : '0'; //是否在可用时间内 1可使用 2不可使用
});
return list;
},
// 最优惠的消费券组合(消费要求为无门槛 或者 满足优惠券使用金额 && 勾选最优的、最早到期的)
findBestCoupons(arr) {
console.log('勾选最优的之前', arr);
let consumeDiscount = this.data.consumeDiscount;
let inputValue = this.data.inputValue;
const amount = parseFloat(inputValue - consumeDiscount);
const validCoupons = arr.filter(coupon => (coupon.isOk == '1' && parseFloat(coupon.desc) <= amount) && amount>=parseFloat(coupon.price));
// 排序后,优先选择最大优惠的券
validCoupons.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
arr.forEach(item => {
const isValid = validCoupons.some(validCoupon => validCoupon.activity_id == item.activity_id);
item.canCheck = isValid ? '1' : '0'; // 如果在 validCoupons 中,设置 canCheck 为 1,否则为 0
});
console.log('可以勾选的券 && 满足付款条件的券', validCoupons);
let stackingCoupons = validCoupons.filter(i => {
return i.accumulationShow == '1'
})
let list1 = []; // 可叠加的优惠券组合
let list2 = []; // 最优惠的不可叠加的优惠券
let finalList = []; //最终用的优惠券组合
// 计算可叠加的组合
let remainingPrice = amount; // 剩余金额
let totalDiscount = 0; // 总优惠金额
// 1. 优先排序 desc 为空或为 0 的,再根据 price 从大到小排序,再根据满减条件 desc 从大到小排序
stackingCoupons.sort((a, b) => {
if (a.desc === '0' || a.desc === '') return -1; // 优先选择 desc 为空或为 0 的
if (b.desc === '0' || b.desc === '') return 1;
if (parseFloat(b.price) !== parseFloat(a.price)) return parseFloat(b.price) - parseFloat(a.price); // 按 price 从大到小
return parseFloat(b.desc) - parseFloat(a.desc); // 按满减条件 desc 从大到小
});
console.log('排序后的可叠加券列表',stackingCoupons);
// 2. 从排序后的券中选择
for (let coupon of stackingCoupons) {
let couponDesc = parseFloat(coupon.desc);
let couponPrice = parseFloat(coupon.price);
let kyNum = Math.floor(remainingPrice / couponDesc);// 计算券可用张数
if (couponDesc === 0) {// 如果满减条件为 0,直接选择
list1.push(coupon);
remainingPrice -= couponPrice; // 减去价格
totalDiscount += couponPrice; // 计算优惠金额
continue;
}
// 如果剩余金额足够,选择券
if (remainingPrice >= couponDesc) {
// 计算实际使用的张数,不能超过 kyNum
let usedCount = Math.min(kyNum, 1); // 假设每次只使用一张
let potentialDiscount = couponDesc * usedCount; // 计算潜在的优惠金额
if (totalDiscount + potentialDiscount <= amount) {// 检查总优惠金额是否会超过总金额
list1.push(coupon);
remainingPrice -= couponPrice * usedCount; // 减去价格
totalDiscount += potentialDiscount; // 计算优惠金额
}
}
// 如果剩余金额已经小于等于 0,停止选择
if (remainingPrice <= 0) break;
}
// 遍历有效优惠券,寻找不可叠加的优惠券
let maxNonStackableValue = 0
validCoupons.forEach(coupon => {
if (coupon.accumulationShow === '0') {
const discountAmount = parseFloat(coupon.price);
// 计算实际支付金额
const finalAmount = amount - discountAmount;
// 确保实际支付金额不小于0,并且是最优惠的
if (finalAmount >= 0) {
if (maxNonStackableValue<discountAmount) {
maxNonStackableValue = discountAmount
list2=[{...coupon}]
}
}
}
});
console.log('可叠加优惠券组合', list1);
console.log('不可叠加的优惠券', list2);
// 计算两个列表的最大优惠值
let maxStackableValue = list1.reduce((total, coupon) => total + parseFloat(coupon.price), 0);
console.log('可叠加优惠券组合总金额', maxStackableValue);
console.log('不可叠加的优惠券总金额', maxNonStackableValue);
// 比较两个最大值并输出结果
if (maxStackableValue > maxNonStackableValue) {
finalList = list1
} else if (maxStackableValue < maxNonStackableValue) {
finalList = list2
} else {
console.log(`两者的优惠值相同: ${maxStackableValue}`);
let copiedList1 = JSON.parse(JSON.stringify(list1));
let copiedList2 = JSON.parse(JSON.stringify(list2));
let minList1 = copiedList1.length > 0 ? Math.min(...copiedList1.map(item => item.useEtime)) : Infinity;
let minList2 = copiedList2.length > 0 ? Math.min(...copiedList2.map(item => item.useEtime)) : Infinity;
// 判断最小的 useEtime 是在 list1 还是 list2
if (minList1 <= minList2) {
console.log('最小的在 list1 中', list1);
finalList = list1
} else {
console.log('最小的在 list2 中', list2);
finalList = list2
}
}
console.log('选中的券组合', finalList);
let discountPrice = 0;
// 更新选中的优惠券
finalList.forEach(coupon => {
let target = arr.findIndex(obj => obj.activity_id === coupon.activity_id);
if (target>-1) {
arr[target].showCpupon = 1;
arr[target].checked = true;
discountPrice += parseFloat(coupon.price); // 使用 parseFloat 确保类型正确
}
console.log('选中的券', {
...coupon
});
});
discountPrice = discountPrice.toFixed(2)
console.log('总优惠金额:', discountPrice);
let actualPrice = (amount - discountPrice).toFixed(2);
console.log('实际支付金额:', actualPrice);
this.setData({
discountPrice,
actualPrice: actualPrice > 0 ? actualPrice : '0.01', // 确保实际支付金额不小于0.01
});
return {
arr,
finalList, // 返回可叠加和不可叠加的优惠券组合
};
},
// 计算免费券有效期的起始、结束日期
setTimeRange(cdate, startOffset, endOffset) {
const startDate = new Date((cdate + startOffset * 86400) * 1000);
startDate.setHours(0, 0, 0, 0);
let useStime = startDate.getTime() / 1000
const endDate = new Date((cdate + endOffset * 86400) * 1000);
endDate.setHours(23, 59, 59, 0);
let useEtime = endDate.getTime() / 1000
return { useStime, useEtime };
},
// 处理优惠券不可用日期数据
hasConsecutiveSelect(arr, type) {
let firstTitle = null;
let lastTitle = null;
let rArr = []
let num = 0
for (let i = 0; i < arr.length; i++) {
let str = type == '1' ? arr[i].selectMor : type == '2' ? arr[i].selectNoon : type == '3' ? arr[i].selectNig : '';
if (str) {
rArr.push(arr[i].title)
num++
if (num == 1) {
firstTitle = arr[i].title
}
if (num >= 5) {
lastTitle = arr[i].title
}
if (num >= 5 && i >= (arr.length - 1)) {
let fi = rArr.findIndex((item) => {
return item == firstTitle
})
rArr.splice(fi, num, firstTitle + '至' + lastTitle)
num = 0
}
} else {
if (num < 5) {
num = 0
firstTitle = null;
lastTitle = null;
} else {
let fi = rArr.findIndex((item) => {
return item == firstTitle
})
rArr.splice(fi, num, firstTitle + '至' + lastTitle)
num = 0
}
}
}
return {
rArr,
lastTitle,
firstTitle
};
},
// 判断当前时间餐段、节假日
getSellerDailyFun(lunchDis) {
let lunchDinnerList = [];
if (lunchDis.morning) {
lunchDinnerList.push({
can: "早餐",
solt: 1,
class: "morning",
})
}
if (lunchDis.noon) {
lunchDinnerList.push({
can: "午餐",
solt: 2,
class: "dinner",
})
}
if (lunchDis.night) {
lunchDinnerList.push({
can: "晚餐",
solt: 3,
class: "lunch",
})
}
const currentTime = new Date().toLocaleTimeString('en-US', {
hour12: false,
hour: '2-digit',
minute: '2-digit'
});
let obj = this.checkTimeInInterval(currentTime, lunchDis, lunchDinnerList);
//节假日数组
var holidays = [
'2025-1-1', // 元旦
'2025-1-28', // 春节
'2025-1-29', // 春节
'2025-1-30', // 春节
'2025-1-31', // 春节
'2025-2-1', // 春节
'2025-2-2', // 春节
'2025-2-3', // 春节
'2025-2-4', // 春节
'2025-4-4', //清明
'2025-4-5', //清明
'2025-4-6', //清明
'2025-5-1', // 劳动节
'2025-5-2', // 劳动节
'2025-5-3', // 劳动节
'2025-5-4', // 劳动节
'2025-5-5', // 劳动节
'2025-5-31', // 端午节
'2025-6-1', // 端午节
'2025-6-2', // 端午节
'2025-10-1', // 国庆节、中秋节
'2025-10-2', // 国庆节、中秋节
'2025-10-3', // 国庆节、中秋节
'2025-10-4', // 国庆节、中秋节
'2025-10-5', // 国庆节、中秋节
'2025-10-6', // 国庆节、中秋节
'2025-10-7', // 国庆节、中秋节
'2025-10-8', // 国庆节、中秋节
];
//周末上班日期数组
var nWeekend = [
'2025-1-26', //春节调整
'2025-2-8', //春节调整
'2025-4-27', //五一调整
'2025-9-28', //国庆调整
'2025-10-11', //国庆调整
];
var curdate = new Date();
var year = curdate.getFullYear();
var month = curdate.getMonth() + 1;
var date = Math.floor((curdate.getTime() % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60 * 24)) + 1; // 计算当前日期
var formattedDate = year + "-" + month + "-" + date;
obj.isshow = '0'
//在节假日数组内
if ((holidays.indexOf(formattedDate) >= 0) && nWeekend.indexOf(formattedDate) < 0) {
obj.isshow = '1'
} else {
obj.isshow = '0'
}
console.log('不可用日期信息餐段节假日', {...obj});
if (obj && obj.can && obj.solt) {
this.setData({
canSolt: {
...obj
}
})
}
this.getCoupon()
},
// 传参currentTime 当前时间 例16:51 lunchDis 餐段 {morning: "07:00-10:00",night: "16:00-21:00",noon: "11:00-14:30"}
// 判断当前时间餐段
checkTimeInInterval(currentTime, lunchDis, lunchDinnerList) {
const [currentHour, currentMinute] = currentTime.split(':');
const [morningHour2, morningMinute2] = lunchDis.morning ? lunchDis.morning.split("-")[1].split(':') : [0, 0];
const [noonHour1, noonMinute1] = lunchDis.noon ? lunchDis.noon.split("-")[0].split(':') : [0, 0];
const [noonHour2, noonMinute2] = lunchDis.noon ? lunchDis.noon.split("-")[1].split(':') : [0, 0];
const [nightHour1, nightMinute1] = lunchDis.night ? lunchDis.night.split("-")[0].split(':') : [0, 0];
const currentTimestamp = new Date().setHours(currentHour, currentMinute, 0, 0); //当前时间
const time1 = (morningHour2 && morningMinute2) ? new Date().setHours(morningHour2, morningMinute2, 0, 0) : ''; //早餐截止时间
const time2 = (noonHour1 && noonMinute1) ? new Date().setHours(noonHour1, noonMinute1, 0, 0) : ''; //午餐开始时间
const time3 = (noonHour2 && noonMinute2) ? new Date().setHours(noonHour2, noonMinute2, 0, 0) : ''; //午餐截止时间
const time4 = (nightHour1 && nightMinute1) ? new Date().setHours(nightHour1, nightMinute1, 0, 0) : ''; //晚餐开始时间
// 1个餐段
if (lunchDinnerList.length == 1) {
return {
solt: lunchDinnerList[0].solt,
can: lunchDinnerList[0].can
};
}
// 2个餐段(早,午)(早,晚)(午,晚)
if (lunchDinnerList.length == 2) {
let obj1 = lunchDinnerList[0];
let obj2 = lunchDinnerList[1];
let timeA1 = obj1.solt == 1 ? time1 : time2;
let timeA2 = obj2.solt == 2 ? time2 : time4;
if (currentTimestamp < timeA1) { // 在早餐/午餐截止时间之前
return obj1.solt == 1 ? {
solt: 1,
can: '早餐'
} : {
solt: 2,
can: '午餐'
}
} else if (currentTimestamp > timeA1 && currentTimestamp < timeA2) { //在早餐/午餐截止时间之后 && 午餐/晚餐开始时间之前
return obj1.solt == 1 ? {
solt: 1,
can: '早餐'
} : {
solt: 2,
can: '午餐'
};
} else if (currentTimestamp > timeA2) { //在午餐/晚餐截止时间之后
return obj2.solt == 2 ? {
solt: 2,
can: '午餐'
} : {
solt: 3,
can: '晚餐'
};
}
}
// 3个餐段(早,午,晚)
if (lunchDinnerList.length == 3) {
if (currentTimestamp < time1) { //当前时间 在早餐截止时间之前
return {
solt: 1,
can: '早餐'
};
} else if (currentTimestamp > time1 && currentTimestamp < time2) { //在早餐截止时间之后 && 午餐开始时间之前
return {
solt: 1,
can: '早餐'
};
} else if (currentTimestamp > time2 && currentTimestamp < time3){
return {
solt: 2,
can: '午餐'
}
} else if (currentTimestamp > time3 && currentTimestamp < time4) { //在午餐截止时间之后 && 晚餐开始时间之前
return {
solt: 2,
can: '午餐'
};
} else {
return {
solt: 3,
can: '晚餐'
};
}
}
},
// 获取当前应该赠送的阶梯券
findObjectByNum(arr, num) {
let result = {};
let maxPrice = -Infinity;
for (let i = 0; i < arr.length; i++) {
const price = parseFloat(arr[i].price, 10);
if (price <= num && price > maxPrice) {
maxPrice = price;
result = arr[i];
}
}
return result;
},
// 跳转到我的券列表
certificate() {
wx.reLaunch({
url: '/pages/me/coupon_news'
})
},
// 跳转到我的消费金列表
gotoConsumeList() {
wx.reLaunch({
url: '/pages/me/consumeAmount'
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
this.myToast = this.selectComponent("#myToast")
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
this.getCheckUserHavePhone()
this.getConsumeConfigFun()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})