puzhibing
2023-12-04 3ad6b6ba2ba56fc0bcd2130e47190779c6e15acc
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
package com.dsh.activity.controller;
 
import java.util.Date;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsh.activity.entity.Coupon;
import com.dsh.activity.entity.CouponCity;
import com.dsh.activity.entity.CouponStore;
import com.dsh.activity.entity.UserCoupon;
import com.dsh.activity.feignclient.account.AppUserClient;
import com.dsh.activity.feignclient.account.CityClient;
import com.dsh.activity.feignclient.account.StoreStaffClient;
import com.dsh.activity.feignclient.account.StudentClient;
import com.dsh.activity.feignclient.account.model.AppUserByNameAndPhoneDTO;
import com.dsh.activity.feignclient.account.model.TCityManager;
import com.dsh.activity.feignclient.model.CouponExamineListSearch;
import com.dsh.activity.feignclient.model.CouponListOfSearch;
import com.dsh.activity.feignclient.model.TAppUser;
import com.dsh.activity.feignclient.other.OperatorClient;
import com.dsh.activity.feignclient.other.RegionClient;
import com.dsh.activity.feignclient.other.StoreClient;
import com.dsh.activity.feignclient.other.model.CityDataAndProvinceDataVo;
import com.dsh.activity.feignclient.other.model.Store;
import com.dsh.activity.feignclient.other.model.StoreInfoDto;
import com.dsh.activity.feignclient.other.model.TOperatorCity;
import com.dsh.activity.model.CouponListVo;
import com.dsh.activity.model.CouponRecordQuery;
import com.dsh.activity.model.request.CommodityRequest;
import com.dsh.activity.model.request.CouponDataVo;
import com.dsh.activity.model.request.CouponPackageReq;
import com.dsh.activity.model.response.CouponPackageResp;
import com.dsh.activity.service.CouponCityService;
import com.dsh.activity.service.CouponStoreService;
import com.dsh.activity.service.ICouponService;
import com.dsh.activity.service.UserCouponService;
import com.dsh.activity.util.GDMapGeocodingUtil;
import com.dsh.activity.util.ResultUtil;
import com.dsh.activity.util.TokenUtil;
import com.dsh.activity.util.ToolUtil;
import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author zhibing.pu
 * @date 2023/6/24 11:27
 */
@RestController
@RequestMapping("")
public class CouponController {
 
    @Autowired
    private ICouponService couponService;
 
    @Autowired
    private TokenUtil tokenUtil;
 
    @Autowired
    private UserCouponService ucService;
 
    @Autowired
    private GDMapGeocodingUtil gdMapGeocodingUtil;
 
    @Resource
    private CityClient citClient;
 
    @Resource
    private StoreStaffClient stoStaClient;
 
 
    @Resource
    private StoreClient stoClient;
 
 
    @Resource
    private RegionClient regionClient;
 
    @Resource
    private CouponStoreService couStoreService;
 
    @Resource
    private CouponCityService cityService;
 
    @Autowired
    private AppUserClient appUserClient;
    @Autowired
    private StudentClient studentClient;
 
    /**
     * 查询注册赠送优惠券 判断当前优惠券限领数量
     */
    @ResponseBody
    @PostMapping("/coupon/queryCouponByUser/{userId}")
    public List<Long> queryCouponByUser(@PathVariable("userId") Integer userId) {
        List<Long> ids = new ArrayList<>();
        System.err.println("到达了赠送优惠价");
        List<Coupon> list = couponService.list(new QueryWrapper<Coupon>().eq("distributionMethod", 2)
                .le("startTime", new Date()).ge("endTime", new Date()).eq("auditStatus", 2)
                .eq("state", 1));
 
        for (Coupon coupon : list) {
            // 发放数量
            Integer quantityIssued = coupon.getQuantityIssued();
            // 限领数量
            Integer pickUpQuantity = coupon.getPickUpQuantity();
            // 优惠券已领取数量
            int couponId = ucService.count(new QueryWrapper<UserCoupon>().eq("couponId", coupon.getId()));
            // 用户已领取该优惠券数量
            int count = ucService.count(new QueryWrapper<UserCoupon>().eq("couponId", coupon.getId()
            ).eq("userId", userId));
            if (couponId >= quantityIssued) {
                continue;
            }
            if (count >= pickUpQuantity) {
                continue;
            }
            // 条件满足 将优惠券送给用户
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setCouponId(coupon.getId());
            userCoupon.setUserId(userId);
            userCoupon.setStatus(1);
            userCoupon.setInsertTime(new Date());
            ucService.save(userCoupon);
            ids.add(userCoupon.getId());
        }
        return ids;
    }
 
