rx
2023-12-13 923fa13e40ca7c38bb9560c0d0c37f2787b0b548
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
package com.hx.phip.controller.market;
 
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.common.BaseController;
import com.hx.exception.TipsException;
import com.hx.mybatisTool.SqlSentence;
import com.hx.phiappt.common.*;
import com.hx.phiappt.constants.tool.employee.EmployeeTool;
import com.hx.phiappt.constants.tool.shop.ShopTool;
import com.hx.phiappt.dao.mapper.*;
import com.hx.phiappt.model.BaseEntity;
import com.hx.phiappt.model.EmployeeRole;
import com.hx.phiappt.model.User;
import com.hx.phiappt.model.coupon.Coupon;
import com.hx.phiappt.model.limit.LimitOther;
import com.hx.phiappt.model.limit.LimitTotal;
import com.hx.phiappt.model.market.*;
import com.hx.phip.service.EmployeeRoleService;
import com.hx.phip.service.market.MarketActivityService;
import com.hx.resultTool.Result;
import com.hx.util.DateUtil;
import com.hx.util.StringUtils;
import com.hz.his.dto.marketing.MarketActivityDto;
import com.hz.his.dto.marketing.common.MarCommonReturnDto;
import com.hz.his.dto.marketing.common.MarketingReturnDto;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 营销活动(热门活动)
 * @USER: fhx
 * @DATE: 2023/7/3
 **/
@Slf4j
@RestController
@RequestMapping("/market/activity")
public class MarketActivityController extends BaseController {
 
    @Resource
    private MarketActivityService marketActivityService;
    @Resource
    private EmployeeRoleService employeeRoleService;
 
