xuhy
2025-04-24 36e4beaea3c7cc2f05213e9fdf023b9685649e21
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
package com.ruoyi.admin.controller;
 
 
import cn.hutool.http.HttpException;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.admin.config.WeChatConfig;
import com.ruoyi.admin.entity.*;
import com.ruoyi.admin.service.*;
import com.ruoyi.admin.utils.MD5AndKL;
import com.ruoyi.admin.utils.WeChatUtil;
import com.ruoyi.admin.utils.util.CreateLinkStringByGet1;
import com.ruoyi.admin.utils.util.HttpRequester;
import com.ruoyi.admin.utils.util.HttpRespons;
import com.ruoyi.admin.utils.util.Md5_Sign;
import com.ruoyi.admin.vo.InfoDto;
import com.ruoyi.admin.vo.MoneyRecentQuery;
import com.ruoyi.admin.vo.PayDto;
import com.ruoyi.admin.vo.RencentBalance;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.service.TokenService;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.service.partnerpayments.app.model.Transaction;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com. wechat. pay. java. service. payments. jsapi. model. PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Getter;
import org.apache.commons.codec.CharEncoding;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
 
/**
 * <p>
 * 加盟商信息表 前端控制器
 * </p>
 *
 * @author hjl
 * @since 2024-05-29
 */
@RestController
@RequestMapping("/franchisee")
@Api(tags = {"后台-加盟商管理"})
public class FranchiseeController {
 
    @Resource
    private FranchiseeService franchiseeService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RegionService regionService;
    @Resource
    private MasterWorkerService masterWorkerService;
    @Resource
    private SiteService siteService;
 
    @Resource
    private JsapiService jsapiService;
 
    @Resource
    private WeChatConfig weChatConfig;
 
    @Resource
    private PrivateKeySigner privateKeySigner;
 