    @ResponseBody
    @PostMapping("/api/coupon/queryCouponList")
    @ApiOperation(value = "获取优惠券列表", tags = {"APP-成为会员", ""})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "1=积分购买,2=注册赠送", name = "distributionMethod", dataType = "int", required = true),
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....")
    })
    public ResultUtil<List<CouponListVo>> queryCouponList(Integer distributionMethod) {
        if (null == distributionMethod) {
            return ResultUtil.paranErr("distributionMethod");
        }
        try {
            Integer uid = tokenUtil.getUserIdFormRedis();
            if (null == uid) {
                return ResultUtil.tokenErr();
            }
            List<CouponListVo> listVos = couponService.queryCouponList(uid, distributionMethod);
            return ResultUtil.success(listVos);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.success();
        }
    }
 
 
    /**
     * 根据id获取优惠券信息
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/coupon/queryCouponById")
    public Coupon queryCouponById(@RequestBody Integer id) {
        try {
            Coupon coupon = couponService.getById(id);
            return coupon;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    @Autowired
    private UserCouponService userCouponService;
 
    @ResponseBody
    @PostMapping("/coupon/queryCouponByUid")
    public List<Coupon> queryCouponByUid(@RequestBody Integer uid) {
        try {
            LocalDateTime currentTime = LocalDateTime.now();
            LocalDateTime oneMinuteAgo = currentTime.minusSeconds(20);
 
            List<UserCoupon> list = userCouponService.list(new QueryWrapper<UserCoupon>().eq("userId", uid).ge("insertTime", oneMinuteAgo));
            List<Integer> ids = new ArrayList<>();
            for (UserCoupon userCoupon : list) {
                ids.add(userCoupon.getCouponId());
            }
 
            if (ids.size() > 0) {
                List<Coupon> userId = couponService.list(new QueryWrapper<Coupon>().in("id", ids));
                return userId;
 
            }
 
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    /**
     * 我的券包列表
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/api/coupon/queryCouponPackage")
    @ApiOperation(value = "我的券包列表", tags = {"APP-使用福利"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....")
    })
    public ResultUtil<List<CouponPackageResp>> queryAppuserCouponList(CouponPackageReq req) {
        try {
            Integer uid = tokenUtil.getUserIdFormRedis();
            if (null == uid) {
                return ResultUtil.tokenErr();
            }
            return ResultUtil.success(ucService.queryCouponPackagesList(uid, req));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.success();
        }
    }
 
 
    @PostMapping("/base/coupon/getAllCoupons")
    public List<Coupon> getAllCoupons(@RequestBody CommodityRequest request) {
        List<Coupon> couponList = new ArrayList<>();
        String provinceCode = "";
        String cityCode = "";
        if (ToolUtil.isEmpty(request.getLat()) && ToolUtil.isEmpty(request.getLon())) {
            return couponList;
        }
        try {
            Map<String, String> geocode = gdMapGeocodingUtil.geocode(request.getLon(), request.getLat());
            provinceCode = geocode.get("provinceCode");
            cityCode = geocode.get("cityCode");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            LocalDateTime currentDate = LocalDateTime.now();
 
            couponList = couponService.list(new QueryWrapper<Coupon>()
                    .eq("distributionMethod", 1)
                    .eq("state", 1)
                    .eq("status", 1)
                    .le("startTime", currentDate)
                    .ge("endTime", currentDate));
            if (couponList.size() > 0) {
                Iterator<Coupon> iterator = couponList.iterator();
                while (iterator.hasNext()) {
                    Coupon merchandise = iterator.next();
                    if (merchandise.getUseScope() == 2) {
                        List<CouponCity> couponCities = cityService.list(new LambdaQueryWrapper<CouponCity>()
                                .eq(CouponCity::getCouponId, merchandise.getId()));
                        if (couponCities.size() > 0) {
                            for (CouponCity couponCity : couponCities) {
                                if (!Objects.equals(couponCity.getCityCode(), cityCode) && !Objects.equals(couponCity.getProvinceCode(), provinceCode)) {
                                    iterator.remove(); // 移除符合条件的商品
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return couponList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
 
    }
 
    @PostMapping("/base/coupon/getRedeemedNums")
    public int getRedeemedQuantity(@RequestBody Integer id) {
        return ucService.count(new QueryWrapper<UserCoupon>()
                .eq("couponId", id));
    }
 
 
    @PostMapping("/base/coupon/insertToAppuserCoupon")
    public void insertToAppuserCoupon(@RequestBody UserCoupon coupon) {
        coupon.setInsertTime(new Date());
        ucService.save(coupon);
    }
 
 
    @Autowired
    private OperatorClient operatorClient;
 
    @ResponseBody
    @PostMapping("/base/coupon/queryCouponListSearch")
    public List<Map<String, Object>> getCouponListOfSearch(@RequestBody CouponListOfSearch ofSearch) {
        List<Map<String, Object>> mapList1 = couponService.queryCouponListOfSearch(ofSearch);
 
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (ofSearch.getStoreIds() == null) {
            ArrayList<Integer> list = new ArrayList<>();
            ofSearch.setStoreIds(list);
        }
        if (ofSearch.getStoreId() != null || ofSearch.getStoreIds().size() != 0) {
            for (Map<String, Object> map : mapList1) {
                // 如果当前登陆人是运营商 只能查看平台添加的优惠券应只展示使用范围为全国通用、
                // 指定城市有运营商管辖的、指定门店有运营商旗下门店
                if (ofSearch.getObjType() == 2) {
                    if (Integer.parseInt(String.valueOf(map.get("useScope"))) == 1) {
                        mapList.add(map);
                    }
                    if (Integer.parseInt(String.valueOf(map.get("useScope"))) == 2) {
                        // 获取到优惠券id 查询这个优惠券指定了哪些城市
                        Integer id = Integer.parseInt(String.valueOf(map.get("id")));
                        // 获取到运营商管理的省和市
                        List<TOperatorCity> cityByOperatorId = ofSearch.getOperatorCities();
                        // 拿到运营商市的code集合
                        List<String> collect = cityByOperatorId.stream().filter(t -> t.getPid() != 0)
                                .map(tOperatorCity -> Integer.toString(tOperatorCity.getCode()))
                                .collect(Collectors.toList());
                        List<CouponCity> couponId = cityService.list(new QueryWrapper<CouponCity>().eq("couponId", id));
                        // 先判断优惠券管理的市  运营商是否有
                        List<String> collect1 = couponId.stream().map(CouponCity::getCityCode)
                                .collect(Collectors.toList());
                        // 优惠券指定的省
                        List<String> collect2 = couponId.stream().map(CouponCity::getCityCode)
                                .collect(Collectors.toList());
                        if (!Collections.disjoint(collect, collect1)) {
                            mapList.add(map);
                        } else {
                            // 如果没有交集 那么还需要判断运营商是否管理了整个省
 
 
                        }
                    }
                    if (Integer.parseInt(String.valueOf(map.get("useScope"))) == 3) {
                        // 获取到优惠券id 查询这个优惠券指定了哪些门店
                        Integer id = Integer.parseInt(String.valueOf(map.get("id")));
                        // 当前运营商管理的门店ids
                        List<Integer> storeIds = ofSearch.getStoreIds();
                        // 优惠券指定的门店
                        List<Integer> collect = couStoreService.list(new QueryWrapper<CouponStore>().eq("couponId", id)
                                .in("storeId", storeIds)).stream().map(CouponStore::getStoreId)
                                .collect(Collectors.toList());
                        // 判断两个集合是否相交
                        // 比较两个集合中是否有相同的元素;当两个集合中没有相同元素时返回true,
                        // 当有相同元素时返回false。
                        if (!Collections.disjoint(collect, storeIds)) {
                            mapList.add(map);
                        }
                    }
                } else {
                    List<CouponStore> id = couStoreService.list(new LambdaQueryWrapper<CouponStore>()
                            .eq(CouponStore::getCouponId, map.get("id").toString()));
                    List<Integer> collect = id.stream().map(CouponStore::getStoreId).collect(Collectors.toList());
                    if (collect.size() == 0) {
                        collect.add(-1);
                    }
                    if (collect.contains(ofSearch.getStoreId())) {
                        if (collect.size() > 1) {
                            map.put("size", 1);
                        } else {
                            map.put("size", 0);
                        }
                        mapList.add(map);
                    }
                }
            }
        } else {
            mapList = mapList1;
        }
        if (mapList.size() > 0) {
            for (Map<String, Object> stringObjectMap : mapList) {
                Integer o = (Integer) stringObjectMap.get("id");
                Object startTime = stringObjectMap.get("startTime");
                Object endTime = stringObjectMap.get("endTime");
                stringObjectMap.put("timeValue", startTime + "至" + endTime);
                int count = ucService.count(new LambdaQueryWrapper<UserCoupon>()
                        .eq(UserCoupon::getCouponId, o));
                stringObjectMap.put("hasPickQty", count);
            }
        }
        return mapList;
    }
 
 
    @ResponseBody
    @PostMapping("/base/coupon/queryCouponListSearch1")
    public List<Map<String, Object>> getCouponListOfSearch1(@RequestBody CouponListOfSearch ofSearch) {
        // 查询全国通用的优惠券和包含指定门店的优惠券
        List<Map<String, Object>> mapList = couponService.queryCouponListOfSearch1(ofSearch);
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDateStr = sdf.format(currentDate);
        // Iterate over the mapList and remove entries where endTime is less than the current date
        Iterator<Map<String, Object>> iterator = mapList.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> map = iterator.next();
            String endTime = (String) map.get("endTime");
            if (endTime.compareTo(currentDateStr) < 0) {
                iterator.remove();
            }
        }
 
 
        if (mapList.size() > 0) {
            for (Map<String, Object> stringObjectMap : mapList) {
                Integer o = (Integer) stringObjectMap.get("id");
                Object startTime = stringObjectMap.get("startTime");
                Object endTime = stringObjectMap.get("endTime");
                stringObjectMap.put("timeValue", startTime + "至" + endTime);
                int count = ucService.count(new LambdaQueryWrapper<UserCoupon>()
                        .eq(UserCoupon::getCouponId, o));
                stringObjectMap.put("hasPickQty", count);
            }
        }
        return mapList;
    }
 
    @ResponseBody
    @PostMapping("/base/coupon/couponExamineListSearch")
    public List<Map<String, Object>> getCouponExamineListOfSearch(@RequestBody CouponExamineListSearch ofSearch) {
        List<Map<String, Object>> mapList = couponService.queryCouponExamineList(ofSearch);
        if (mapList.size() > 0) {
            for (Map<String, Object> stringObjectMap : mapList) {
                Object startTime = stringObjectMap.get("startTime");
                Object endTime = stringObjectMap.get("endTime");
                stringObjectMap.put("timeValue", startTime + "至" + endTime);
                Integer publisherType = (Integer) stringObjectMap.get("publisherType");
                if (publisherType != null) {
                    if (publisherType == 1) {
 
                    }
                }
            }
        }
        return mapList;
    }
 
 
    @ResponseBody
    @PostMapping("/base/coupon/couponExamineDetail")
    Map<String, Object> queryCouponExamineDetail(@RequestBody Integer id) {
        Map<String, Object> couponInfo = new HashMap<>();
        Coupon coupon = couponService.getById(id);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (ToolUtil.isNotEmpty(coupon)) {
            couponInfo.put("id", coupon.getId());
            couponInfo.put("auditStatus", coupon.getAuditStatus());
            couponInfo.put("publisherType", coupon.getPublisherType());
 
            couponInfo.put("name", coupon.getName());
            couponInfo.put("type", coupon.getType());
            JSONObject jsonObject = JSON.parseObject(coupon.getContent());
            switch (coupon.getType()) {
                case 1:
//                {"conditionalAmount":50,"deductionAmount":10,"experienceName":""}
                    couponInfo.put("num1", jsonObject.getDouble("conditionalAmount"));
                    couponInfo.put("num2", jsonObject.getDouble("deductionAmount"));
                    break;
                case 2:
                    couponInfo.put("num1", jsonObject.getDouble("conditionalAmount"));
                    break;
                case 3:
                    couponInfo.put("num1", jsonObject.getString("experienceName"));
                    break;
                default:
                    break;
            }
            couponInfo.put("illustrate", coupon.getIllustrate());
            switch (coupon.getDistributionMethod()) {
                case 1:
                    couponInfo.put("distributionMethod", "积分注册");
                    break;
                case 2:
                    couponInfo.put("distributionMethod", "注册赠送");
                    break;
                case 3:
                    couponInfo.put("distributionMethod", "自动发券");
                    break;
                default:
                    break;
            }
            couponInfo.put("redemptionMethod", coupon.getRedemptionMethod());
            couponInfo.put("integral", coupon.getIntegral());
            couponInfo.put("cash", coupon.getCash());
            switch (coupon.getUserPopulation()) {
                case 1:
                    couponInfo.put("userPopulation", "全部用户");
                    break;
                case 2:
                    couponInfo.put("userPopulation", "年度会员");
                    break;
                case 3:
                    couponInfo.put("userPopulation", "已有学员用户");
                    break;
                default:
                    break;
            }
            couponInfo.put("quantityIssued", coupon.getQuantityIssued());
            couponInfo.put("pickUpQuantity", coupon.getPickUpQuantity());
            String startTime = simpleDateFormat.format(coupon.getStartTime());
            String endTime = simpleDateFormat.format(coupon.getEndTime());
            couponInfo.put("timeValue", startTime + "至" + endTime);
            couponInfo.put("useScope", coupon.getUseScope());
            ArrayList<Map<String, Object>> maps = new ArrayList<>();
            switch (coupon.getUseScope()) {
                case 2:
                    List<CouponCity> couponCities = cityService.list(new LambdaQueryWrapper<CouponCity>()
                            .eq(CouponCity::getCouponId, coupon.getId()));
                    if (couponCities.size() > 0) {
                        for (CouponCity couponCity : couponCities) {
                            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                            stringObjectHashMap.put("province", couponCity.getProvince());
                            stringObjectHashMap.put("city", couponCity.getCity());
                            maps.add(stringObjectHashMap);
                        }
                        couponInfo.put("rangeData", maps);
                    }
                    break;
                case 3:
                    List<CouponStore> list = couStoreService.list(new LambdaQueryWrapper<CouponStore>()
                            .eq(CouponStore::getCouponId, coupon.getId()));
                    if (list.size() > 0) {
                        // 获取门店ids
                        List<Integer> collect = list.stream().map(CouponStore::getStoreId).collect(Collectors.toList());
                        List<Store> storeList = stoClient.queryStoreByIds(collect);
                        if (storeList.size() > 0) {
                            for (Store store : storeList) {
 
                                StoreInfoDto storeInfo = stoClient.getStoreInfo(store.getStoreStaffId());
                                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                                stringObjectHashMap.put("procity", store.getProvince() + store.getCity());
                                stringObjectHashMap.put("storeAccount", storeInfo.getInfo());
                                stringObjectHashMap.put("storeName", store.getName());
                                maps.add(stringObjectHashMap);
                            }
                            couponInfo.put("rangeData", maps);
                        }
 
                    }
                    break;
                default:
                    break;
            }
        }
        return couponInfo;
    }
 
 
    @ResponseBody
    @PostMapping("/base/coupon/updateCouponExamine")
    public boolean updateCouponData(@RequestBody Coupon coupon) {
        try {
            return couponService.updateById(coupon);
        } catch (Exception e) {
            return false;
        }
    }
 
    @ResponseBody
    @PostMapping("/base/coupon/insertIntoCouponData")
    public boolean saveCouponData(@RequestBody CouponDataVo dataVo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            System.out.println(dataVo);
            Coupon coupon = new Coupon();
            coupon.setName(dataVo.getCouponName());
            coupon.setType(dataVo.getPrescription());
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            Gson gson = new Gson();
            switch (dataVo.getPrescription()) {
//                {"conditionalAmount":50,"deductionAmount":10,"experienceName":""}
                case 1:
                    stringObjectHashMap.put("conditionalAmount", dataVo.getCondition());
                    stringObjectHashMap.put("deductionAmount", dataVo.getSubtraction());
                    coupon.setContent(gson.toJson(stringObjectHashMap));
                    break;
                case 2:
                    stringObjectHashMap.put("conditionalAmount", dataVo.getDiscount());
                    coupon.setContent(gson.toJson(stringObjectHashMap));
                    break;
                case 3:
                    stringObjectHashMap.put("experienceName", dataVo.getExperience());
                    coupon.setContent(gson.toJson(stringObjectHashMap));
                    break;
                default:
                    break;
            }
            coupon.setIllustrate(dataVo.getIllustrate());
            coupon.setDistributionMethod(dataVo.getDistributionMethod());
            coupon.setRedemptionMethod(dataVo.getExchangeMethod());
            if (dataVo.getExchangeMethod() != null&&dataVo.getDistributionMethod()!=4) {
                switch (dataVo.getExchangeMethod()) {
                    case 1:
                        coupon.setIntegral(BigDecimal.valueOf(dataVo.getRequiredPoints()));
                        break;
                    case 2:
                        coupon.setIntegral(BigDecimal.valueOf(dataVo.getRequiredPoints()));
                        coupon.setCash(dataVo.getRequiredCash());
                        break;
                    case 3:
                        coupon.setCash(dataVo.getRequiredCash());
                        break;
                    default:
                        break;
                }
            }
 
            coupon.setQuantityIssued(dataVo.getQuantityIssued());
            coupon.setPickUpQuantity(dataVo.getPickUpQuantity());
            coupon.setUseScope(dataVo.getCompany());
            coupon.setUserPopulation(dataVo.getUserGroup());
            String timeDeal = dataVo.getPeriodOfValidity();
            if (ToolUtil.isNotEmpty(timeDeal)) {
                String[] split = timeDeal.split(" - ");
                coupon.setStartTime(simpleDateFormat.parse(split[0]));
                coupon.setEndTime(simpleDateFormat.parse(split[1]));
            }
            coupon.setAuditStatus(1);
            coupon.setStatus(1);
            coupon.setState(1);
            coupon.setInsertTime(new Date());
            coupon.setCover(dataVo.getGoodImg());
            String goodImgs = dataVo.getGoodImgs();
            String[] imgsSplit = goodImgs.split(",");
            if (imgsSplit.length > 0) {
                if (imgsSplit.length == 1) {
                    coupon.setProductImages(imgsSplit[0]);
                } else {
                    coupon.setProductImages(goodImgs);
                }
            }
            if (dataVo.getUserType() == 1) {
                coupon.setPublisherType(2);
                coupon.setAuditStatus(2);
                coupon.setCityManagerId(dataVo.getCityManagerId());
            }
            if (dataVo.getUserType() == 2) {
                coupon.setPublisherType(1);
                coupon.setAuditStatus(1);
                coupon.setCityManagerId(dataVo.getCityManagerId());
            }
            if (dataVo.getUserType() == 3) {
                coupon.setPublisherType(3);
                coupon.setAuditStatus(1);
                coupon.setCityManagerId(dataVo.getCityManagerId());
            }
 
            boolean save = couponService.save(coupon);
            AppUserByNameAndPhoneDTO dto = new AppUserByNameAndPhoneDTO();
            List<TAppUser> tAppUsers = appUserClient.queryAppUserList(dto);
            // 发放数量
            Integer quantityIssued = dataVo.getQuantityIssued();
            // 限领数量
            Integer pickUpQuantity = dataVo.getPickUpQuantity();
            // 赠送用户数量
            int count = quantityIssued / pickUpQuantity;
            // 自动发券
            if (dataVo.getDistributionMethod() == 3) {
                // 判断用户人群 再判断限领数量
                switch (dataVo.getUserGroup()) {
                    case 1:
                        // 给全部用户发券
                        // 全部用户ids
                        List<Integer> collect = tAppUsers.stream()
                                .map(TAppUser::getId).collect(Collectors.toList());
                        for (int i = 0; i < count; i++) {
                            for (int j = 0; j < pickUpQuantity; j++) {
                                UserCoupon u1 = new UserCoupon();
                                u1.setCouponId(coupon.getId());
                                u1.setUserId(collect.get(i));
                                u1.setStatus(1);
                                u1.setVerificationUserId(null);
                                u1.setVerificationTime(null);
                                u1.setInsertTime(new Date());
                                ucService.save(u1);
                            }
                        }
                        break;
                    case 2:
                        // 给年度会员发券 获取年度会员ids
                        List<Integer> collect1 = tAppUsers.stream().filter(t -> t.getVipEndTime().after(new Date()))
                                .map(TAppUser::getId)
                                .collect(Collectors.toList());
                        for (int i = 0; i < count; i++) {
                            for (int j = 0; j < pickUpQuantity; j++) {
                                UserCoupon u1 = new UserCoupon();
                                u1.setCouponId(coupon.getId());
                                u1.setUserId(collect1.get(i));
                                u1.setStatus(1);
                                u1.setVerificationUserId(null);
                                u1.setVerificationTime(null);
                                u1.setInsertTime(new Date());
                                ucService.save(u1);
                            }
                        }
                        break;
                    case 3:
                        // 给已有学员用户发券 获取已有学员的用户ids
                        List<Integer> collect2 = studentClient.getHasStudentUser();
                        for (int i = 0; i < count; i++) {
                            for (int j = 0; j < pickUpQuantity; j++) {
                                UserCoupon u1 = new UserCoupon();
                                u1.setCouponId(coupon.getId());
                                u1.setUserId(collect2.get(i));
                                u1.setStatus(1);
                                u1.setVerificationUserId(null);
                                u1.setVerificationTime(null);
                                u1.setInsertTime(new Date());
                                ucService.save(u1);
                            }
                        }
                        break;
                }
            }
            if (save) {
                if (dataVo.getCompany() == 3) {
                    String[] split = dataVo.getStoreIds().split(",");
                    for (String storeId : split) {
                        CouponStore couponStore = new CouponStore();
                        couponStore.setCouponId(coupon.getId());
                        couponStore.setStoreId(Integer.parseInt(storeId));
                        couStoreService.save(couponStore);
                    }
                }
                String cityIds = dataVo.getCityIds();
                String[] split = cityIds.split(",");
                List<Integer> cityIdss = new ArrayList<>();
                if (dataVo.getCompany() == 2 && split.length > 0) {
                    for (String s : split) {
                        int intValue = Integer.parseInt(s);
                        cityIdss.add(intValue);
                    }
                    List<CityDataAndProvinceDataVo> cityAndProvince = regionClient.getCityAndProvince(cityIdss);
                    for (CityDataAndProvinceDataVo cityId : cityAndProvince) {
                        CouponCity couponCity = new CouponCity();
                        couponCity.setCouponId(coupon.getId());
                        couponCity.setCityCode(cityId.getCityCode());
                        couponCity.setCity(cityId.getCityName());
                        couponCity.setProvinceCode(cityId.getProvinceCode());
                        couponCity.setProvince(cityId.getProvinceName());
                        System.out.println(couponCity);
                        cityService.save(couponCity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    @ResponseBody
    @PostMapping("/base/coupon/queryCity")
    public List<CouponCity> queryCity(@RequestBody Integer id) {
        List<CouponCity> list = cityService.list(new LambdaQueryWrapper<CouponCity>().eq(CouponCity::getCouponId, id));
        return list;
    }
 
    @ResponseBody
    @PostMapping("/base/coupon/queryStore")
    public List<Integer> queryStore(@RequestBody Integer id) {
        return couStoreService.list(new LambdaQueryWrapper<CouponStore>().eq(CouponStore::getCouponId, id)).stream().map(CouponStore::getStoreId).collect(Collectors.toList());
    }
 
 
    @PostMapping("/base/coupon/listRecord")
    @ResponseBody
    public List<Map<String, Object>> listRecord(@RequestBody CouponRecordQuery ofSearch) {
        Page<Object> objectPage = new Page<>(ofSearch.getOffset(), ofSearch.getLimit());
        return couponService.listRecord(objectPage, ofSearch.getId(), ofSearch.getIds(), ofSearch.getType());
    }
 
 
    @PostMapping("/base/coupon/updateType")
    public void updateType(@RequestBody Long id) {
        couponService.updateType(id);
    }
}