    /** 列表 */
    @PostMapping("/list")
    public Result list(@RequestBody(required = false) MarketActivityDto dto) {
 
        if(dto == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求对象为空!");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
 
        StringBuffer sql = new StringBuffer();
        sql.append(" select a.id, a.title, a.intro, a.managerName, a.isUp, a.couponNum, a.isLimitShop  ")
                .append(" , date_format(a.startTime, '%Y/%m/%d') as startTime ")
                .append(" , date_format(a.endTime, '%Y/%m/%d %H:%i:%s') as endTime ");
                //子查询第一张轮播图
//              .append(" , (select imgUrl from market_activity_banner ab where ab.isDel = 0 and ab.marketActivityId = a.id order by sortNo asc limit 1) as imgUrl ")
        //用户领取
        if(StringUtils.noNull(dto.getUserId())){
            values.put("userId", dto.getUserId());
            sql.append(" , ( select ifnull(sum(jr.receiveNum), 0) from market_activity_join_record jr where jr.isDel = 0 and jr.marketActivityId = a.id and jr.userId = #{m.userId} ) as receiveNum ");
        }else{
            sql.append(" , 0 as receiveNum ");
        }
 
        sql.append(" from market_activity a where a.isDel = 0  ");
 
        //处理列表条件查询sql
        handleListConditionQuerysSql(dto, sql, values);
 
        sql.append(" order by a.createTime desc ");
        sqlSentence.setSqlSentence(sql.toString());
 
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
        PageInfo pageInfo = new PageInfo(list);
 
        return Result.success(pageInfo);
    }
 
    /** 分类tab列表 */
    @RequestMapping("/tabData")
    public Result tabData(@RequestBody MarketActivityDto dto){
 
        //查询活动分类
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("type", BaseClassifyConstants.TYPE_MARKET_ACTIVITY);
        sqlSentence.setSqlSentence(" select id, name, 0 as num from base_classify where isDel = 0 and type = #{m.type} order by sortNo asc ");
        List<Map<String, Object>> list = commonService.selectListMap(BaseClassifyMapper.class, sqlSentence);
 
        StringBuffer sql = new StringBuffer();
        sql.append(" select a.id, a.classifyId from market_activity a where a.isDel = 0  ");
        //处理列表条件查询sql
        handleListConditionQuerysSql(dto, sql, values);
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> activityList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
 
        if(activityList != null && activityList.size() > 0){
            //按分类id分组计算
            Map<String, Long> countMap = activityList.stream().collect(Collectors.groupingBy(s->s.get("classifyId").toString(), Collectors.counting()));
            //遍历赋值对应数量
            for(Map<String, Object> m : list){
                if(countMap.containsKey(m.get("id").toString())){
                    m.put("num", countMap.get(m.get("id").toString()));
                }
            }
        }
 
        JSONObject data = new JSONObject();
        data.put("list", list);
        data.put("allNum", activityList.size());
        return Result.success(data);
    }
 
    /** 顶部轮播图数据 */
    @RequestMapping("/topBannerData")
    public Result topBannerData(@RequestBody MarketActivityDto dto){
 
        //用户为空直接返回空数据
        if(StringUtils.isEmpty(dto.getUserId())){
            return Result.success();
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        StringBuffer sql = new StringBuffer();
        sql.append(" select a.id, bc.name as classifyName, a.title, a.intro ")
                .append(" , date_format(a.startTime, '%Y.%m.%d') as startTime ")
                .append(" , date_format(a.endTime, '%Y.%m.%d') as endTime ")
                .append(" from market_activity a  ")
                .append(" left join base_classify bc on bc.id = a.classifyId ")
                .append(" where a.isDel = 0 ");
 
        //设置只查询上架的
        dto.setIsUp(BaseEntity.YES);
        //处理列表条件查询sql
        handleListConditionQuerysSql(dto, sql, values);
        //查询用户未查看过的活动
        values.put("userId", dto.getUserId());
        sql.append(" and (select count(1) from market_activity_view_record vr where vr.isDel = 0 and vr.marketActivityId = a.id and vr.userId = #{m.userId} ) = 0 ");
        sql.append(" order by a.createTime desc ");
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
 
        JSONObject data = new JSONObject();
        data.put("list", list);
        return Result.success(data);
    }
 
    /** 详情 */
    @PostMapping("/detail")
    public Result detail(@RequestBody(required = false) MarketActivityDto dto){
 
        if(dto == null || StringUtils.isEmpty(dto.getId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询标识不能为空!");
        }
 
        MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getId());
        if(marketActivity == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
        }
 
        User user = null;
        if(StringUtils.noNull(dto.getUserId())){
            user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("marketActivityId", marketActivity.getId());
        StringBuffer sql = new StringBuffer();
 
        //营销活动关联轮播图--------------------------------------------------
        sqlSentence.setSqlSentence(" select imgUrl from market_activity_banner where isDel = 0 and marketActivityId = #{m.marketActivityId} order by sortNo asc ");
        List<Map<String, Object>> bannerList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
 
        //营销活动关联优惠券--------------------------------------------------
        //查询用户优惠券码判断用户是否已领取过
        String receiveNumSql = " 0 as receiveNum ";
        //查询用户对应优惠券是否有待审核数量
        String waitApproveSql = " 0 as waitApproveNum ";
 
        if(StringUtils.noNull(dto.getUserId())){
            values.put("userId", dto.getUserId());
//            receiveNumSql = "( select count(1) from market_activity_receive_record_item i join market_activity_receive_record r on r.id = i.receiveRecordId  where i.isDel = 0 and r.userId = #{m.userId} and i.marketActivityId = ai.marketActivityId and i.commonId = ai.commonId )  as receiveNum ";
            receiveNumSql = "( select count(1) from market_activity_receive_record_item i join market_activity_receive_record r on r.id = i.receiveRecordId  where i.isDel = 0 and r.userId = #{m.userId} and i.marketActivityId = ai.marketActivityId and i.activityItemId = ai.id )  as receiveNum ";
            //是否有待审核数量
//            values.put("approveStatus", MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT);
            waitApproveSql = "( select count(1) from market_activity_receive_record_item i join market_activity_receive_record r on r.id = i.receiveRecordId  where i.isDel = 0 and r.userId = #{m.userId} and i.marketActivityId = ai.marketActivityId and i.activityItemId = ai.id and i.approveStatus = #{m.approveStatus} )  as waitApproveNum ";
        }
 
        sql.setLength(0);
        values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
        sql.append(" select ai.marketActivityId, ai.id as activityCouponId, ai.commonId as couponId")
                .append(" , ai.limitRecNum, ai.groupId, ai.isApprove  ")
                .append(" , c.title, c.type, c.discountAmount, c.discountNum ")
                .append(" , c.conditionType, c.amountSatisfied, c.platformType, c.issueType ")
                .append(" , c.useProjectType, c.useGoodsType, c.usePromotionType, c.useCardType ")
                .append(" , date_format(c.issueStartTime, '%Y-%m-%d %H:%i:%s') as issueStartTime ")
                .append(" , date_format(c.issueEndTime, '%Y-%m-%d %H:%i:%s') as issueEndTime ")
                .append(" , date_format(c.startTime, '%Y-%m-%d %H:%i:%s') as startTime ")
                .append(" , date_format(c.endTime, '%Y-%m-%d %H:%i:%s') as endTime ")
                .append(" , ").append(receiveNumSql)
                .append(" , ").append(waitApproveSql)
                .append(" from market_activity_item ai  ")
                .append(" left join coupon c on c.id = ai.commonId ")
                .append(" where ai.isDel = 0 and ai.marketActivityId = #{m.marketActivityId} ")
                .append(" and ai.commonType = #{m.commonType} ");
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> couponList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
        //遍历判断用户是可领取
        Integer receiveNum, limitRecNum;
        for(Map<String, Object> m : couponList){
            m.put("isReceive", BaseEntity.YES);
            receiveNum = m.get("receiveNum") != null ? new BigDecimal(m.get("receiveNum").toString()).intValue() : 0;
            limitRecNum = m.get("limitRecNum") != null ? new BigDecimal(m.get("limitRecNum").toString()).intValue() : 0;
            //判断用户对应优惠券领取数量是否超过活动优惠券限制次数
            if(limitRecNum > 0 && receiveNum >= limitRecNum){
                m.put("isReceive", BaseEntity.NO);
            }
        }
 
        //根据groupId分组转换后面分组匹配
        Map<String, List<Map<String, Object>>> couponListMap = couponList.stream().collect(Collectors.groupingBy(s->s.get("groupId").toString()));
        //查询活动分组,然后遍历匹配分组的优惠券
        sqlSentence.setSqlSentence(" select id, limitRctNum from market_activity_group where isDel = 0 and marketActivityId = #{m.marketActivityId} order by sortNum asc ");
        List<Map<String, Object>> groupList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
        //查询用户对应活动分组领取过的优惠券种类数量
        values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
        sql.setLength(0);
        sql.append(" select count(DISTINCT i.commonId) ")
                .append(" from market_activity_receive_record_item i ")
                .append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
                .append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
                .append(" and r.marketActivityId = #{m.marketActivityId} and i.groupId = #{m.groupId} ");
        sqlSentence.setSqlSentence(sql.toString());
        //遍历分组
        for(Map<String, Object> groupMap : groupList){
            groupMap.put("couponList", couponListMap.get(groupMap.get("id").toString()));
            groupMap.put("rctNum", BaseEntity.NO);
            if(user != null){
                values.put("userId", user.getId());
                values.put("groupId", groupMap.get("id"));
                groupMap.put("rctNum", commonService.selectCountSql(sqlSentence));
            }
        }
 
        //活动限制门店信息-----------------------------------------------------------
        sql.setLength(0);
        sql.append(" select lo.commonId, lo.commonName, lo.type ")
                .append(" from limit_total lt  ")
                .append(" join limit_other lo on lo.limitTotalId = lt.id  ")
                .append(" where lt.isDel = 0 and lo.isDel = 0 and lt.foreignKey = #{m.marketActivityId} ");
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> limitList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
        //过滤限制门店的信息
        List<Map<String, Object>> limitShopList = limitList.stream().filter(s-> LimitOther.TYPE_SHOP.toString().equals(s.get("type").toString())).collect(Collectors.toList());
        //过滤限制渠道的信息
//        List<Map<String, Object>> limitUCList = limitList.stream().filter(s-> LimitOther.TYPE_CHANNEL.toString().equals(s.get("type").toString())).collect(Collectors.toList());
 
 
        //------------------------------------------------------------------------
 
        JSONObject data = new JSONObject();
        //活动信息
        data.put("title", marketActivity.getTitle());
        data.put("ruleInfo", marketActivity.getRuleInfo());
        data.put("startTime", DateUtil.formatDate_2(marketActivity.getStartTime()));
        data.put("endTime", DateUtil.formatDate_2(marketActivity.getEndTime()));
        data.put("joinNum", marketActivity.getJoinNum());
        data.put("limitPeNum", marketActivity.getLimitPeNum());
        data.put("managerName", marketActivity.getManagerName());
//        data.put("limitRctNum", marketActivity.getLimitRctNum());
        //用户信息
        if(user != null){
            data.put("userShopId", user.getShopId());
        }
        //活动轮播图
        data.put("bannerList", bannerList);
        //活动优惠分组
        data.put("groupList", groupList);
        //活动优惠券
//        data.put("couponList", couponList);
        //限制参与门店
        data.put("limitShopList", limitShopList);
        //用户是否参与过活动,默认0没有
        data.put("isUserJoin", BaseEntity.NO);
        //用户是否有查看记录
        data.put("isView", BaseEntity.NO);
 
        values.put("marketActivityId", marketActivity.getId());
        //用户不为空则查询用户是否参与过活动
        if(StringUtils.noNull(dto.getUserId())){
            values.put("userId", dto.getUserId());
            sqlSentence.setSqlSentence(" select id from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} and userId = #{m.userId} ");
            MarketActivityJoinRecord joinRecord = commonService.selectOne(MarketActivityJoinRecordMapper.class, sqlSentence);
            if(joinRecord != null){
                data.put("isUserJoin", BaseEntity.YES);
            }
 
            //查询是否有查看记录
            sqlSentence.setSqlSentence(" select count(1) from market_activity_view_record vr where vr.isDel = 0 and vr.marketActivityId = #{m.marketActivityId} and vr.userId = #{m.userId} ");
            int count = commonService.selectCountSql(sqlSentence);
            data.put("isView", count > 0 ? BaseEntity.YES : BaseEntity.NO);
        }
 
        //查询总参与人数
        sqlSentence.setSqlSentence(" select count(DISTINCT userId) from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} ");
        int totalJoinNum = commonService.selectCountSql(sqlSentence);
        data.put("totalJoinNum", totalJoinNum);
 
//        //更新查看记录(处理报错不抛出,避免影响流程)
//        if(user != null){
//            try{
//                marketActivityService.updateViewRecord(marketActivity.getId(), dto.getPlatformType(), user);
//            }catch (Exception e){
//                log.error("营销活动更新查看记录失败:{}", GlobalExceptionHandler.getExceptionInformation(e));
//            }
//        }
 
        return Result.success(data);
    }
 
    /** 确认已查看 */
    @RequestMapping("/confirmView")
    public Result confirmView(@RequestBody MarketActivityDto dto){
 
        if(dto == null || StringUtils.isEmpty(dto.getId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动标识不能为空!");
        }
 
        if(StringUtils.isEmpty(dto.getUserId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "用户标识不能为空!");
        }
 
        MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getId());
        if(marketActivity == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
        }
 
        User user =  commonService.selectOneByKey(UserMapper.class, dto.getUserId());
        if(user == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
        }
 
        marketActivityService.updateViewRecord(marketActivity.getId(), dto.getPlatformType(), user);
 
        return Result.success();
    }
 
    /** 领取优惠券 */
    @PostMapping("/receiveCoupon")
    public Result receiveCoupon(@RequestBody(required = false) MarketActivityDto dto){
 
        log.info("营销活动领取优惠券参数:{}", JSONObject.toJSONString(dto));
 
        //检查领取参数
        MarketActivity marketActivity = checkReceiveParams(dto);
        String errMsg = marketActivity.getErrMsg();
 
        MarketActivityGroup group = commonService.selectOneByKey(MarketActivityGroupMapper.class, dto.getGroupId());
        if(group == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动分组信息!");
        }
 
        EmployeeRole employeeRole = null;
        if(dto.getOpType() == OperatorConstants.OP_TYPE_EMPLOYEE && StringUtils.noNull(dto.getOpRoleId())){
            employeeRole = employeeRoleService.selectOneByKey(dto.getOpRoleId());
        }
 
        User user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
        if(user == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
        }
        //领取检查参与限制逻辑
        receiveCheckJoinLimit(marketActivity, user, errMsg);
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        StringBuffer sql = new StringBuffer();
        values.put("marketActivityId", marketActivity.getId());
 
        //查询用户是否又参与记录
        values.put("userId", dto.getUserId());
        sqlSentence.setSqlSentence(" select * from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} and userId = #{m.userId} ");
        MarketActivityJoinRecord joinRecord = commonService.selectOne(MarketActivityJoinRecordMapper.class, sqlSentence);
 
        //判断如果活动限制参与人数
        if(marketActivity.getLimitPeNum() > 0){
            //没有参与记录则判断活动总参与人数是否超过了限制数量
            if(joinRecord == null){
                sqlSentence.setSqlSentence(" select count(1) from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} ");
                int joinNum = commonService.selectCountSql(sqlSentence);
                if(joinNum >= marketActivity.getLimitPeNum()){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券已领取完," + errMsg);
                }
            }
        }
 
        //查询活动领取的优惠券信息
        sql.setLength(0);
        values.put("groupId", group.getId());
        values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
        sql.append(" select * from market_activity_item where isDel = 0 and marketActivityId = #{m.marketActivityId} and groupId = #{m.groupId} and commonType = #{m.commonType} ");
        //单张优惠券领取则需要传这个值
        if(StringUtils.noNull(dto.getActivityCouponId())){
            values.put("id", dto.getActivityCouponId());
            sql.append(" and id = #{m.id} ");
        }
 
        sqlSentence.setSqlSentence(sql.toString());
        List<MarketActivityItem> list = commonService.selectList(MarketActivityItemMapper.class, sqlSentence);
        if(list == null || list.size() < 1){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "查询不到活动优惠券信息!");
        }
 
        Date now = new Date();
        List<MarketActivityItem> receiveList = new ArrayList<>();
        //存储已领取完的优惠券名
        List<String> cNameList = new ArrayList<>();
        //是否全部领取
        boolean isAll = StringUtils.isEmpty(dto.getActivityCouponId()) ? true : false;
        //最小可领取间隔时长
        int minInterval = 0;
 
        //查询用户分组下领取过的优惠券种类数量
        values.clear();
        values.put("userId", dto.getUserId());
        values.put("marketActivityId", marketActivity.getId());
        values.put("groupId", group.getId());
        values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
        sql.setLength(0);
        sql.append(" select count(DISTINCT i.commonId) ")
                .append(" from market_activity_receive_record_item i ")
                .append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
                .append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
                .append(" and r.marketActivityId = #{m.marketActivityId} and i.groupId = #{m.groupId} ");
        sqlSentence.setSqlSentence(sql.toString());
        int rctNum = commonService.selectCountSql(sqlSentence);
        //记录是否有新的领药优惠券种类数量
        int rctNewNum = 0;
 
        //查询对应活动优惠券用户是否已领取(要根据优惠券id来,不可根据活动优惠券id来)
        sql.setLength(0);
        values.put("approveStatus", MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT);
        sql.append(" select count(if(i.groupId = #{m.groupId}, 1, null)) as receiveNum ")
                .append(" , count(if(i.approveStatus = #{m.approveStatus}, 1, null)) as waitApproveNum ")
                .append(" , date_format(max(i.createTime), '%Y-%m-%d %H:%i:%s') as receiveTime ")
                .append(" from market_activity_receive_record_item i ")
                .append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
                .append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
                .append(" and r.marketActivityId = #{m.marketActivityId} and i.activityItemId = #{m.activityItemId} ");
        sqlSentence.setSqlSentence(sql.toString());
 
        int receiveNum = 0;     //领取数量
        int diffInterval = 0;   //相差间隔时长
        int waitApproveNum = 0; //待审批数量
        Date receiveTime = null;//最后领取时间
        Map<String, Object> receiveMap;
        Coupon coupon;
 
        log.info("领取种类数量:{}", rctNum);
        for(MarketActivityItem activityItem : list){
 
            receiveNum = 0;
            receiveTime = null;
 
            values.put("activityItemId", activityItem.getId());
            receiveMap = commonService.selectOneMap(MarketActivityMapper.class, sqlSentence);
            if(receiveMap != null && receiveMap.size() > 0){
                receiveNum = receiveMap.get("receiveNum") != null ? Integer.parseInt(receiveMap.get("receiveNum").toString()) : 0;
                receiveTime = receiveMap.get("receiveTime") != null ? DateUtil.parseString_1(receiveMap.get("receiveTime").toString()) : null;
                waitApproveNum = receiveMap.get("waitApproveNum") != null ? Integer.parseInt(receiveMap.get("waitApproveNum").toString()) : 0;
            }
 
 
 
            //如果领取数量为0,则领取种类数量+1
            if(receiveNum == 0){
                rctNewNum++;
                rctNum ++;
            }
 
            //用户没有领取记录,判断活动是否限制了N选M,然后判断用户领取是否超过N选M设置数量
            if(group.getLimitRctNum() > 0 && rctNum > group.getLimitRctNum()){
                if(isAll){
                    continue;
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券种类已超过活动分组设置的数量,不可继续领取其他优惠券," + errMsg);
            }
            log.info("领取种类数量:{},{}", rctNum, rctNewNum);
 
 
            //判断活动限制参与次数,且领取超过限制次数(原为活动joinNum字段判断,现在按优惠券设置字段来判断)
            if(activityItem.getLimitRecNum() > 0 && receiveNum >= activityItem.getLimitRecNum()){
                if(isAll){
                    continue;
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前活动优惠券每人仅限领取"+activityItem.getLimitRecNum()+"次," + errMsg);
            }
 
            //判断活动是否限制了领取间隔
//            log.info("receiveNum:{}", receiveNum);
//            log.info("最后领取时间:{}", DateUtil.formatDate_2(receiveTime));
//            log.info("限制领取间隔:{}", marketActivity.getRecInterval());
            if(marketActivity.getRecInterval() > BaseEntity.NO && receiveTime != null){
                //计算相差间隔时长 = 活动限制间隔时长 - 领取间隔时长
                diffInterval =  marketActivity.changeRecInterval() - differHour(receiveTime, now).intValue();
//                log.info("相差间隔:{}", diffInterval);
                if(diffInterval > 0){
                    if(isAll){
                        //赋值最小间隔时长
                        minInterval = minInterval == 0 ? diffInterval : diffInterval < minInterval ? diffInterval : minInterval;
                        continue;
                    }
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券还需等待" + diffInterval + "小时才可继续领取!");
                }
            }
 
            //查询优惠券信息,判断是否到了领取时间
            coupon = commonService.selectOneByKey(CouponMapper.class, activityItem.getCommonId());
            if(coupon == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "查询不到领取的优惠券信息!");
            }
 
            if(coupon.getIsDel() == BaseEntity.YES){
                if(isAll){
                    continue;
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券已被删除," + errMsg);
            }
 
            if(coupon.getIsUp() == BaseEntity.NO){
                if(isAll){
                    continue;
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券已下架,"+ errMsg);
            }
 
            if(coupon.getIssueStartTime() != null && now.compareTo(coupon.getIssueStartTime()) < 0){
                if(isAll){
                    continue;
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券还未到领取时间," + errMsg);
            }
 
            if(coupon.getIssueEndTime() != null && now.compareTo(coupon.getIssueEndTime()) > 0){
                if(isAll){
                    continue;
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券已过领取时间," + errMsg);
            }
 
            //判断待审批的不能领取
            if(waitApproveNum > 0){
                if(isAll){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "优惠券["+activityItem.getCommonName()+"]上次领取还未审批,不可全部领取," + errMsg);
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前优惠券上次领取还未审批,不可继续领取," + errMsg);
            }
 
            //判断优惠券剩余数量是否小于等于0,存储名称后面抛错提示
            if(couponSurplusNum(coupon) <= 0){
                cNameList.add(coupon.getTitle());
            }
 
            receiveList.add(activityItem);
        }
 
        if(cNameList.size() > 0){
            StringBuffer errSb = new StringBuffer();
            errSb.append("活动爆满,优惠券【");
            for(String name : cNameList){
                errSb.append(name).append("、");
            }
            errSb.delete(errSb.length() - 1, errSb.length()).append("】已领取完,").append(errMsg);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, errSb.toString());
        }
 
        if(receiveList.size() == 0){
            if(isAll){
                if(minInterval > 0){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动全部领取还需等待" + minInterval + "小时才可继续领取!");
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "暂无可领取的优惠券," + errMsg);
            }
//            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动每人仅限参与"+marketActivity.getJoinNum()+"次," + errMsg);
        }
 
        //处理参与记录逻辑
        if(joinRecord == null){
            joinRecord = new MarketActivityJoinRecord();
            joinRecord.setDateStr(Integer.parseInt(DateUtil.formatDate(now)));
            joinRecord.setMarketActivityId(marketActivity.getId());
            joinRecord.setPlatformType(dto.getPlatformType());
            //领取次数
            joinRecord.setReceiveNum(1);
            //用户信息
            joinRecord.setUserId(user.getId());
            joinRecord.setUserName(user.getName());
            joinRecord.setCIQ(user.getCIQ());
            joinRecord.setUserLevel(user.getUserLevel());
            joinRecord.setUserStatus(user.getUserStatus());
            joinRecord.setUserConsultantId(user.getHisCorpUserId());
            joinRecord.setUserConsultantName(EmployeeTool.getCnName(joinRecord.getUserConsultantId(), commonService));
            joinRecord.setUserShopId(user.getShopId());
            joinRecord.setUserShopName(ShopTool.getShopName(joinRecord.getUserShopId(), commonService));
            //通过用户创建日期
            if(DateUtil.formatDate(user.getCreateTime()).equals(joinRecord.getDateStr())){
                joinRecord.setIsNewUser(BaseEntity.YES);
            }
        }
 
        //每次都新增领取记录
        MarketActivityReceiveRecord receiveRecord = new MarketActivityReceiveRecord();
        receiveRecord.setMarketActivityId(marketActivity.getId());
        receiveRecord.setPlatformType(dto.getPlatformType());
        //操作人
        receiveRecord.setOpId(dto.getOpId());
        receiveRecord.setOpName(dto.getOpName());
        receiveRecord.setOpType(dto.getOpType());
        if(employeeRole != null){
            receiveRecord.setOpShopId(employeeRole.getShopId());
            receiveRecord.setOpRoleId(employeeRole.getId());
            receiveRecord.setOpRoleStr(employeeRole.getRoleUniqueStr());
        }
        //没有指定领取对应关联优惠券时,则是全部领取
        receiveRecord.setIsAll(isAll ? 1 : 0);
        //用户信息
        receiveRecord.setUserId(user.getId());
        receiveRecord.setUserName(user.getName());
        receiveRecord.setCIQ(user.getCIQ());
        receiveRecord.setUserLevel(user.getUserLevel());
        receiveRecord.setUserStatus(user.getUserStatus());
        receiveRecord.setUserConsultantId(user.getHisCorpUserId());
        receiveRecord.setUserConsultantName(EmployeeTool.getCnName(receiveRecord.getUserConsultantId(), commonService));
        receiveRecord.setUserShopId(user.getShopId());
        receiveRecord.setUserShopName(ShopTool.getShopName(receiveRecord.getUserShopId(), commonService));
 
        //累加领取优惠券数量
        joinRecord.setCouponNum(joinRecord.getCouponNum() + receiveList.size());
 
        synchronized (MarketActivityController.class){
            marketActivityService.receiveCoupon(marketActivity, receiveList, user, joinRecord, receiveRecord);
        }
 
        return Result.success();
    }
 
    /** 领取审批回调 */
    @RequestMapping("/receiveApproveCallback")
    public Result receiveApproveCallback(@RequestBody MarCommonReturnDto returnDto){
        log.info("营销活动领取审批回调:{}", JSONObject.toJSONString(returnDto));
 
        if(StringUtils.isEmpty(returnDto.getData())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求数据为空!");
        }
 
        MarketingReturnDto dto = JSONObject.parseObject(returnDto.getData(), MarketingReturnDto.class);
        if(dto == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "返回结果数据为空!");
        }
 
        if(StringUtils.isEmpty(dto.getResult())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批结果为空!");
        }
 
        if(StringUtils.isEmpty(dto.getUniqueId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "唯一值标识为空!");
        }
 
        MarketActivityReceiveRecordItem recordItem = commonService.selectOneByKey(MarketActivityReceiveRecordItemMapper.class, dto.getUniqueId());
        if(recordItem == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息1!");
        }
 
        if(recordItem.getApproveStatus() != MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取记录审批状态异常!");
        }
 
        if(MarketingReturnDto.AGREE.equals(dto.getResult())){
            recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_SUC);
        }else if(MarketingReturnDto.REJECT.equals(dto.getResult())){
            recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_FAIL);
        }else{
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批状态异常!");
        }
        recordItem.setApproveRemark(dto.getApplyRemarks());
 
        MarketActivityReceiveRecord receiveRecord = commonService.selectOneByKey(MarketActivityReceiveRecordMapper.class, recordItem.getReceiveRecordId());
        if(receiveRecord == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息2!");
        }
 
        MarketActivityJoinRecord joinRecord = commonService.selectOneByKey(MarketActivityJoinRecordMapper.class, receiveRecord.getJoinRecordId());
        if(joinRecord == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动参与记录信息!");
        }
 
        marketActivityService.receiveApproveHandle(joinRecord, receiveRecord, recordItem);
 
        return Result.success();
    }
 
    /**审批列表*/
    @RequestMapping("/approve/list")
    public Result pendingApproveCoupon(@RequestBody MarketActivityDto dto) {
 
        log.info("营销活动获取待审核优惠券参数:{}", JSONObject.toJSONString(dto));
 
        //检查
        if(StringUtils.isEmpty(dto.getMarketActivityId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "营销活动标识为空!");
        }
 
        MarketActivity marketActivity = commonService.selectOneByKeyBlob(MarketActivityMapper.class,dto.getMarketActivityId());
        if(marketActivity == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到营销活动信息!");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
 
        values.put("isDel", BaseEntity.NO);
        values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
        values.put("marketActivityId", dto.getMarketActivityId());
 
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT ri.id as recordItemId,ri.approveStatus, c.id AS couponId, c.title AS couponName")
                .append(" , c.type,c.platformType, mai.limitRecNum , ma.id as marketActivityId, mai.id as marketActivityItemId")
                .append(" , date_format( c.issueStartTime, '%Y-%m-%d %H:%i:%s') as issueStartTime ")
                .append(" , date_format( c.issueEndTime, '%Y-%m-%d %H:%i:%s') as issueEndTime ")
                .append(" , CASE c.type WHEN 0 THEN c.discountNum ELSE c.discountAmount END AS couponPrice")
                .append(" , rr.opName,rr.userName,rr.CIQ,ri.approveRemark as remark ")
                .append(" FROM market_activity ma")
                .append(" LEFT JOIN market_activity_item mai ON ma.id = mai.marketActivityId")
                .append(" LEFT JOIN coupon c ON mai.commonId = c.id AND mai.commonType = #{m.commonType} ")
                .append(" LEFT JOIN market_activity_receive_record_item ri on ri.activityItemId = mai.id ")
                .append(" LEFT JOIN market_activity_receive_record rr on ri.receiveRecordId = rr.id ")
                .append(" WHERE ma.isDel = #{m.isDel} AND ma.id = #{m.marketActivityId} ");
        //审批状态查询
        if (dto.getApprovalStatus()!= null) {
            values.put("approveStatus", dto.getApprovalStatus());
            sql.append(" AND ri.approveStatus = #{m.approveStatus}");
        }else {
            sql.append(" AND ri.approveStatus in (0,1,2,3)");
        }
 
        sql.append(" ORDER BY ri.createTime DESC ");
        sqlSentence.setSqlSentence(sql.toString());
 
        PageHelper.startPage(dto.getPageNum() == null ? 1 : dto.getPageNum(), dto.getPageSize() == null ? 10 : dto.getPageSize());
        List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
        PageInfo pageInfo = new PageInfo(list);
 
        return Result.success(pageInfo);
 
    }
 
    /** 后台领取审批 */
    @RequestMapping("/receive/approve/callback/admin")
    public Result receiveApproveCallbackAdmin(@RequestBody MarketActivityDto dto){
 
        log.info("营销活动审核操作传值参数:{}", JSONObject.toJSONString(dto));
 
        if(StringUtils.isEmpty(dto.getRecordItemId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "标识为空!");
        }
 
        if(StringUtils.isEmpty(dto.getOpId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人为空!");
        }
 
        if(StringUtils.isEmpty(dto.getStatusStr())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审核状态为空!");
        }
 
        MarketActivityReceiveRecordItem recordItem = commonService.selectOneByKeyBlob(MarketActivityReceiveRecordItemMapper.class, dto.getRecordItemId());
        if(recordItem == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息!");
        }
 
        if(recordItem.getApproveStatus() != MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取记录审批状态异常!");
        }
 
        if(MarketingReturnDto.AGREE.equals(dto.getStatusStr())){
            recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_SUC);
        }else if(MarketingReturnDto.REJECT.equals(dto.getStatusStr())){
            recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_FAIL);
        }else{
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批状态异常!");
        }
        recordItem.setApproveRemark(dto.getRemark());
        MarketActivity marketActivity = commonService.selectOneByKeyBlob(MarketActivityMapper.class,recordItem.getMarketActivityId());
        if(marketActivity == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
        }
 
        if(!marketActivity.getManagerId().equals(dto.getOpId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "当前操作审批人与负责人不一致!");
        }
 
        MarketActivityReceiveRecord receiveRecord = commonService.selectOneByKey(MarketActivityReceiveRecordMapper.class, recordItem.getReceiveRecordId());
        if(receiveRecord == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息!");
        }
 
        MarketActivityJoinRecord joinRecord = commonService.selectOneByKey(MarketActivityJoinRecordMapper.class, receiveRecord.getJoinRecordId());
        if(joinRecord == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动参与记录信息!");
        }
 
        marketActivityService.receiveApproveHandle(joinRecord, receiveRecord, recordItem);
 
        return Result.success();
    }
 
    ///////////////////////////////////////////////////////////////////////////
 
    /** 检查校验领取参数 */
    private MarketActivity checkReceiveParams(MarketActivityDto dto){
        if(dto == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求对象不能为空!");
        }
 
        if(StringUtils.isEmpty(dto.getMarketActivityId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动标识不能为空!");
        }
 
        if(StringUtils.isEmpty(dto.getGroupId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动分组标识不能为空!");
        }
 
 
        if(StringUtils.isEmpty(dto.getUserId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取用户不能为空!");
        }
 
        if(StringUtils.isEmpty(dto.getPlatformType())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "平台类型不能为空!");
        }
 
        if(dto.getOpType() == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人类型不能为空!");
        }
 
        if(StringUtils.isEmpty(dto.getOpId())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人标识不能为空!");
        }
 
        if(StringUtils.isEmpty(dto.getOpName())){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人名称不能为空!");
        }
 
        MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getMarketActivityId());
        if(marketActivity == null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
        }
 
        String errMsg = "请联系活动负责人"+marketActivity.getManagerName()+"咨询情况";
        marketActivity.setErrMsg(errMsg);
 
        if(marketActivity.getIsUp() == BaseEntity.NO){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动已下架," + errMsg);
        }
 
        if(marketActivity.getTimeType() == MarketActivity.TIME_TYPE_APPOINT_TIME){
            Date now = new Date();
            if(now.compareTo(marketActivity.getStartTime()) < 0){
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动还未开始," + errMsg);
            }
            if(now.compareTo(marketActivity.getEndTime()) > 0){
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动已结束," + errMsg);
            }
        }
 
        return marketActivity;
    }
 
    //获取优惠券剩余数量
    public int couponSurplusNum(Coupon coupon){
        // 查询已发送的数量
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("validState", BaseEntity.YES);
        sqlValues.put("couponId", coupon.getId());
        sqlSentence.sqlWhere(" couponId = #{m.couponId} AND validState = #{m.validState} AND isDel = #{m.isDel}", sqlValues);
        int count = commonService.selectCount(CouponNumberMapper.class,sqlSentence);
        if (coupon.getIssueNum() != null) {
            return coupon.getIssueNum() - count;
        } else {
           return 0;
        }
    }
 
    //查询用户渠道inSql
    public String queryUserChannelInSql(User user){
        StringBuffer channelInSql = new StringBuffer();
        if(StringUtils.noNull(user.getChannelId())){
            channelInSql.append("'").append(user.getChannelId()).append("',");
        }
        if(StringUtils.noNull(user.getChannel2Id())){
            channelInSql.append("'").append(user.getChannel2Id()).append("',");
        }
        if(StringUtils.noNull(user.getChannelAssistId())){
            channelInSql.append("'").append(user.getChannelAssistId()).append("',");
        }
        if(StringUtils.noNull(user.getChannelAssist2Id())){
            channelInSql.append("'").append(user.getChannelAssist2Id()).append("',");
        }
        if(channelInSql.length() > 0){
            channelInSql.delete(channelInSql.length()-1, channelInSql.length());
        }
        return channelInSql.toString();
    }
 
    //领取检查参与限制逻辑
    public void receiveCheckJoinLimit(MarketActivity marketActivity, User user, String errMsg){
 
        //判断用户会员等级是否符合限制--------------------------------------------------
        if(StringUtils.noNull(marketActivity.getLimitUserLevel())){
            if(StringUtils.isEmpty(user.getUserLevel())
                    || marketActivity.getLimitUserLevel().indexOf(user.getUserLevel()) == -1){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户会员等级不在活动范围内," + errMsg);
            }
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        StringBuffer sql = new StringBuffer();
        values.put("marketActivityId", marketActivity.getId());
 
        //查询活动限制总表限制信息------------------------------------------------------
        sql.append(" select lo.commonId, lo.commonName, lo.type ")
                .append(" from limit_total lt  ")
                .append(" join limit_other lo on lo.limitTotalId = lt.id  ")
                .append(" where lt.isDel = 0 and lo.isDel = 0 and lt.foreignKey = #{m.marketActivityId} ");
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> limitList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
 
        //过滤限制门店的信息判断用户是否符合限制门店
        List<Map<String, Object>> limitShopList = limitList.stream().filter(s-> LimitOther.TYPE_SHOP.toString().equals(s.get("type").toString())).collect(Collectors.toList());
        if(limitShopList != null && limitShopList.size() > 0){
            boolean canReceive = false;
            for(Map<String, Object> m : limitShopList){
                if(m.get("commonId").toString().equals(user.getShopId())){
                    canReceive = true;
                    break;
                }
            }
            if(!canReceive){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户所属门店不在活动范围内," + errMsg);
            }
        }
 
        //过滤限制渠道的信息判断用户是否符合限制渠道---------------------------------------------
        List<Map<String, Object>> limitUcList = limitList.stream().filter(s-> LimitOther.TYPE_CHANNEL.toString().equals(s.get("type").toString())).collect(Collectors.toList());
        if(limitUcList != null && limitUcList.size() > 0){
            boolean canReceive = false;
            //用户渠道id
            String userChannelIds = queryUserChannelInSql(user);
            for(Map<String, Object> m : limitUcList){
                //用户渠道包含的就算
                if(userChannelIds.indexOf(m.get("commonId").toString()) != -1){
                    canReceive = true;
                    break;
                }
            }
            if(!canReceive){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户所属渠道不在活动范围内," + errMsg);
            }
        }
 
        //执行或消费限制判断----------------------------------------------------------
        if(marketActivity.getLimitEcNum() > 0){
            //查询出限制条件
            sqlSentence.setSqlSentence(" select * from market_activity_limit_ec where isDel = 0 and marketActivityId = #{m.marketActivityId} order by moduleNo asc ");
            List<MarketActivityLimitEc> limitEcList = commonService.selectList(MarketActivityLimitEcMapper.class, sqlSentence);
            if(limitEcList != null && limitEcList.size() > 0)
            {
 
                //查询用户项目执行次数sql(已执行、汇总执行次数)
                String executeSql = "select ifnull( sum(dp.num), 0) from deduction_project dp join deduction_single ds on ds.id = dp.deductionSingleId where ds.isDel = 0 and dp.isDel = 0 and ds.status = #{m.status} and ds.userId = #{m.userId} and dp.projectId = #{m.commonId} and ds.createTime >= #{m.dateTime} ";
                //查询用户消费次数sql(已支付、汇总时购买数量-已退款数量)
                String consumeSql = "select ifnull( sum(oi.buyNum - oi.hasReNum), 0) from order_item oi join orders_total ot on ot.id = oi.orderId where ot.isDel = 0 and oi.isDel = 0 and ot.payStatus = #{m.payStatus} and ot.userId = #{m.userId} and oi.commonId = #{m.commonId} and ot.payTime >= #{m.dateTime} ";
 
                //按模块编号过滤分组数据
                Map<Integer, List<MarketActivityLimitEc>> ecMap = limitEcList.stream().collect(Collectors.groupingBy(MarketActivityLimitEc::getModuleNo));
                log.info("限制消费模块数据:{}", JSONObject.toJSONString(ecMap));
                //最终是否符合
                boolean isConform = false;
                //遍历是否满足模块所有条件
                boolean isOk = false;
                //遍历
                for(Map.Entry<Integer, List<MarketActivityLimitEc>> entry : ecMap.entrySet())
                {
                    //按模块遍历,默认是满足,下面遍历如果有条件不符合,就是false
                    isOk = true;
                    values.put("userId", user.getId());
 
                    //遍历模块下的限制条件
                    for(MarketActivityLimitEc limitEc : entry.getValue())
                    {
                        if(limitEc.getActionType() == MarketActivityLimitEc.ACTION_TYPE_EXECUTE){
                            //执行-项目
                            values.put("status", DeductionSingleConstants.STATUS_DONE_EXECUTE);
                            sqlSentence.setSqlSentence(executeSql);
                        }else if(limitEc.getActionType() == MarketActivityLimitEc.ACTION_TYPE_CONSUME){
                            //消费-项目、促销、卡项
                            values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
                            sqlSentence.setSqlSentence(consumeSql);
                        }else{
                            //没有对应类型,直接不满足跳出循环
                            isOk = false;
                            break;
                        }
 
                        //根据时间单位+时间范围数值换算出有效日期
                        values.put("dateTime", limitEc.convertDateTime());
                        values.put("commonId", limitEc.getCommonId());
 
                        //判断如果用户不满足限制数量,直接跳出循环,用户不满足模块限制
                        if(commonService.selectCountSql(sqlSentence) < limitEc.getNum()){
                            isOk = false;
                            break;
                        }
                    }
 
                    //其中一个满足,直接跳出循环,然后标记为符合领取
                    if(isOk){
                        isConform = true;
                        break;
                    }
                }
                //全部遍历完成后,如果不符合则提示不能领取
                if(!isConform){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户不满足执行或消费条件限制无法领取," + errMsg);
                }
            }
        }
 
        //END--------------------------------------------------------------
    }
 
    //间隔时长
    public static Long differHour(Date startTime, Date endTime) {
        if(startTime == null || endTime == null){
            return 0L;
        }
        long sTime = startTime.getTime();
        long eTime = endTime.getTime();
        return (eTime - sTime) / 1000L / 60L / 60L;
    }
 
    /** 处理列表条件查询sql */
    public void handleListConditionQuerysSql(MarketActivityDto dto, StringBuffer sql, Map<String, Object> values){
 
        if (!StringUtils.isEmpty(dto.getKeyWord())) {
            sql.append(" and a.title like #{m.keyWord} ");
            values.put("keyWord", "%" + dto.getKeyWord() + "%");
        }
 
        if(dto.getIsUp() != null){
            sql.append(" and a.isUp = #{m.isUp} ");
            values.put("isUp", dto.getIsUp());
        }
 
        if(dto.getIsCoupon() != null){
            if(dto.getIsCoupon() == BaseEntity.NO){
                sql.append(" and a.couponNum = 0 ");
            }else{
                sql.append(" and a.couponNum > 0 ");
            }
        }
 
        if (!StringUtils.isEmpty(dto.getClassifyId())) {
            sql.append(" and a.classifyId = #{m.classifyId} ");
            values.put("classifyId", dto.getClassifyId());
        }
 
        if (!StringUtils.isEmpty(dto.getStartTime())) {
            sql.append(" and a.startTime >= date_format(#{m.startTime}, '%Y-%m-%d %00:%00:%00') ");
            values.put("startTime", dto.getStartTime());
        }
 
        if (!StringUtils.isEmpty(dto.getEndTime())) {
            sql.append(" and a.endTime <= date_format(#{m.endTime}, '%Y-%m-%d %23:%59:%59') ");
            values.put("endTime", dto.getEndTime());
        }
 
        if(StringUtils.noNull(dto.getShopIds())){
            //遍历拼接门店in查询sql
            String [] shopArr = dto.getShopIds().split(",");
            StringBuffer shopInSql = new StringBuffer();
            for(String shopId : shopArr){
                shopInSql.append("'").append(shopId).append("',");
            }
            shopInSql.delete(shopInSql.length() - 1, shopInSql.length());
 
            //对应子查询限制总表符合的活动id,再in查询对应符合的
            values.put("ltType", LimitTotal.LIMIT_MARKET_ACTIVITY);
            values.put("loType", LimitOther.TYPE_SHOP);
            sql.append(" and ( ")
                    .append(" a.id in ( ")
                    .append(" select lt.foreignKey from limit_total lt ")
                    .append(" join limit_other lo on lo.limitTotalId = lt.id and lo.isDel = 0 ")
                    .append(" where lt.isDel = 0 and lt.type = #{m.ltType} and lo.type = #{m.loType}  ")
                    .append(" and lo.commonId in (").append(shopInSql).append(") group by lt.foreignKey ")
                    .append(" )  ")
                    .append(" or a.isLimitShop = 0  )   ");
        }
 
        //如果用户id不为空,处理限制用户逻辑
        if(StringUtils.noNull(dto.getUserId())){
            User user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
            if(user == null){
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
            }
 
            //查询符合用户会员等级的活动
            values.put("userLevel", user.getUserLevel());
            sql.append(" and ( limitUserLevel is null  or ( #{m.userLevel} is not null and #{m.userLevel} != '' and LOCATE( #{m.userLevel}, limitUserLevel) > 0) ) ");
 
            //对应子查询限制总表符合用户渠道的活动id,再in查询对应符合的
            String channelInSql = queryUserChannelInSql(user);
            sql.append(" and ( a.isLimitUC = 0 ");
            if(StringUtils.noNull(channelInSql)){
                values.put("ltType2", LimitTotal.LIMIT_MARKET_ACTIVITY);
                values.put("loType2", LimitOther.TYPE_CHANNEL);
                sql.append(" or a.id in ( ")
                        .append(" select lt.foreignKey from limit_total lt ")
                        .append(" join limit_other lo on lo.limitTotalId = lt.id and lo.isDel = 0 ")
                        .append(" where lt.isDel = 0 and lt.type = #{m.ltType2} and lo.type = #{m.loType2}  ")
                        .append(" and lo.commonId in (").append(channelInSql).append(") group by lt.foreignKey ")
                        .append(" )  ");
            }
            sql.append(" ) ");
        }
    }
 
    public static void main(String args[]){
//        Date startTime = DateUtil.parseString_1("2023-08-21 16:00:00");
//        Date endTime = new Date();
//        System.out.println(differHour(startTime, endTime));
 
//        List<MarketActivityLimitEc> limitEcList = new ArrayList<>();
//        limitEcList.add(new MarketActivityLimitEc(1, "1001"));
//        limitEcList.add(new MarketActivityLimitEc(1, "1002"));
//        limitEcList.add(new MarketActivityLimitEc(1, "1003"));
//
//        limitEcList.add(new MarketActivityLimitEc(2, "2001"));
//        limitEcList.add(new MarketActivityLimitEc(2, "2002"));
//
//        limitEcList.add(new MarketActivityLimitEc(3, "3001"));
//
//        Map<Integer, List<MarketActivityLimitEc>> ecMap =limitEcList.stream().collect(Collectors.groupingBy(MarketActivityLimitEc::getModuleNo));
//        System.out.println(ecMap.entrySet());
 
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("id", "1");
        list.add(map);
 
 
        map = new HashMap<>();
        map.put("id", "2");
        list.add(map);
        map = new HashMap<>();
        map.put("id", "2");
        list.add(map);
 
        map = new HashMap<>();
        map.put("id", "3");
        list.add(map);
        map = new HashMap<>();
        map.put("id", "3");
        list.add(map);
        map = new HashMap<>();
        map.put("id", "3");
        list.add(map);
 
        Map<String, Long> map2 = list.stream().filter(s->s.get("id1") != null).collect(Collectors.groupingBy(s->s.get("id1").toString(), Collectors.counting()));
        System.out.println(map2.entrySet());
 
    }
}