    @Resource
    private TFranchiseeBalanceChangeService balanceChangeService;
 
    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new SecureRandom();
 
 
    @ApiOperation(value = "加盟商列表余额", tags = {"后台2.0-加盟商列表余额"})
    @GetMapping(value = "/recent/money")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "加盟商名称", name = "name", dataType = "String"),
            @ApiImplicitParam(value = "管理员", name = "head", dataType = "String"),
            @ApiImplicitParam(value = "手机号码", name = "phone", dataType = "String"),
            @ApiImplicitParam(value = "管辖城市", name = "city", dataType = "String"),
            @ApiImplicitParam(value = "充值/扣款起始时间", name = "date1", dataType = "String"),
            @ApiImplicitParam(value = "充值/扣款结束时间", name = "date2", dataType = "String"),
            @ApiImplicitParam(value = "页码", name = "pageNum", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "每页条数", name = "pageSize", dataType = "Integer", required = true)
    })
    public R<RencentBalance> recentmoney(String name, String head, String phone, String city,
                                         String date1,String date2,
                                         @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        BigDecimal balance = new BigDecimal(0);
        LambdaQueryWrapper<Franchisee> franchiseeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        franchiseeLambdaQueryWrapper = StringUtils.isNotBlank(name) ? franchiseeLambdaQueryWrapper.like(Franchisee::getName, name) : franchiseeLambdaQueryWrapper;
        franchiseeLambdaQueryWrapper = StringUtils.isNotBlank(head) ? franchiseeLambdaQueryWrapper.like(Franchisee::getHead, head) : franchiseeLambdaQueryWrapper;
        franchiseeLambdaQueryWrapper = StringUtils.isNotBlank(phone) ? franchiseeLambdaQueryWrapper.like(Franchisee::getHeadPhone, phone) : franchiseeLambdaQueryWrapper;
        franchiseeLambdaQueryWrapper = StringUtils.isNotBlank(city) ? franchiseeLambdaQueryWrapper.like(Franchisee::getCity, city) : franchiseeLambdaQueryWrapper;
        List<Franchisee> list = franchiseeService.list(franchiseeLambdaQueryWrapper);
        List<Integer> collect = list.stream().map(Franchisee::getId).collect(Collectors.toList());
        if (collect.isEmpty())collect.add(-1);
        for (Franchisee franchisee : list) {
            balance = balance.add(franchisee.getBalance());
        }
        //充值的金额
        BigDecimal balance1 = new BigDecimal(0);
        List<TFranchiseeBalanceChange> list1 = balanceChangeService.lambdaQuery()
                .in(TFranchiseeBalanceChange::getFranchiseeId,collect)
                .between(date1!=null,TFranchiseeBalanceChange::getCreateTime, date1, date2)
                .eq(TFranchiseeBalanceChange::getType, 1).list();
        for (TFranchiseeBalanceChange franchiseeBalanceChange : list1) {
            balance1 = balance1.add(franchiseeBalanceChange.getAmount());
        }
        //扣除的金额
        BigDecimal balance2 = new BigDecimal(0);
        List<TFranchiseeBalanceChange> list2 = balanceChangeService.lambdaQuery()
                .in(TFranchiseeBalanceChange::getFranchiseeId,collect)
                .eq(TFranchiseeBalanceChange::getType, 2)
                .between(date1!=null,TFranchiseeBalanceChange::getCreateTime, date1, date2)
                .eq(TFranchiseeBalanceChange::getIs_pay,1).list();
        for (TFranchiseeBalanceChange franchiseeBalanceChange : list2) {
            balance2 = balance2.add(franchiseeBalanceChange.getAmount());
        }
 
        RencentBalance balance3 = new RencentBalance();
        balance3.setBalance1(balance);
        balance3.setBalance2(balance1);
        balance3.setBalance3(balance2);
 
        return R.ok(balance3);
    }
 
    @ApiOperation(value = "详情",tags = {"师傅段2.0-统一充值扣款列表"})
    @PostMapping(value = "/change/detail")
    public R<TFranchiseeBalanceChange> detail1(@RequestParam Integer id) throws AlipayApiException {
        TFranchiseeBalanceChange balanceChange = balanceChangeService.getById(id);
        if (balanceChange.getType()==2){
            balanceChange.setPayStr("微信支付");
        }
        return R.ok(balanceChange);
    }
 
 
    @ApiOperation(value = "扣款记录及充值记录", tags = {"后台2.0-统一充值扣款列表","师傅段2.0-统一充值扣款列表"})
    @PostMapping(value = "/recent/money/list")
    public R<Page<TFranchiseeBalanceChange>> recentmoneylist(@RequestBody MoneyRecentQuery moneyRecentQuery) {
        Long userid = tokenService.getLoginUser().getUserid();
        SysUser sysUser = sysUserService.getById(userid);
        Page<TFranchiseeBalanceChange> page = balanceChangeService.lambdaQuery().eq(moneyRecentQuery.getType() != null, TFranchiseeBalanceChange::getType, moneyRecentQuery.getType())
                .eq(sysUser.getFranchiseeId() != null, TFranchiseeBalanceChange::getFranchiseeId, sysUser.getFranchiseeId())
                .like(moneyRecentQuery.getName() != null && !"".equals(moneyRecentQuery.getName()), TFranchiseeBalanceChange::getFranchiseeName, moneyRecentQuery.getName())
                .ge(moneyRecentQuery.getDate1() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate1())
                .le(moneyRecentQuery.getDate2() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate2())
                .eq(moneyRecentQuery.getFranchId()!=null, TFranchiseeBalanceChange::getFranchiseeId, moneyRecentQuery.getFranchId())
                .eq(TFranchiseeBalanceChange::getIs_pay,1)
                .orderByDesc(TFranchiseeBalanceChange::getCreateTime)
                .page(Page.of(moneyRecentQuery.getPageNum(), moneyRecentQuery.getPageSize()));
 
 
        for (TFranchiseeBalanceChange record : page.getRecords()) {
            Franchisee franchisee = franchiseeService.getById(record.getFranchiseeId());
            if (franchisee.getSiteIds()!=null) {
                String siteIds = franchisee.getSiteIds();
                List<Site> list1 = siteService.lambdaQuery().in(Site::getId, siteIds.split(",")).list();
                record.setList1(list1);
            }
            String cityCode = franchisee.getCityCode();
            List<Region> list = regionService.lambdaQuery().in(Region::getCode, cityCode.split(",")).list();
            record.setList(list);
            record.setFranchiseeName(franchisee.getName());
            if (record.getType()==1){
                record.setPayStr("扣除旧机款");
            }
            if (record.getType()==2){
                record.setPayStr("充值");
            }
        }
        return R.ok(page);
    }
 
    @ApiOperation(value = "导出", tags = {"后台2.0-统一充值扣款列表"})
    @PostMapping(value = "/recent/money/list/export")
    public R<Page<TFranchiseeBalanceChange>> export(@RequestBody MoneyRecentQuery moneyRecentQuery, HttpServletResponse response) {
        Long userid = tokenService.getLoginUser().getUserid();
        SysUser sysUser = sysUserService.getById(userid);
        if (moneyRecentQuery.getType()==2) {
            List<TFranchiseeBalanceChange> page = balanceChangeService.lambdaQuery().eq(moneyRecentQuery.getType() != null, TFranchiseeBalanceChange::getType, moneyRecentQuery.getType())
                    .eq(sysUser.getFranchiseeId() != null, TFranchiseeBalanceChange::getFranchiseeId, sysUser.getFranchiseeId())
                    .eq(moneyRecentQuery.getName() != null && !"".equals(moneyRecentQuery.getName()), TFranchiseeBalanceChange::getFranchiseeName, moneyRecentQuery.getName())
                    .ge(moneyRecentQuery.getDate1() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate1())
                    .le(moneyRecentQuery.getDate2() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate2())
                    .eq(moneyRecentQuery.getFranchId()!=null, TFranchiseeBalanceChange::getFranchiseeId, moneyRecentQuery.getFranchId())
                    .eq(TFranchiseeBalanceChange::getIs_pay,1)
                    .orderByDesc(TFranchiseeBalanceChange::getCreateTime)
                    .list();
            for (TFranchiseeBalanceChange tFranchiseeBalanceChange : page) {
                tFranchiseeBalanceChange.setPayStr("微信支付");
                LocalDateTime createTime = tFranchiseeBalanceChange.getCreateTime();
                // 转化为String类型的格式字符串yyyy-MM-dd HH:mm:ss
                tFranchiseeBalanceChange.setCreateTimeStr(createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            try {
                response.setCharacterEncoding(Constants.UTF8);
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        URLEncoder.encode(Constants.EXCEL_ORDER_FILE_NAME, CharEncoding.UTF_8) + ".xlsx");
            } catch (UnsupportedEncodingException e) {
                return R.fail("excel导出失败!");
            }
            try {
                // excel模板封装
                ExcelWriterBuilder excelWriterBuilder = EasyExcelFactory.write(response.getOutputStream());
                InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + Constants.EXCEL_ORDER_FILE_NAME1 + ".xlsx");
                // 自动释放资源
                try (ExcelWriter excelWriter = excelWriterBuilder.withTemplate(stream).build()) {
                    WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();
                    excelWriter.fill(page, writeSheet);
                    excelWriter.finish();
                } catch (Exception e) {
                    return R.fail("excel导出失败!");
                }
            } catch (IOException e) {
                return R.fail("excel导出失败!");
            }
            return R.ok();
        }else {
            List<TFranchiseeBalanceChange> page = balanceChangeService.lambdaQuery().eq(moneyRecentQuery.getType() != null, TFranchiseeBalanceChange::getType, moneyRecentQuery.getType())
                    .eq(sysUser.getFranchiseeId() != null, TFranchiseeBalanceChange::getFranchiseeId, sysUser.getFranchiseeId())
                    .eq(moneyRecentQuery.getName() != null && !"".equals(moneyRecentQuery.getName()), TFranchiseeBalanceChange::getFranchiseeName, moneyRecentQuery.getName())
                    .ge(moneyRecentQuery.getDate1() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate1())
                    .le(moneyRecentQuery.getDate2() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate2())
                    .orderByDesc(TFranchiseeBalanceChange::getCreateTime)
                    .list();
            for (TFranchiseeBalanceChange tFranchiseeBalanceChange : page) {
                LocalDateTime createTime = tFranchiseeBalanceChange.getCreateTime();
                // 转化为String类型的格式字符串yyyy-MM-dd HH:mm:ss
                tFranchiseeBalanceChange.setCreateTimeStr(createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            try {
                response.setCharacterEncoding(Constants.UTF8);
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        URLEncoder.encode(Constants.EXCEL_ORDER_FILE_NAME, CharEncoding.UTF_8) + ".xlsx");
            } catch (UnsupportedEncodingException e) {
                return R.fail("excel导出失败!");
            }
            try {
                // excel模板封装
                ExcelWriterBuilder excelWriterBuilder = EasyExcelFactory.write(response.getOutputStream());
                InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + Constants.EXCEL_ORDER_FILE_NAME2 + ".xlsx");
                // 自动释放资源
                try (ExcelWriter excelWriter = excelWriterBuilder.withTemplate(stream).build()) {
                    WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();
                    excelWriter.fill(page, writeSheet);
                    excelWriter.finish();
                } catch (Exception e) {
                    return R.fail("excel导出失败!");
                }
            } catch (IOException e) {
                return R.fail("excel导出失败!");
            }
            return R.ok();
        }
    }
 
 
    @ApiOperation(value = "扣余额", tags = {"后台2.0-加盟商列表余额"})
    @PostMapping(value = "/recent/money/consume")
    public R<Page<TFranchiseeBalanceChange>> consume(@RequestBody TFranchiseeBalanceChange franchiseeBalanceChange) {
        Franchisee byId = franchiseeService.getById(franchiseeBalanceChange.getFranchiseeId());
        franchiseeBalanceChange.setFranchiseeName(byId.getName());
        Region byId1 = regionService.getById(franchiseeBalanceChange.getRegionId());
        franchiseeBalanceChange.setRegionName(byId1.getName());
 
        Site byId2 = siteService.getById(franchiseeBalanceChange.getSiteId());
        franchiseeBalanceChange.setSiteName(byId2.getSiteName());
        franchiseeBalanceChange.setIs_pay(1);
        balanceChangeService.save(franchiseeBalanceChange);
        byId.setBalance(byId.getBalance().subtract(franchiseeBalanceChange.getAmount()));
        franchiseeService.updateById(byId);
        return R.ok();
    }
 
    @Getter
    private PrivateKey privateKey;
 
    @ApiOperation(value = "js支付", tags = {"2.0-支付"})
    @GetMapping(value = "/js/wxPay")
    public R jsPay(@RequestParam String openId,@RequestParam BigDecimal money,@RequestParam Integer userId) throws IOException {
        SysUser byId1 = sysUserService.getById(userId);
        this.privateKey = PemUtil.loadPrivateKey(getPrivateKeyStream());
        this.privateKeySigner = new PrivateKeySigner(weChatConfig.merchantSerialNumber, privateKey);
 
        String code = generateTradeNumber();
        int i = money.multiply(BigDecimal.valueOf(100)).intValue();
        Franchisee byId = franchiseeService.getById(byId1.getFranchiseeId());
 
 
        //
        String key = "ad273ceb5e1b49e68d5c565d28d1d305";/** md5密钥商户后台-商户中心-商户设置-密钥管理获取 必填!*/
        Map<String, String> map = new HashMap<String, String>();
        map.put("p0_Version", "2.5");/** 版本号 */
        map.put("p1_MerchantNo", "888122400007793");/** 商户编号 */
        map.put("p2_OrderNo", code); /**商户订单号*/
        map.put("p3_Amount", String.valueOf(money));/**订单金额*/
        map.put("p4_Cur", "1"); /**交易币种 */
        map.put("q5_OpenId", openId);
        map.put("p5_ProductName", "加盟商充值"); /** 商品名称 */
        map.put("p9_NotifyUrl", "http://101.34.55.62:9100/admin/franchisee/callBack"); /** 服务器异步通知地址 */
        map.put("q1_FrpCode", "WEIXIN_APP3"); /** 交易类型*/
        map.put("q7_AppId", "wx1a4a7760be53a835"); /** 交易类型*/
        map.put("qa_TradeMerchantNo", "777165000859101"); /** 777开头的报备商户号   必填!*/
 
        String Strmap = CreateLinkStringByGet1.createLinkStringByGet(map);
 
        // 签名
        String sign = "";
        sign = Md5_Sign.SignByMD5(Strmap, key);
        map.put("hmac", sign);/** 签名数据 */
        System.out.println("发送:" + JSON.toJSONString(map).toString());
 
        // post请求参数内容
        HttpRequester hr = new HttpRequester();
        HttpRespons HP = hr.sendPost("https://www.joinpay.com/trade/uniPayApi.action", map);
        System.out.println("接收返回参数:" + HP.getContent());
        JSONObject jsonObject = JSONObject.parseObject(HP.getContent());
        JSONObject rcResult = JSONObject.parseObject(jsonObject.getString("rc_Result"));
        Map<String, Object> map2 = new HashMap<>();
        map2.put("rcResult", rcResult);
//        map2.put("timestamp", rcResult.get("timeStamp"));
//        map2.put("prepayid", rcResult.get("package"));
//        map2.put("sign", rcResult.get("paySign"));
 
        //
//        PrepayRequest prepayRequest = new PrepayRequest();
//        prepayRequest.setAppid(weChatConfig.appId);
//        prepayRequest.setMchid(weChatConfig.merchantId);
//        prepayRequest.setDescription("加盟商充值");
//        prepayRequest.setOutTradeNo(code);
//        prepayRequest.setNotifyUrl("http://www.zhipingwang.com.cn:9090/admin/franchisee/callBack");
//        Amount amount = new Amount();
//        amount.setTotal(i);
//        prepayRequest.setAmount(amount);
//        Payer payer = new Payer();
//        payer.setOpenid(openId);
//        prepayRequest.setPayer(payer);
//        PrepayResponse prepay = jsapiService.prepay(prepayRequest);
//        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
//        String packageStr = "prepay_id=" + prepay.getPrepayId();
//
//        String prepay_id = prepay.getPrepayId();
//        //重新进行签名后返回给前端
 
////        String s1 = this.weixinSignature(map2);
//        String signStr = Stream.of(weChatConfig.getAppId(), timeStamp, code, packageStr).collect(Collectors.joining("\n", "", "\n"));
//        String packageSign = privateKeySigner.sign(signStr.getBytes(StandardCharsets.UTF_8)).getSign();
//
//        System.err.println(map2);
 
 
        TFranchiseeBalanceChange tFranchiseeBalanceChange = new TFranchiseeBalanceChange();
        tFranchiseeBalanceChange.setAmount(money.multiply(new BigDecimal("0.9972")).setScale(2,BigDecimal.ROUND_DOWN));
        tFranchiseeBalanceChange.setIs_pay(0);
        tFranchiseeBalanceChange.setFranchiseeName(byId.getName());
        tFranchiseeBalanceChange.setFranchiseeId(String.valueOf(byId.getId()));
        tFranchiseeBalanceChange.setType(2);
        tFranchiseeBalanceChange.setRemark("微信支付");
        tFranchiseeBalanceChange.setCode(code);
        balanceChangeService.save(tFranchiseeBalanceChange);
 
        return R.ok(map2);
 
    }
 
    public InputStream getPrivateKeyStream() {
        // 需要证书释放
        byte[] certData;
//        InputStream certStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(this.privateKeyPath);
        InputStream certStream = null;
        try {
            certStream = new FileInputStream(weChatConfig.privateKeyPath);
            certData = IOUtils.toByteArray(certStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("私钥文件未找到");
        }finally {
            if(null != certStream){
                try {
                    certStream.close();
                } catch (IOException e) {
                }
            }
        }
        return new ByteArrayInputStream(certData);
    }
    @Resource
    private TokenService tokenService;
    @Resource
    private NativePayService nativePayService;
 
    public static void main(String[] args) {
        BigDecimal money = new BigDecimal(2);
 
 
        System.err.println(money.multiply(new BigDecimal("0.9972")).setScale(2,BigDecimal.ROUND_DOWN));
    }
 
    @ApiOperation(value = "扫码支付",tags = {"后台2.0-加盟商列表余额"})
    @PostMapping(value = "/code/buy")
    public R buy(@RequestParam BigDecimal money) throws AlipayApiException, IOException {
        Long userid = tokenService.getLoginUser().getUserid();
        SysUser byId1 = sysUserService.getById(userid);
        Franchisee byId = franchiseeService.getById(byId1.getFranchiseeId());
        String code = generateTradeNumber();
        int i = money.multiply(BigDecimal.valueOf(100)).intValue();
        String key = "ad273ceb5e1b49e68d5c565d28d1d305";/** md5密钥商户后台-商户中心-商户设置-密钥管理获取 必填!*/
        Map<String, String> map = new HashMap<String, String>();
        map.put("p0_Version", "2.5");/** 版本号 */
        map.put("p1_MerchantNo", "888122400007793");/** 商户编号 */
        map.put("p2_OrderNo", code); /**商户订单号*/
        map.put("p3_Amount", String.valueOf(money));/**订单金额*/
        map.put("p4_Cur", "1"); /**交易币种 */
        map.put("p5_ProductName", "充值"); /** 商品名称 */
        map.put("p6_ProductDesc", "加盟商充值"); /** 商品名称 */
//        map.put("p7_Mp", ""); /** 如果商户请求时传递了该参数,则返回给商户时会原值传 回。 */
        map.put("p9_NotifyUrl", "http://101.34.55.62:9100/admin/franchisee/callBack"); /** 服务器异步通知地址 */
        map.put("q1_FrpCode", "WEIXIN_NATIVE"); /** 微信扫码(主扫)【注:此为用户主扫,商户被扫】*/
        map.put("q4_IsShowPic", "1"); /** 是否展示二 维码图片 1表示输出*/
        map.put("q7_AppId", "wx1a4a7760be53a835"); /** 交易类型*/
        map.put("qa_TradeMerchantNo", "777165000859101"); /** 777开头的报备商户号   必填!*/
        map.put("qi_FqSellerPercen", "0"); /** 卖家承担收 费比例 目前仅支持传入 0 ,即用户承 担手续费!*/
 
        String Strmap = CreateLinkStringByGet1.createLinkStringByGet(map);
 
        // 签名
        String sign = "";
        sign = Md5_Sign.SignByMD5(Strmap, key);
        map.put("hmac", sign);/** 签名数据 */
        System.out.println("发送:" + JSON.toJSONString(map).toString());
 
        // post请求参数内容
        HttpRequester hr = new HttpRequester();
        HttpRespons HP = hr.sendPost("https://trade.joinpay.com/tradeRt/uniPay", map);
        System.out.println("接收返回参数:" + HP.getContent());
        JSONObject jsonObject = JSONObject.parseObject(HP.getContent());
        String rcResult = jsonObject.getString("rd_Pic");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("rcResult", rcResult);
//        com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest prepayRequest = new com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest();
//            prepayRequest.setAppid(weChatConfig.appId);
//            prepayRequest.setMchid(weChatConfig.merchantId);
//            prepayRequest.setOutTradeNo(code);
//            prepayRequest.setDescription("购买资料");
//            prepayRequest.setNotifyUrl("http://www.zhipingwang.com.cn:9090/admin/franchisee/callBack");
//            com.wechat.pay.java.service.payments.nativepay.model.Amount amount = new com.wechat.pay.java.service.payments.nativepay.model.Amount();
//            amount.setTotal(i);
//            prepayRequest.setAmount(amount);
//            // 调用下单方法,得到应答
//            com.wechat.pay.java.service.partnerpayments.app.model.PrepayResponse response;
        try {
//                com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse prepay = nativePayService.prepay(prepayRequest);
            //预支付成功,创建预支付订单
            TFranchiseeBalanceChange tFranchiseeBalanceChange = new TFranchiseeBalanceChange();
            tFranchiseeBalanceChange.setAmount(money.multiply(new BigDecimal("0.9972")).setScale(2,BigDecimal.ROUND_DOWN));
            tFranchiseeBalanceChange.setIs_pay(0);
            tFranchiseeBalanceChange.setFranchiseeName(byId.getName());
            tFranchiseeBalanceChange.setFranchiseeId(String.valueOf(byId.getId()));
            tFranchiseeBalanceChange.setType(2);
            tFranchiseeBalanceChange.setCode(code);
            tFranchiseeBalanceChange.setRemark("加盟商扫码充值");
            balanceChangeService.save(tFranchiseeBalanceChange);
 
 
 
            PayDto payDto = new PayDto();
            payDto.setOrderId(tFranchiseeBalanceChange.getId());
            payDto.setQrCode(rcResult);
 
            return R.ok(payDto);
        } catch (HttpException e) { // 发送HTTP请求失败
//                log.error("发送HTTP请求失败: {}", e.getHttpRequest());
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300,例如500
//                log.error("服务返回状态异常: {}", e.getResponseBody());
        } catch (MalformedMessageException e) { // 服务返回成功,返回体类型不合法,或者解析返回体失败
//                log.error("返回体类型不合法: {}", e.getMessage());
        } catch (Exception e) {
//                log.error("预下单异常: {}", e.getMessage());
        }
        return null;
 
    }
    @ApiOperation(value = "扫码支付",tags = {"后台2.0-总平台"})
    @PostMapping(value = "/code/buyPlatform")
    public R buyPlatform(@RequestParam BigDecimal money,Integer id) throws AlipayApiException, IOException {
        Franchisee byId = franchiseeService.getById(id);
        String code = generateTradeNumber();
        int i = money.multiply(BigDecimal.valueOf(100)).intValue();
        String key = "ad273ceb5e1b49e68d5c565d28d1d305";/** md5密钥商户后台-商户中心-商户设置-密钥管理获取 必填!*/
        Map<String, String> map = new HashMap<String, String>();
        map.put("p0_Version", "2.5");/** 版本号 */
        map.put("p1_MerchantNo", "888122400007793");/** 商户编号 */
        map.put("p2_OrderNo", code); /**商户订单号*/
        map.put("p3_Amount", String.valueOf(money));/**订单金额*/
        map.put("p4_Cur", "1"); /**交易币种 */
        map.put("p5_ProductName", "充值"); /** 商品名称 */
        map.put("p6_ProductDesc", "加盟商充值"); /** 商品名称 */
//        map.put("p7_Mp", ""); /** 如果商户请求时传递了该参数,则返回给商户时会原值传 回。 */
        map.put("p9_NotifyUrl", "http://101.34.55.62:9100/admin/franchisee/callBack"); /** 服务器异步通知地址 */
        map.put("q1_FrpCode", "WEIXIN_NATIVE"); /** 微信扫码(主扫)【注:此为用户主扫,商户被扫】*/
        map.put("q4_IsShowPic", "1"); /** 是否展示二 维码图片 1表示输出*/
        map.put("q7_AppId", "wx1a4a7760be53a835"); /** 交易类型*/
        map.put("qa_TradeMerchantNo", "777165000859101"); /** 777开头的报备商户号   必填!*/
        map.put("qi_FqSellerPercen", "0"); /** 卖家承担收 费比例 目前仅支持传入 0 ,即用户承 担手续费!*/
 
        String Strmap = CreateLinkStringByGet1.createLinkStringByGet(map);
 
        // 签名
        String sign = "";
        sign = Md5_Sign.SignByMD5(Strmap, key);
        map.put("hmac", sign);/** 签名数据 */
        System.out.println("发送:" + JSON.toJSONString(map).toString());
 
        // post请求参数内容
        HttpRequester hr = new HttpRequester();
        HttpRespons HP = hr.sendPost("https://trade.joinpay.com/tradeRt/uniPay", map);
        System.out.println("接收返回参数:" + HP.getContent());
        JSONObject jsonObject = JSONObject.parseObject(HP.getContent());
        String rcResult = jsonObject.getString("rd_Pic");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("rcResult", rcResult);
//        com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest prepayRequest = new com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest();
//            prepayRequest.setAppid(weChatConfig.appId);
//            prepayRequest.setMchid(weChatConfig.merchantId);
//            prepayRequest.setOutTradeNo(code);
//            prepayRequest.setDescription("购买资料");
//            prepayRequest.setNotifyUrl("http://www.zhipingwang.com.cn:9090/admin/franchisee/callBack");
//            com.wechat.pay.java.service.payments.nativepay.model.Amount amount = new com.wechat.pay.java.service.payments.nativepay.model.Amount();
//            amount.setTotal(i);
//            prepayRequest.setAmount(amount);
//            // 调用下单方法,得到应答
//            com.wechat.pay.java.service.partnerpayments.app.model.PrepayResponse response;
        try {
//                com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse prepay = nativePayService.prepay(prepayRequest);
            //预支付成功,创建预支付订单
            TFranchiseeBalanceChange tFranchiseeBalanceChange = new TFranchiseeBalanceChange();
            tFranchiseeBalanceChange.setAmount(money.multiply(new BigDecimal("0.9972")).setScale(2,BigDecimal.ROUND_DOWN));
            tFranchiseeBalanceChange.setIs_pay(0);
            tFranchiseeBalanceChange.setFranchiseeName(byId.getName());
            tFranchiseeBalanceChange.setFranchiseeId(String.valueOf(byId.getId()));
            tFranchiseeBalanceChange.setType(2);
            tFranchiseeBalanceChange.setCode(code);
            tFranchiseeBalanceChange.setRemark("加盟商扫码充值");
            balanceChangeService.save(tFranchiseeBalanceChange);
 
 
 
            PayDto payDto = new PayDto();
            payDto.setOrderId(tFranchiseeBalanceChange.getId());
            payDto.setQrCode(rcResult);
 
            return R.ok(payDto);
        } catch (HttpException e) { // 发送HTTP请求失败
//                log.error("发送HTTP请求失败: {}", e.getHttpRequest());
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300,例如500
//                log.error("服务返回状态异常: {}", e.getResponseBody());
        } catch (MalformedMessageException e) { // 服务返回成功,返回体类型不合法,或者解析返回体失败
//                log.error("返回体类型不合法: {}", e.getMessage());
        } catch (Exception e) {
//                log.error("预下单异常: {}", e.getMessage());
        }
        return null;
 
    }
 
    @ApiOperation(value = "轮询获取支付状态",tags = {"后台2.0-加盟商列表余额"})
    @PostMapping(value = "/code/check")
    public R buy(@RequestParam Integer orderId) throws AlipayApiException {
        TFranchiseeBalanceChange byId = balanceChangeService.getById(orderId);
        if (byId.getIs_pay()==1){
            return R.ok(true);
        }else {
            return R.ok(false);
        }
 
    }
    @Resource
    private NotificationParser notificationParser;
 
    @ApiOperation(value = "支付回调",tags = {"微信支付回调"})
    @RequestMapping (value = "/callBack")
    @Transactional
    public R payNotify(HttpServletRequest request,String r2_OrderNo) throws Exception{
        System.err.println("======回调开始");
        System.err.println("======回调开始"+r2_OrderNo);
        System.err.println("请求"+request.getParameterMap());
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 2.0新增充值费率
        String r6Status = request.getParameter("r6_Status");
        if (org.springframework.util.StringUtils.hasLength(r6Status)){
            if (r6Status.equals("101")){
                return R.errorCode("支付失败");
            }
        }
        // 循环打印
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            for (String value : values) {
                System.err.println("======回调开始"+key + ":" + value);
            }
        }
//        Transaction transaction;
//        transaction = notificationParser.parse(WeChatUtil.handleNodifyRequestParam(request), Transaction.class);
//        if (transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
            //将记录变为已支付
            TFranchiseeBalanceChange one = balanceChangeService.lambdaQuery().eq(TFranchiseeBalanceChange::getCode,r2_OrderNo).one();
            if (one.getIs_pay()==0) {
                //将加盟商的余额增加
                Franchisee byId = franchiseeService.getById(one.getFranchiseeId());
                byId.setBalance(byId.getBalance().add(one.getAmount()));
                franchiseeService.updateById(byId);
                one.setIs_pay(1);
                balanceChangeService.updateById(one);
                return R.ok(null,"success");
//            }
 
        }
        return R.ok(null,"error");
    }
 
    public static String generateTradeNumber() {
        // 定义订单号前缀
        // 当前年月日
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String currentTimeStr =now.format(formatter);
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();
        // 构造订单号
        return currentTimeStr + timestamp;
    }
 
 
 
    private String weixinSignature(Map<String, Object> map){
        try {
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(entries);
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    Object val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            sb.append("key=" + "TA2npSNWmS0GcB0tFFRWA94rm1M0iSFs");
            String sign = MD5AndKL.MD5Encode(sb.toString(), "UTF-8").toUpperCase(); //注:MD5签名方式
            return sign;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
 
 
 
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }
 
    /**
     * 加盟商信息分页列表
     *
     * @param pageNum  页码
     * @param pageSize 每页显示条数
     */
    @RequiresPermissions("franchisee_list")
    @ApiOperation(value = "加盟商信息分页查询列表", tags = {"后台-加盟商管理"})
    @GetMapping(value = "/page")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "加盟商名称", name = "name", dataType = "String"),
            @ApiImplicitParam(value = "管理员", name = "head", dataType = "String"),
            @ApiImplicitParam(value = "手机号码", name = "phone", dataType = "String"),
            @ApiImplicitParam(value = "管辖城市", name = "city", dataType = "String"),
            @ApiImplicitParam(value = "页码", name = "pageNum", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "每页条数", name = "pageSize", dataType = "Integer", required = true)
    })
    public R<IPage<Franchisee>> queryPageList(String name, String head, String phone, String city,
                                              @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LambdaQueryChainWrapper<Franchisee> wrapper = franchiseeService.lambdaQuery();
        wrapper = StringUtils.isNotBlank(name) ? wrapper.like(Franchisee::getName, name) : wrapper;
        wrapper = StringUtils.isNotBlank(head) ? wrapper.like(Franchisee::getHead, head) : wrapper;
        wrapper = StringUtils.isNotBlank(phone) ? wrapper.like(Franchisee::getHeadPhone, phone) : wrapper;
        wrapper = StringUtils.isNotBlank(city) ? wrapper.like(Franchisee::getCity, city) : wrapper;
        Page<Franchisee> page = wrapper.eq(Franchisee::getIsDelete, 0)
                .orderByDesc(Franchisee::getCreateTime).page(Page.of(pageNum, pageSize));
        for (Franchisee record : page.getRecords()) {
                if (record.getSiteIds()!=null){
                    String[] split = record.getSiteIds().split(",");
                    List<Site> list = siteService.lambdaQuery().in(Site::getId, split).list();
                        //用 , 拼接
                    record.setSiteStr(list.stream().map(Site::getSiteName).collect(Collectors.joining(",")));
                }
 
 
        }
        return R.ok(page);
    }
 
    /**
     * 加盟商信息详情
     *
     * @param id 加盟商信息id
     */
    @RequiresPermissions("franchisee_detail")
    @ApiOperation(value = "加盟商信息详情", tags = {"后台-加盟商管理"})
    @GetMapping(value = "/detail")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "加盟商信息id", name = "id", dataType = "Integer", required = true)
    })
    public R<Franchisee> detail(@RequestParam("id") Integer id) {
        Franchisee one = franchiseeService.lambdaQuery()
                .eq(Franchisee::getId, id).eq(Franchisee::getIsDelete, 0).one();
        List<Site> list = siteService.lambdaQuery().in(Site::getId, one.getSiteIds().split(",")).list();
        //用 , 拼接
        one.setSiteStr(list.stream().map(Site::getSiteName).collect(Collectors.joining(",")));
 
        return R.ok(one);
    }
 
    /**
     * 加盟商管辖城市详情
     * -- 远程调用
     *
     * @param id 加盟商信息id
     */
    @ApiOperation(value = "加盟商管辖城市详情", tags = {"后台-加盟商管理"})
    @GetMapping(value = "/cityDetail")
    public R<List<String>> cityDetail(@RequestParam("id") Integer id) {
        Franchisee franchisee = franchiseeService.lambdaQuery()
                .eq(Franchisee::getId, id).eq(Franchisee::getIsDelete, 0).one();
        return R.ok(Arrays.stream(franchisee.getCityCode().split(",")).collect(Collectors.toList()));
    }
 
 
    @ApiOperation(value = "主页信息", tags = {"2.0师傅端"})
    @GetMapping(value = "/info")
    public R<InfoDto> info() {
        Long userid = tokenService.getLoginUser().getUserid();
        SysUser byId = sysUserService.getById(userid);
        Franchisee franchisee = franchiseeService.lambdaQuery()
                .eq(Franchisee::getId, byId.getFranchiseeId()).eq(Franchisee::getIsDelete, 0).one();
        String siteIds = franchisee.getSiteIds();
        String cityCode = franchisee.getCityCode();
        List<Region> list = regionService.lambdaQuery().in(Region::getCode, cityCode.split(",")).list();
        List<Site> list1 = siteService.lambdaQuery().in(Site::getId, siteIds.split(",")).list();
        InfoDto infoDto = new InfoDto();
        infoDto.setList(list);
        infoDto.setList1(list1);
        infoDto.setFranchisee(franchisee);
        return R.ok(infoDto);
    }
 
    @ApiOperation(value = "主页信息", tags = {"2.0师傅端"})
    @GetMapping(value = "/info1")
    public R<InfoDto> info1(Integer id) {
 
        Franchisee franchisee = franchiseeService.lambdaQuery()
                .eq(Franchisee::getId, id).eq(Franchisee::getIsDelete, 0).one();
        String siteIds = franchisee.getSiteIds();
        String cityCode = franchisee.getCityCode();
        List<Region> list = regionService.lambdaQuery().in(Region::getCode, cityCode.split(",")).list();
        List<Site> list1 = siteService.lambdaQuery().in(Site::getId, siteIds.split(",")).list();
        InfoDto infoDto = new InfoDto();
        infoDto.setList(list);
        infoDto.setList1(list1);
        infoDto.setFranchisee(franchisee);
        return R.ok(infoDto);
    }
 
    @ApiOperation(value = "当前余额", tags = {"后台2.0-加盟商列表余额"})
    @GetMapping(value = "/rencentBalance")
    public R<Franchisee> rencentBalance() {
        Long userid = tokenService.getLoginUser().getUserid();
        SysUser byId = sysUserService.getById(userid);
        Franchisee franchisee = franchiseeService.lambdaQuery()
                .eq(Franchisee::getId, byId.getFranchiseeId()).eq(Franchisee::getIsDelete, 0).one();
 
        return R.ok(franchisee);
    }
 
    @GetMapping(value = "/getWorkPic")
    public R<String> getWorkPic(@RequestParam("id") Integer id) {
        MasterWorker byId = masterWorkerService.getById(id);
        return R.ok(byId.getProfilePicture());
    }
 
    /**
     * 新增加盟商信息
     *
     * @param franchisee 加盟商信息信息
     */
    @RequiresPermissions("franchisee_save")
    @ApiOperation(value = "新增加盟商信息", tags = {"后台-加盟商管理"})
    @PostMapping(value = "/save")
    public R<String> save(@RequestBody @Validated Franchisee franchisee) {
        if (null == franchisee.getAdminPassword() || StringUtils.isBlank(franchisee.getAdminPassword())) {
            throw new GlobalException("请输入管理员初始密码!");
        }
        String md5Password = checkFranchisee(franchisee);
        String cityCode = franchisee.getCityCode();
        List<String> list = Arrays.stream(cityCode.split(",")).collect(Collectors.toList());
        StringBuilder str = new StringBuilder();
        for (String code : list) {
            Region region = regionService.lambdaQuery()
                    .eq(Region::getCode, code).one();
            if (null != region) {
                str.append(region.getName()).append(",");
            }
        }
        String city = str.substring(Constants.ZERO, str.length() - 1);
        franchisee.setCity(city);
        List<SysUser> list1 = sysUserService.lambdaQuery().eq(SysUser::getAccount, franchisee.getAdminAccount())
                .eq(SysUser::getIsEnable, 1).eq(SysUser::getIsDelete, 0).list();
        if(!list1.isEmpty()){
            return R.passwordError("该管理员账号已存在!");
        }
        boolean save = franchiseeService.save(franchisee);
        // 生成sysUser账号
        SysUser sysUser = new SysUser();
        sysUser.setFranchiseeId(franchisee.getId());
        sysUser.setNickName(franchisee.getName());
        sysUser.setAccount(franchisee.getAdminAccount());
        sysUser.setPassword(md5Password);
        sysUser.setIsEnable(Constants.ONE);
        sysUser.setIsDelete(Constants.ZERO);
        save = save && sysUserService.save(sysUser);
        // 添加账号与角色关联
        UserRole userRole = new UserRole();
        userRole.setUserId(sysUser.getUserId());
        userRole.setRoleId(franchisee.getRoleId().longValue());
        save = save && userRoleService.save(userRole);
        //franchisee.setCityStr(String.valueOf(franchisee.getCityArr()));
        return save ? R.ok() : R.fail();
    }
 
    /**
     * 修改加盟商信息
     *
     * @param franchisee 加盟商信息信息
     */
    @RequiresPermissions("franchisee_update")
    @ApiOperation(value = "修改加盟商信息", tags = {"后台-加盟商管理"})
    @PostMapping(value = "/update")
    public R<String> update(@RequestBody @Validated Franchisee franchisee) {
        boolean b = false;
        if (franchisee.getAdminPassword().equals("")){
            b = true;
        }
        String md5Password = checkFranchisee(franchisee);
        SysUser sysUser = sysUserService.lambdaQuery()
                .eq(SysUser::getFranchiseeId, franchisee.getId())
                .eq(SysUser::getIsDelete, Constants.ZERO).one();
        if (null == sysUser) {
            sysUser = new SysUser();
            sysUser.setNickName(franchisee.getName());
            sysUser.setAccount(franchisee.getAdminAccount());
            sysUser.setPassword(md5Password);
            sysUser.setIsEnable(franchisee.getIsEnable());
            sysUser.setIsDelete(Constants.ZERO);
            sysUserService.save(sysUser);
        } else {
            // 生成sysUser账号
            sysUser.setNickName(franchisee.getName());
            sysUser.setAccount(franchisee.getAdminAccount());
            if (!b) {
                sysUser.setPassword(md5Password);
            }
            sysUser.setIsEnable(franchisee.getIsEnable());
 
 
 
            sysUserService.updateById(sysUser);
        }
        List<String> cityStr = new ArrayList<>();
        String[] split = franchisee.getCityCode().split(",");
        for (String s : split) {
            Region one = regionService.lambdaQuery().eq(Region::getCode, s).one();
            cityStr.add(one.getName());
        }
        franchisee.setCity(String.join(",", cityStr));
 
        return franchiseeService.updateById(franchisee) ? R.ok() : R.fail();
    }
 
    /**
     * 启用/关闭加盟商
     *
     * @param id     加盟商id
     * @param enable 启用/关闭
     */
    @RequiresPermissions("franchisee_enable")
    @ApiOperation(value = "启用/关闭加盟商", tags = {"后台-加盟商管理"})
    @GetMapping(value = "/enable")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "加盟商id", name = "id", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "0:关闭;1:启用", name = "enable", dataType = "Integer", required = true)
    })
    public R<String> enable(@RequestParam Integer id, @RequestParam Integer enable) {
        boolean update = franchiseeService.lambdaUpdate().set(Franchisee::getIsEnable, enable)
                .eq(Franchisee::getId, id).update();
        // 启动/关闭后台账号
        sysUserService.lambdaUpdate()
                .eq(SysUser::getFranchiseeId, id)
                .set(SysUser::getIsEnable, enable).update();
        return update ? R.ok() : R.fail();
    }
 
    /**
     * 校验加盟商所管辖城市并加密登录密码
     *
     * @param franchisee 加盟商信息
     */
    private String checkFranchisee(Franchisee franchisee) {
        LambdaQueryChainWrapper<Franchisee> wrapper = franchiseeService.lambdaQuery()
                .eq(Franchisee::getAdminAccount, franchisee.getAdminAccount())
                .eq(Franchisee::getIsDelete, 0);
        // 校验账号是否唯一
        Franchisee only;
        if (null == franchisee.getId()) {
            only = wrapper.one();
        } else {
            only = wrapper.ne(Franchisee::getId, franchisee.getId()).one();
        }
        // 校验后台账号是否存在当前账号
        SysUser user = sysUserService.lambdaQuery()
                .eq(SysUser::getAccount, franchisee.getAdminAccount())
                .eq(SysUser::getIsDelete, Constants.ZERO)
                .eq(SysUser::getFranchiseeId, null).one();
        if (null != only || null != user) {
            throw new GlobalException("该账号已存在!", 500);
        }
//        String city = franchisee.getCity();
//        List<String> cityList = Arrays.stream(city.split(",")).collect(Collectors.toList());
//        for (String c : cityList) {
//            Franchisee one = franchiseeService.lambdaQuery().like(Franchisee::getCity, c)
//                    .eq(Franchisee::getIsDelete, 0).one();
//            if (null != one) {
//                throw new GlobalException("当前所选城市中 " + c + " 已有加盟商所管辖!");
//            }
//        }
        // MD5加密登录密码(新)
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String md5Password = passwordEncoder.encode(franchisee.getAdminPassword());
        franchisee.setAdminPassword(md5Password);
        return md5Password;
    }
 
    /**
     * 根据id批量删除加盟商信息
     *
     * @param ids 加盟商信息多条id拼接
     */
    @RequiresPermissions("franchisee_delete")
    @ApiOperation(value = "批量删除加盟商信息", tags = {"后台-加盟商管理"})
    @GetMapping(value = "/batchDelete")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "多条加盟商信息id ',' 拼接", name = "ids", dataType = "String", required = true)
    })
    public R<String> batchDelete(@RequestParam String ids) {
        List<String> idList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        List<Franchisee> list = franchiseeService.lambdaQuery().in(Franchisee::getId, idList).list();
        list.forEach(data -> data.setIsDelete(1));
        // 删除对应sysUser账号
        sysUserService.lambdaUpdate()
                .in(SysUser::getFranchiseeId, idList)
                .set(SysUser::getIsDelete, Constants.ONE).update();
        return franchiseeService.updateBatchById(list) ? R.ok() : R.fail();
    }
 
}