k94314517
2025-06-17 0e6bbda3d9f0b9e421b7bf6247be3d82d825de27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
package com.doumee.service.business.impl;
 
import com.alibaba.fastjson.JSONObject;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.model.LoginUserInfo;
import com.doumee.core.model.PageData;
import com.doumee.core.model.PageWrap;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.DateUtil;
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.*;
import com.doumee.dao.business.dto.*;
import com.doumee.dao.business.join.*;
import com.doumee.dao.business.model.*;
import com.doumee.dao.system.SystemUserMapper;
import com.doumee.dao.system.model.SystemUser;
import com.doumee.service.business.SmsEmailService;
import com.doumee.service.business.UnionApplyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doumee.service.business.third.SignService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 合并投保单信息表Service实现
 * @author 江蹄蹄
 * @date 2024/03/12 11:34
 */
@Service
public class UnionApplyServiceImpl implements UnionApplyService {
 
    @Autowired
    private UnionApplyMapper unionApplyMapper;
 
    @Autowired
    private UnionApplyJoinMapper unionApplyJoinMapper;
 
    @Autowired
    private SolutionsMapper solutionsMapper;
 
    @Autowired
    private CompanyMapper companyMapper;
 
    @Autowired
    private InsuranceApplyJoinMapper insuranceApplyJoinMapper;
 
    @Autowired
    private ApplyDetailJoinMapper applyDetailJoinMapper;
 
    @Autowired
    private MultifileMapper multifileMapper;
 
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
 
    @Autowired
    private SignService signService;
 
    @Autowired
    private SmsEmailService smsEmailService;
    @Autowired
    private ApplyLogMapper applyLogMapper;
    @Autowired
    private ApplyLogJoinMapper applyLogJoinMapper;
 
    @Autowired
    private MemberInsuranceJoinMapper memberInsuranceJoinMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private SystemUserMapper systemUserMapper;
 
    @Autowired
    private CompanyDepartmentMapper companyDepartmentMapper;
    @Value("${debug_model}")
    private boolean debugModel;
 
    @Override
    public Integer create(UnionApply unionApply) {
        unionApplyMapper.insert(unionApply);
        return unionApply.getId();
    }
 
    @Override
    public void deleteById(Integer id) {
        unionApplyMapper.deleteById(id);
    }
 
    @Override
    public void delete(UnionApply unionApply) {
        UpdateWrapper<UnionApply> deleteWrapper = new UpdateWrapper<>(unionApply);
        unionApplyMapper.delete(deleteWrapper);
    }
 
    @Override
    public void deleteByIdInBatch(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        unionApplyMapper.deleteBatchIds(ids);
    }
 
    @Override
    public void updateById(UnionApply unionApply) {
        unionApplyMapper.updateById(unionApply);
    }
 
    @Override
    public void updateByIdInBatch(List<UnionApply> unionApplys) {
        if (CollectionUtils.isEmpty(unionApplys)) {
            return;
        }
        for (UnionApply unionApply: unionApplys) {
            this.updateById(unionApply);
        }
    }
 
    @Override
    public UnionApply findById(Integer id) {
        return unionApplyMapper.selectById(id);
    }
 
    @Override
    public UnionApply findOne(UnionApply unionApply) {
        QueryWrapper<UnionApply> wrapper = new QueryWrapper<>(unionApply);
        return unionApplyMapper.selectOne(wrapper);
    }
 
    @Override
    public List<UnionApply> findList(UnionApply unionApply) {
        QueryWrapper<UnionApply> wrapper = new QueryWrapper<>(unionApply);
        return unionApplyMapper.selectList(wrapper);
    }
  
    @Override
    public PageData<UnionApply> findPage(PageWrap<UnionApply> pageWrap) {
        IPage<UnionApply> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        MPJLambdaWrapper<UnionApply> queryWrapper = new MPJLambdaWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        queryWrapper.selectAll(UnionApply.class);
        queryWrapper.selectAs(Solutions::getName,UnionApply::getSolutionName)
          .selectAs(Solutions::getMaxAge,UnionApply::getMaxAge)
                .selectAs(Solutions::getMinAge,UnionApply::getMinAge)
                .selectAs(Solutions::getPrice,UnionApply::getPrice)
                .selectAs(Solutions::getTimeUnit,UnionApply::getTimeUnit)
                .selectAs(Solutions::getOrtherInfo,UnionApply::getOrtherInfo)
                .selectAs(Solutions::getSpecialAgreement,UnionApply::getSpecialAgreement)
                .selectAs(Solutions::getSpecialInfo,UnionApply::getSpecialInfo)
                .select(" (select c.NAME from insurance_apply i left join company c on i.COMPANY_ID = c.id where i.UNION_APPLY_ID = t.id limit 1 ) ",UnionApply::getCompanyName);
        queryWrapper.select("(select count(distinct(b.MEMBER_ID)) from apply_detail b where b.isdeleted=0 and b.union_apply_id=t.id) as insureNum ");
        queryWrapper.select(" ( select count(DISTINCT(b.MEMBER_ID)) from apply_detail b inner join insurance_apply a on b.apply_id = a.id  and a.status in ( 5 , 27 )  where b.union_apply_id=t.id and b.END_TIME > now() ) as guaranteeNum");
 
        if(pageWrap.getModel().getQueryFlag() == 1){
            queryWrapper.select("(select count(1) from apply_change a inner join insurance_apply b on a.apply_id = b.id  where b.union_apply_id=t.id " +
                    "and a.status = "+Constants.ApplyChangeStatus.CHECHED_PASSED.getKey()+" and a.type = 0  ) as addApplyNum ");
 
 
        }else  if(pageWrap.getModel().getQueryFlag() ==2){
            queryWrapper.select("(select count(1) from apply_change a inner join insurance_apply b on a.apply_id = b.id  where b.union_apply_id=t.id " +
                    "and a.status = "+Constants.ApplyChangeStatus.CHECHED_PASSED.getKey()+" and a.type = 1  ) as changeApplyNum ");
        }else{
            queryWrapper.select("(select count(1) from apply_change a inner join insurance_apply b on a.apply_id = b.id  where b.union_apply_id=t.id " +
                    "and b.status = "+Constants.InsuranceApplyStatus.WTB_TOUBAOING.getKey()+" and a.type = 0  ) as addApplyNum ");
 
            queryWrapper.select("(select count(1) from apply_change a inner join insurance_apply b on a.apply_id = b.id  where b.union_apply_id=t.id " +
                    "and b.status = "+Constants.InsuranceApplyStatus.WTB_TOUBAOING.getKey()+" and a.type = 1  ) as changeApplyNum ");
        }
        queryWrapper.leftJoin(Solutions.class,Solutions::getId,UnionApply::getSolutionId); 
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(Constants.equalsInteger(user.getType(),Constants.TWO)){
            queryWrapper.eq(UnionApply::getCompanyId, user.getCompanyId());
        }
 
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.eq(UnionApply::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getSolutionId() != null) {
            queryWrapper.eq(UnionApply::getSolutionId, pageWrap.getModel().getSolutionId());
        }
        if (pageWrap.getModel().getHasApplying() != null) {
            if(Constants.equalsInteger(pageWrap.getModel().getHasApplying() ,Constants.ONE)){
                queryWrapper.exists(
                        " ( select 1  from apply_change a inner join insurance_apply b on a.apply_id = b.id  where b.union_apply_id= t.id " +
                                "        and a.status = "+Constants.ApplyChangeStatus.CHECHED_PASSED.getKey()+" and a.type = 0  ) "
                );
            }else if(Constants.equalsInteger(pageWrap.getModel().getHasApplying() ,Constants.TWO)){
                queryWrapper.exists(
                        " ( select 1  from apply_change a inner join insurance_apply b on a.apply_id = b.id  where b.union_apply_id= t.id " +
                                "        and a.status = "+Constants.ApplyChangeStatus.CHECHED_PASSED.getKey()+" and a.type = 1   ) "
                );
            }
 
        }
        if (pageWrap.getModel().getCreator() != null) {
            queryWrapper.eq(UnionApply::getCreator, pageWrap.getModel().getCreator());
        }
        if (pageWrap.getModel().getQueryStartTime() != null) {
            queryWrapper.ge(UnionApply::getCreateDate, pageWrap.getModel().getQueryStartTime() +" 00:00:00" );
        }
        if (pageWrap.getModel().getQueryEndTime() != null) {
            queryWrapper.le(UnionApply::getCreateDate, pageWrap.getModel().getQueryEndTime() +" 23:59:59");
        }
        if (pageWrap.getModel().getCreateDate() != null) {
            queryWrapper.ge(UnionApply::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.le(UnionApply::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
        }
        if (pageWrap.getModel().getEditor() != null) {
            queryWrapper.eq(UnionApply::getEditor, pageWrap.getModel().getEditor());
        }
        if (pageWrap.getModel().getEditDate() != null) {
            queryWrapper.ge(UnionApply::getEditDate, Utils.Date.getStart(pageWrap.getModel().getEditDate()));
            queryWrapper.le(UnionApply::getEditDate, Utils.Date.getEnd(pageWrap.getModel().getEditDate()));
        }
        if (pageWrap.getModel().getIsdeleted() != null) {
            queryWrapper.eq(UnionApply::getIsdeleted, pageWrap.getModel().getIsdeleted());
        }
        if (pageWrap.getModel().getRemark() != null) {
            queryWrapper.eq(UnionApply::getRemark, pageWrap.getModel().getRemark());
        }
        if (pageWrap.getModel().getSortnum() != null) {
            queryWrapper.eq(UnionApply::getSortnum, pageWrap.getModel().getSortnum());
        }
        if (pageWrap.getModel().getCompanyId() != null) {
            queryWrapper.eq(UnionApply::getCompanyId, pageWrap.getModel().getCompanyId());
        }
        if (pageWrap.getModel().getEndTime() != null) {
            queryWrapper.ge(UnionApply::getEndTime, Utils.Date.getStart(pageWrap.getModel().getEndTime()));
            queryWrapper.le(UnionApply::getEndTime, Utils.Date.getEnd(pageWrap.getModel().getEndTime()));
        }
        if (pageWrap.getModel().getStartTime() != null) {
            queryWrapper.ge(UnionApply::getStartTime, Utils.Date.getStart(pageWrap.getModel().getStartTime()));
            queryWrapper.le(UnionApply::getStartTime, Utils.Date.getEnd(pageWrap.getModel().getStartTime()));
        }
        if (pageWrap.getModel().getCheckDate() != null) {
            queryWrapper.ge(UnionApply::getCheckDate, Utils.Date.getStart(pageWrap.getModel().getCheckDate()));
            queryWrapper.le(UnionApply::getCheckDate, Utils.Date.getEnd(pageWrap.getModel().getCheckDate()));
        }
        if (pageWrap.getModel().getCheckInfo() != null) {
            queryWrapper.eq(UnionApply::getCheckInfo, pageWrap.getModel().getCheckInfo());
        }
        if (pageWrap.getModel().getCheckUserId() != null) {
            queryWrapper.eq(UnionApply::getCheckUserId, pageWrap.getModel().getCheckUserId());
        }
        if (pageWrap.getModel().getCode() != null) {
            queryWrapper.eq(UnionApply::getCode, pageWrap.getModel().getCode());
        }
        if (pageWrap.getModel().getStatus() != null) {
            queryWrapper.eq(UnionApply::getStatus, pageWrap.getModel().getStatus());
        }
        if (pageWrap.getModel().getQueryStatus() != null) {
            if(Constants.equalsInteger(pageWrap.getModel().getQueryStatus(),Constants.THREE)){
                queryWrapper.eq(UnionApply::getStatus, Constants.UnionApplyStatus.FINISH.getKey());
                queryWrapper.apply(" t.START_TIME < now()  and t.END_TIME > now() ");
            }else if(Constants.equalsInteger(pageWrap.getModel().getQueryStatus(),Constants.SIX)){
                queryWrapper.eq(UnionApply::getStatus, Constants.UnionApplyStatus.FINISH.getKey());
                queryWrapper.apply("   t.END_TIME < now() ");
            }else if(Constants.equalsInteger(pageWrap.getModel().getQueryStatus(),Constants.FIVE)){
                queryWrapper.eq(UnionApply::getStatus, Constants.UnionApplyStatus.FINISH.getKey());
                queryWrapper.apply("   t.START_TIME > now() ");
            }else if(Constants.equalsInteger(pageWrap.getModel().getQueryStatus(),Constants.ZERO)){
                queryWrapper.in(UnionApply::getStatus, Constants.UnionApplyStatus.MERGE.getKey(),Constants.UnionApplyStatus.RETRIAL.getKey());
            }else{
                queryWrapper.eq(UnionApply::getStatus, pageWrap.getModel().getQueryStatus());
            }
 
        }
        
        if (pageWrap.getModel().getCurrentFee() != null) {
            queryWrapper.eq(UnionApply::getCurrentFee, pageWrap.getModel().getCurrentFee());
        }
        if (pageWrap.getModel().getFee() != null) {
            queryWrapper.eq(UnionApply::getFee, pageWrap.getModel().getFee());
        }
        if (pageWrap.getModel().getSignApplyNo() != null) {
            queryWrapper.eq(UnionApply::getSignApplyNo, pageWrap.getModel().getSignApplyNo());
        }
        if(pageWrap.getSorts().size() == 0){
            queryWrapper.orderByDesc(UnionApply::getCreateDate );
        }else {
            for(PageWrap.SortData sortData: pageWrap.getSorts()) {
                if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
                    queryWrapper.orderByDesc(sortData.getProperty());
                } else {
                    queryWrapper.orderByAsc(sortData.getProperty());
                }
            }
        }
 
        PageData<UnionApply> pageData = PageData.from(unionApplyJoinMapper.selectJoinPage(page,UnionApply.class, queryWrapper));
        if(pageData!=null && pageData.getRecords()!=null){
            for(UnionApply model : pageData.getRecords()){
                initStatusInfo(model);
            }
        }
        return pageData;
    }
 
    private void initStatusInfo(UnionApply model) {
        model.setStatusInfo(Constants.UnionApplyStatus.getName(Constants.formatIntegerNum(model.getStatus())));
 
        if(Constants.equalsInteger(model.getStatus(),Constants.UnionApplyStatus.FINISH.getKey())){
            if(model.getStartTime().getTime()>System.currentTimeMillis()){
                model.setStatusInfo("待生效");
            }else if(model.getEndTime().getTime()<System.currentTimeMillis()){
                model.setStatusInfo("已过期");
            }else{
                model.setStatusInfo("保障中");
            }
        }
 
    }
 
    @Override
    public long count(UnionApply unionApply) {
        QueryWrapper<UnionApply> wrapper = new QueryWrapper<>(unionApply);
        return unionApplyMapper.selectCount(wrapper);
    }
 
    @Override
    public      UnionApply findDetailForExport(UnionApply model){
        UnionApply insuranceApply = detail(model.getId());
        if(Objects.isNull(insuranceApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
 
        MPJLambdaWrapper<ApplyDetail> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(ApplyDetail.class);
        queryWrapper.selectAs(DispatchUnit::getName,ApplyDetail::getDuName);
        queryWrapper.selectAs(Company::getName,ApplyDetail::getCompanyName);
        queryWrapper.selectAs(Worktype::getName,ApplyDetail::getWorkTypeName);
        queryWrapper.selectAs(Member::getIdcardNo,ApplyDetail::getIdcardNo);
        queryWrapper.selectAs(Member::getName,ApplyDetail::getMemberName);
        queryWrapper.leftJoin(DispatchUnit.class,DispatchUnit::getId,ApplyDetail::getDuId);
        queryWrapper.leftJoin(Worktype.class,Worktype::getId,ApplyDetail::getWorktypeId);
        queryWrapper.leftJoin(Member.class,Member::getId,ApplyDetail::getMemberId);
        queryWrapper.leftJoin(Company.class,Company::getId,Member::getCompanyId);
        queryWrapper.eq(  ApplyDetail::getUnionApplyId,model.getId());
        List<ApplyDetail> detailList=  applyDetailJoinMapper.selectJoinList( ApplyDetail.class, queryWrapper);
        //查询明细
        if(detailList!=null){
            insuranceApply.setInsureNum(detailList.size());
            insuranceApply.setApplyDetailList(detailList);
        }
        insuranceApply.setRemark(model.getRemark());
        return insuranceApply;
    }
 
 
 
    @Override
    public UnionApply detail(Integer applyId){
        UnionApply unionApply = unionApplyJoinMapper.selectJoinOne(UnionApply.class,
                new MPJLambdaWrapper<UnionApply>()
                        .selectAll(UnionApply.class)
                        .selectAs(Solutions::getName,UnionApply::getSolutionName)
                        .selectAs(Solutions::getDelOnlyReplace,UnionApply::getDelOnlyReplace)
                        .selectAs(Solutions::getHasDispatchUnit,UnionApply::getHasDispatchUnit)
                        .selectAs(Solutions::getSignType,UnionApply::getSignType)
                        .selectAs(Company::getName,UnionApply::getCompanyName)
                        .select(" ( select count(DISTINCT(ad.MEMBER_ID)) from apply_detail ad  where ad.UNION_APPLY_ID = t.id ) as insureNum")
                .select(" ( select count(DISTINCT(b.MEMBER_ID)) from apply_detail b inner join insurance_apply a on b.apply_id = a.id  and a.status in ( 5 , 27 )  where b.union_apply_id=t.id and b.END_TIME > now() ) as guaranteeNum")
                        .select(" ( select group_concat(DISTINCT(cd.name)) from insurance_apply ad left join company cd on ad.company_id = cd.id where ad.UNION_APPLY_ID = t.id ) as companyNames")
                        .leftJoin(Solutions.class,Solutions::getId,UnionApply::getSolutionId)
                        .leftJoin(Company.class,Company::getId,UnionApply::getCompanyId)
                        .eq(UnionApply::getId,applyId)
                        .last(" limit 1 ")
        );
        unionApply.setServiceDays(Constants.ZERO);
        if(unionApply.getStatus().equals(Constants.UnionApplyStatus.FINISH.getKey())){
            //如果当前时间大于结束日期 则使用结束日期对比开始日期
            if(DateUtil.compareDate(new Date(),unionApply.getEndTime())>=Constants.ZERO){
                unionApply.setServiceDays(
                        DateUtil.daysBetweenDates(unionApply.getEndTime(),unionApply.getStartTime())+1
                );
            }else if(DateUtil.compareDate(unionApply.getStartTime(),new Date())>=Constants.ZERO){
                //未开始
                unionApply.setServiceDays(Constants.ZERO);
            }else{
                unionApply.setServiceDays(DateUtil.daysBetweenDates(new Date(),unionApply.getStartTime())+1);
            }
        }
        initStatusInfo(unionApply);
 
        //查询附件数据
        initImgData(unionApply);
        //查询操作记录
        List<ApplyLog> applyLogList = applyLogJoinMapper.selectJoinList(ApplyLog.class,
                new MPJLambdaWrapper<ApplyLog>()
                        .selectAll(ApplyLog.class)
                        .selectAs(SystemUser::getRealname,ApplyLog::getCreatorName)
                        .selectAs(Company::getName,ApplyLog::getCompanyName)
                        .selectAs(SystemUser::getType,ApplyLog::getCreatorType)
                        .leftJoin(SystemUser.class,SystemUser::getId,ApplyLog::getCreator)
                        .leftJoin(Company.class,Company::getId,SystemUser::getCompanyId)
                        .in(ApplyLog::getObjType,Constants.ApplyLogType.getTypeList(Constants.THREE))
                        .eq(ApplyLog::getApplyId,unionApply.getId())
                        .orderByAsc(ApplyLog::getCreateDate)
        );
        unionApply.setApplyLogList(applyLogList);
 
        return unionApply;
    }
 
    private void initImgData(UnionApply model) {
        List<Multifile> multifiles = multifileMapper.selectList(new QueryWrapper<Multifile>().lambda()
                .eq(Multifile::getObjId, model.getId())
                .in(Multifile::getObjType, Arrays.asList(new Integer[]{
                        Constants.MultiFile.HBD_BD_APPLY_PDF.getKey()
                        ,Constants.MultiFile.HBD_BD_SIGNED_PDF.getKey()
                        ,Constants.MultiFile.WTB_BD_DONE_PDF.getKey() }))
                .eq(Multifile::getIsdeleted,Constants.ZERO)
                .orderByAsc(Multifile::getId));
        if(multifiles!=null){
            String path = systemDictDataBiz.queryByCode(Constants.OSS,Constants.RESOURCE_PATH).getCode()
                    +systemDictDataBiz.queryByCode(Constants.OSS,Constants.APPLY_FILE).getCode();
            for(Multifile f : multifiles){
                if(StringUtils.isBlank(f.getFileurl())){
                    continue;
                }
                f.setFileurlFull(path+f.getFileurl());
                if(Constants.equalsInteger(f.getObjType(),Constants.MultiFile.HBD_BD_APPLY_PDF.getKey())){
                    //签署前的投保单
                    model.setToubaodanFile(f);
                }else if(Constants.equalsInteger(f.getObjType(),Constants.MultiFile.HBD_BD_SIGNED_PDF.getKey())){
                    //签署后的投保单
                    model.setToubaodanSignedFile(f);
                }else if(Constants.equalsInteger(f.getObjType(),Constants.MultiFile.WTB_BD_DONE_PDF.getKey())){
                    //最終保险单
                    model.setBaoxiandanFile(f);
                }
            }
        }
    }
 
 
    @Override
    @Transactional(rollbackFor ={BusinessException.class,Exception.class} )
    public Integer merge(SaveUnionApplyDTO saveUnionApplyDTO){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(Objects.isNull(saveUnionApplyDTO)
            || Objects.isNull(saveUnionApplyDTO.getApplyIds())
            || saveUnionApplyDTO.getApplyIds().size() == 0
            || Objects.isNull(saveUnionApplyDTO.getStartDate())
            || Objects.isNull(saveUnionApplyDTO.getEndDate())
            || saveUnionApplyDTO.getStartDate().getTime()>saveUnionApplyDTO.getEndDate().getTime()
            || Objects.isNull(saveUnionApplyDTO.getBaseSolutionId())
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        Solutions solutions = solutionsMapper.selectOne(new QueryWrapper<Solutions>().lambda().
                eq(Solutions::getType,Constants.ONE)
                .eq(Solutions::getIsdeleted,Constants.ZERO)
                .eq(Solutions::getDataType,Constants.ZERO)
                .eq(Solutions::getId,saveUnionApplyDTO.getBaseSolutionId()));
        //查询方案数据
        if(solutions == null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,方案信息有误,请刷新页面重试");
        }
        //根据方案查询对应的结束日期
        CountCyclePriceDTO countCyclePriceDTO = new CountCyclePriceDTO();
        countCyclePriceDTO.setSolutions(solutions);
        countCyclePriceDTO.setStartDate(saveUnionApplyDTO.getStartDate());
        Date endTime =  Constants.getCountCyclePriceVO(countCyclePriceDTO).getEndDate();
        if(saveUnionApplyDTO.getEndDate().getTime()>endTime.getTime()) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,结束日期超出方案可允许日期周期,请更改后重试!");
        }
        List<InsuranceApply> insuranceApplyList = insuranceApplyJoinMapper.selectJoinList(InsuranceApply.class,
                new MPJLambdaWrapper<InsuranceApply>()
                        .selectAll(InsuranceApply.class)
                        .selectAs(Solutions::getBaseId,InsuranceApply::getSolutionBaseId)
                        .leftJoin(Solutions.class,Solutions::getId,InsuranceApply::getSolutionId)
                        .eq(InsuranceApply::getIsdeleted, Constants.ZERO)
                        .eq(InsuranceApply::getStatus,Constants.InsuranceApplyStatus.WTB_BUSINESS_CHECK_PASS.getKey())
                        .eq(Solutions::getBaseId,saveUnionApplyDTO.getBaseSolutionId())
                        .in(InsuranceApply::getId,saveUnionApplyDTO.getApplyIds())
                        .isNull(InsuranceApply::getUnionApplyId)
        );
        //查询数据是否存在未处于审批通过的数据
        if(insuranceApplyList.size()!=saveUnionApplyDTO.getApplyIds().size()){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"存在数据已处理,请刷新重试");
        }
        saveUnionApplyDTO.setEndDate(DateUtil.getMontageDate(saveUnionApplyDTO.getEndDate(),2));
        UnionApply unionApply = new UnionApply();
        unionApply.setCreateDate(new Date());
        unionApply.setCreator(user.getId());
        unionApply.setEditor(user.getId());
        unionApply.setEditDate(new Date());
        if(Constants.equalsInteger(user.getType(),Constants.ZERO)){
            unionApply.setCompanyId(solutions.getShopId());
        }else{
            unionApply.setCompanyId(user.getCompanyId());
        }
        unionApply.setStartTime(saveUnionApplyDTO.getStartDate());
        unionApply.setEndTime(saveUnionApplyDTO.getEndDate());
        unionApply.setCheckDate(new Date());
 
        if(Constants.equalsInteger(solutions.getRetrial(),Constants.ONE)){
                SystemUser systemUser = systemUserMapper.selectById(user.getId());
                if(Objects.nonNull(systemUser) && Objects.nonNull(systemUser.getDepartmentId())){
                    CompanyDepartment companyDepartment = companyDepartmentMapper.selectById(systemUser.getDepartmentId());
                    if(Objects.nonNull(companyDepartment)&&Objects.nonNull(companyDepartment.getHeadId())){
                        unionApply.setRetrialId(companyDepartment.getHeadId());
                    }
                }
        }
        if(Constants.equalsInteger(solutions.getSignType(), Constants.ZERO)){
            unionApply.setStatus(Constants.UnionApplyStatus.MERGE.getKey());
        }else if(Constants.equalsInteger(solutions.getSignType(), Constants.ONE)){
            unionApply.setStatus(Constants.UnionApplyStatus.WAIT_SIGNATURE.getKey());
        }else{
            if(Objects.nonNull(unionApply.getRetrialId())){
                unionApply.setStatus(Constants.UnionApplyStatus.RETRIAL.getKey());
            }else{
                unionApply.setStatus(Constants.UnionApplyStatus.UPLOAD_INSURANCE_POLICY.getKey());
            }
        }
        unionApply.setCheckUserId(user.getId());
        unionApply.setCurrentFee(BigDecimal.ZERO);
        unionApply.setIsdeleted(Constants.ZERO);
        unionApply.setSolutionId(solutions.getId());
 
        List<ApplyDetail> applyDetailList = applyDetailJoinMapper.selectJoinList(ApplyDetail.class,new MPJLambdaWrapper<ApplyDetail>()
                .select(ApplyDetail::getId,ApplyDetail::getPrice,ApplyDetail::getStartTime,ApplyDetail::getEndTime,ApplyDetail::getFee)
                .selectAs(Member::getIdcardNo,ApplyDetail::getIdcardNo)
                .selectAs(Member::getName,ApplyDetail::getMemberName)
                .leftJoin(Member.class,Member::getId,ApplyDetail::getMemberId)
                .in(ApplyDetail::getApplyId,saveUnionApplyDTO.getApplyIds())
                .eq(ApplyDetail::getIsdeleted,Constants.ZERO));
        if(applyDetailList.size()==0){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,存在委托投保申请记录信息有误,请返回查看申请人员是否为空!");
        }
        BigDecimal fee = BigDecimal.ZERO;
        for (ApplyDetail applyDetail:applyDetailList) {
            //查询人员信息是否存在相同的方案下是否存在 冲突数据
            InsuranceApplyServiceImpl.checkStaticMemberSolution(solutions.getBaseId(),
                    applyDetail.getMemberId(),applyDetail.getIdcardNo(),applyDetail.getMemberName(),unionApply.getStartTime(),unionApply.getEndTime(),
                    applyDetailJoinMapper);
            fee =fee.add(
                    Constants.reduceFee(solutions,solutions.getPrice(),applyDetail.getStartTime(),applyDetail.getEndTime(),saveUnionApplyDTO.getStartDate(),saveUnionApplyDTO.getEndDate())
            );
        }
        unionApply.setFee(fee);
        unionApplyMapper.insert(unionApply);
        if(Constants.equalsInteger(unionApply.getStatus(),Constants.UnionApplyStatus.WAIT_SIGNATURE.getKey())){
            //查询企业签章的文件
            Integer applyId = insuranceApplyList.get(Constants.ZERO).getId();
            Multifile m = multifileMapper.selectOne(new QueryWrapper<Multifile>().lambda().eq(Multifile::getObjId,applyId)
                    .eq(Multifile::getObjType,Constants.MultiFile.MEMBER_LIST_LATTER.getKey())
                    .last(" limit  1 ")
            );
            if(Objects.isNull(m)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"未查询到保单企业签署文件");
            }
            Multifile multifile = new Multifile();
            multifile.setCreateDate(new Date());
            multifile.setIsdeleted(Constants.ZERO);
            multifile.setObjId(unionApply.getId());
            multifile.setObjType(Constants.MultiFile.HBD_BD_APPLY_PDF.getKey());
            multifile.setFileurl(m.getFileurl());
            multifileMapper.insert(multifile);
        }
        insuranceApplyJoinMapper.update(null,new UpdateWrapper<InsuranceApply>().lambda()
                .set(InsuranceApply::getUnionApplyId,unionApply.getId())
                .set(InsuranceApply::getCheckDate,new Date())
                .set(InsuranceApply::getCheckUserId,user.getId())
                .set(InsuranceApply::getStatus,Constants.InsuranceApplyStatus.WTB_TOUBAOING.getKey())
                .in(InsuranceApply::getId,saveUnionApplyDTO.getApplyIds()));
        applyDetailJoinMapper.update(null,new UpdateWrapper<ApplyDetail>().lambda()
                .set(ApplyDetail::getUnionApplyId,unionApply.getId())
                .in(ApplyDetail::getApplyId,saveUnionApplyDTO.getApplyIds()));
 
 
 
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.IA_HBD_UPLOAD;
        ApplyLog log = new ApplyLog(unionApply,applyLogType.getName(), null
                ,unionApply.getId(),applyLogType.getKey(),null, JSONObject.toJSONString(unionApply));
        applyLogMapper.insert(log);
 
        return unionApply.getId();
    }
 
 
 
    @Override
    @Transactional(rollbackFor ={BusinessException.class,Exception.class} )
    public Integer reexamineCheck(UnionApply unionApply){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        UnionApply model = unionApplyMapper.selectById(unionApply.getId());
        if(Objects.isNull(unionApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!Constants.equalsInteger(model.getStatus(),Constants.UnionApplyStatus.RETRIAL.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已流转,您无法进行该操作!");
        }
        unionApply.setEditor(user.getId());
        unionApply.setEditDate(new Date());
        //如果是商户端,则只能由指定人进行处理
        if(Constants.equalsInteger(user.getType(),Constants.TWO)){
            if(!Constants.equalsInteger(model.getRetrialId(),user.getId())){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非您的复审数据,无法进行审批");
            }
        }else{
            //如果是平台端,根据人员类型处理 如果是固定人员则不限制 其他人员需要比对
            if(!user.getFixed()){
                if(!Constants.equalsInteger(model.getRetrialId(),user.getId())){
                    throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非您的复审数据,无法进行审批");
                }
            }
        }
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.IA_HBD_REEXAMINE_PASS;
        String info = applyLogType.getInfo();
        unionApply.setStatus(Constants.UnionApplyStatus.UPLOAD_INSURANCE_POLICY.getKey());
        unionApplyMapper.updateById(unionApply);
        ApplyLog log = new ApplyLog(unionApply,applyLogType.getName(), info
                ,unionApply.getId(),applyLogType.getKey(),null, null);
        applyLogMapper.insert(log);
        return unionApply.getId();
 
 
    }
 
 
 
 
    /**
     * 取消保单合并
     * @param closeDTO
     */
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public void cancelMerge(CloseDTO closeDTO){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!(Constants.equalsInteger(user.getType(),Constants.ZERO)||Constants.equalsInteger(user.getType(),Constants.TWO))){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"企业用户,无法进行该操作!");
        }
        if(Objects.isNull(closeDTO)
                ||Objects.isNull(closeDTO.getId())
                ||StringUtils.isBlank(closeDTO.getReason())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        UnionApply unionApply = unionApplyMapper.selectById(closeDTO.getId());
        if(Objects.isNull(unionApply)||!Constants.equalsInteger(unionApply.getIsdeleted(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(Constants.equalsInteger(user.getType(),Constants.TWO)&&!unionApply.getCompanyId().equals(user.getCompanyId())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起非您的合并单,您无法进行操作!");
        }
        if(unionApply.getStatus().equals(Constants.UnionApplyStatus.FINISH.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已完结,您无法进行该操作!");
        }
        if(unionApply.getStatus().equals(Constants.UnionApplyStatus.CLOSE.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已关闭");
        }
 
 
        //合并单状态处于待投保
        if(unionApply.getStatus().equals(Constants.UnionApplyStatus.UPLOAD_INSURANCE_POLICY.getKey())
        || unionApply.getStatus().equals(Constants.UnionApplyStatus.WAIT_SIGNATURE.getKey())){
            multifileMapper.delete(new QueryWrapper<Multifile>()
                    .lambda()
                    .apply(" multifile.id in ( select i.id  from insurance_apply i where i.UNION_APPLY_ID = "+unionApply.getId()+" ) ")
                    .eq(Multifile::getObjType,Constants.MultiFile.BD_APPLY_PDF.getKey()));
        }
        insuranceApplyJoinMapper.update(null,new UpdateWrapper<InsuranceApply>().lambda()
                .set(InsuranceApply::getUnionApplyId,null)
                .set(InsuranceApply::getCheckDate,new Date())
                .set(unionApply.getStatus().equals(Constants.UnionApplyStatus.UPLOAD_INSURANCE_POLICY.getKey())
                        || unionApply.getStatus().equals(Constants.UnionApplyStatus.WAIT_SIGNATURE.getKey()),
                        InsuranceApply::getUnionApplyTbdStatus,Constants.ZERO)
                .set(unionApply.getStatus().equals(Constants.UnionApplyStatus.UPLOAD_INSURANCE_POLICY.getKey())
                        || unionApply.getStatus().equals(Constants.UnionApplyStatus.WAIT_SIGNATURE.getKey()),
                        InsuranceApply::getApplyTbdNo,null)
                .set(InsuranceApply::getCheckUserId,user.getId())
                .set(InsuranceApply::getStatus,Constants.InsuranceApplyStatus.WTB_RETURN.getKey())
                .eq(InsuranceApply::getUnionApplyId,unionApply.getId())
        );
 
        applyDetailJoinMapper.update(null,new UpdateWrapper<ApplyDetail>().lambda()
                .set(ApplyDetail::getUnionApplyId,null)
                .eq(ApplyDetail::getUnionApplyId,unionApply.getId()));
 
        unionApplyMapper.update(null,new UpdateWrapper<UnionApply>().lambda()
                .set(UnionApply::getCheckDate,new Date())
                .set(UnionApply::getCheckUserId,user.getId())
                .set(UnionApply::getStatus,Constants.UnionApplyStatus.CLOSE.getKey())
                .eq(UnionApply::getId,unionApply.getId())
        );
 
 
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.IA_HBD_CLOSE;
        String info =applyLogType.getInfo();
        info = info.replace("${param}", closeDTO.getReason());
        ApplyLog log = new ApplyLog(unionApply,applyLogType.getName(), info
                ,unionApply.getId(),applyLogType.getKey(),null, null);
        applyLogMapper.insert(log);
    }
 
 
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public void uploadToubaodan(UploadMultifileDTO uploadMultifileDTO){
        if(uploadMultifileDTO.getBusinessId() == null
                ||StringUtils.isBlank( uploadMultifileDTO.getFileurl())
                ||StringUtils.isBlank( uploadMultifileDTO.getName())){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
//        if(!user.getType().equals(Constants.TWO)){
//            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非商户用户,无法进行该操作!");
//        }
        UnionApply unionApply = unionApplyMapper.selectById(uploadMultifileDTO.getBusinessId());
        if(Objects.isNull(unionApply)||!Constants.equalsInteger(unionApply.getIsdeleted(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        unionApply.setStatus(Constants.formatIntegerNum(unionApply.getStatus()));
        if(Constants.equalsInteger(user.getType(),Constants.TWO)){
            if(!unionApply.getCompanyId().equals(user.getCompanyId())){
                throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起非您的合并单,您无法进行操作!");
            }
        }
 
        if(unionApply.getStatus().equals(Constants.UnionApplyStatus.FINISH.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已完结,您无法进行该操作!");
        }
        if(!unionApply.getStatus().equals(Constants.UnionApplyStatus.MERGE.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已流转,您无法进行该操作!");
        }
 
        unionApply.setCheckDate(new Date());
        unionApply.setCheckUserId(user.getId());
        unionApply.setStatus(Constants.UnionApplyStatus.WAIT_SIGNATURE.getKey());
        unionApply.setEditor(user.getId());
        unionApply.setEditDate(new Date());
        unionApplyMapper.updateById(unionApply);
 
        Multifile multifile = new Multifile();
        multifile.setIsdeleted(Constants.ZERO);
        multifile.setCreator(user.getId());
        multifile.setCreateDate(new Date());
        multifile.setObjId(uploadMultifileDTO.getBusinessId());
        multifile.setCreateDate(new Date());
        multifile.setObjType(Constants.MultiFile.HBD_BD_APPLY_PDF.getKey());
        multifile.setType(Constants.TWO);
        multifile.setFileurl(uploadMultifileDTO.getFileurl());
        multifile.setName(uploadMultifileDTO.getName());
        multifileMapper.insert(multifile);
 
 
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.IA_HBD_UPLOAD_TBD;
        ApplyLog log = new ApplyLog(unionApply,applyLogType.getName(), null
                ,unionApply.getId(),applyLogType.getKey(),null, JSONObject.toJSONString(unionApply));
        applyLogMapper.insert(log);
 
    }
 
 
    /**
     * 合并单 - 投保申请签署
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public  String getSignLink(SmsCheckDTO smsCheckDTO) {
        if(Objects.isNull(smsCheckDTO)
                || Objects.isNull(smsCheckDTO.getBusinessId())
//                || StringUtils.isBlank(smsCheckDTO.getCode())
        ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        //验证 验证码
//        if(!debugModel){
//            smsEmailService.validateCode(smsCheckDTO.getCode());
//        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        UnionApply unionApply = unionApplyJoinMapper.selectById(smsCheckDTO.getBusinessId());
        if(unionApply == null ||!Constants.equalsInteger(unionApply.getIsdeleted(),Constants.ZERO)){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        Solutions solutions = solutionsMapper.selectById(unionApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询方案信息");
        }
 
        if(!Constants.equalsInteger(unionApply.getStatus(),Constants.UnionApplyStatus.WAIT_SIGNATURE.getKey())){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,该合并单状态已流转,当前不支持该操作~");
        }
        Multifile f = multifileMapper.selectOne(new QueryWrapper<Multifile>().lambda()
                .eq(Multifile::getObjId,unionApply.getId())
                .eq(Multifile::getObjType,Constants.MultiFile.HBD_BD_APPLY_PDF.getKey())
                .eq(Multifile::getIsdeleted,Constants.ZERO)
                .last("limit 1"));
        if(f == null || StringUtils.isBlank(f.getFileurl())){
            throw  new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"对不起,获取待签章文件失败,请联系确认合并保单是否正确!");
        }
 
        Company company =  companyMapper.selectById(unionApply.getCompanyId());
        if(company== null || StringUtils.isBlank( company.getEmail()) || !Constants.equalsInteger(company.getSignStatus(),Constants.THREE)){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,商户尚未具备在线签章条件,请联系平台管理员确认~");
        }
 
        String url = systemDictDataBiz.queryByCode(Constants.OSS,Constants.RESOURCE_PATH).getCode()+systemDictDataBiz.queryByCode(Constants.OSS,Constants.APPLY_FILE).getCode()+f.getFileurl();
        String notifyUrl = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.SIGN_DONE_NOTIFY_URL).getCode();
        notifyUrl = notifyUrl.replace("${type}","0").replace("${id}", unionApply.getId().toString());
 
        String applyNo = signService.applySignDoByParam(company.getName(),url,company.getName(),company.getCode(),company.getEmail(),null,company.getSignId(),notifyUrl,new Float(0.7));
 
        if(StringUtils.isBlank(applyNo) ){
            throw  new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"对不起,获取在线签章地址失败,请稍后重试!");
        }
        String link = signService.signLink(applyNo,company.getName(),company.getCode());
        if(StringUtils.isBlank(link) ){
            throw  new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"对不起,获取在线签章地址失败,请稍后重试!");
        }
        UnionApply update= new UnionApply();
        update.setId(unionApply.getId());
        update.setEditor(user.getId());
        update.setEditDate(new Date());
        update.setSignApplyNo(applyNo);
        unionApplyJoinMapper.updateById(update);
        return  link;
    }
 
 
 
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public void uploadBXD(UnionApplyBXDDTO unionApplyBXDDTO){
        if(Objects.isNull(unionApplyBXDDTO)
            || Objects.isNull(unionApplyBXDDTO.getId())
            || Objects.isNull(unionApplyBXDDTO.getStartTime())
            || Objects.isNull(unionApplyBXDDTO.getEndTime())
            || StringUtils.isBlank(unionApplyBXDDTO.getCode())
            || StringUtils.isBlank(unionApplyBXDDTO.getFileUrl())
            || StringUtils.isBlank(unionApplyBXDDTO.getFileName())
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
 
        UnionApply unionApply = unionApplyJoinMapper.selectById(unionApplyBXDDTO.getId());
        if(unionApply == null ||!Constants.equalsInteger(unionApply.getIsdeleted(),Constants.ZERO)){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!unionApply.getStatus().equals(Constants.UnionApplyStatus.UPLOAD_INSURANCE_POLICY.getKey())){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,该合并单状态已流转,当前不支持该操作~");
        }
        Solutions solutions = solutionsMapper.selectById(unionApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"未查询到方案信息");
        }
        //根据方案查询对应的结束日期
        CountCyclePriceDTO countCyclePriceDTO = new CountCyclePriceDTO();
        countCyclePriceDTO.setSolutions(solutions);
        countCyclePriceDTO.setStartDate(unionApplyBXDDTO.getStartTime());
        Date endTime =  Constants.getCountCyclePriceVO(countCyclePriceDTO).getEndDate();
        if(unionApplyBXDDTO.getEndTime().getTime()>endTime.getTime()) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,结束日期超出方案可允许日期周期,请更改后重试!");
        }
        //加价参数
        List<UnionApplyBXDDetailDTO> unionApplyBXDDetailDTOList = unionApplyBXDDTO.getUnionApplyBXDDDetailDTOList();
 
        //所有投保申请保单明细行
        List<ApplyDetail> applyDetailList = applyDetailJoinMapper.selectJoinList(ApplyDetail.class,new MPJLambdaWrapper<ApplyDetail>()
                        .selectAll(ApplyDetail.class)
                .selectAs(DispatchUnit::getName,ApplyDetail::getDuName)
                .selectAs(InsuranceApply::getCode,ApplyDetail::getApplyCode)
                .selectAs(Solutions::getId,ApplyDetail::getSolutionId)
                .selectAs(Solutions::getName,ApplyDetail::getSolutionName)
                .selectAs(Worktype::getName,ApplyDetail::getWorkTypeName)
                .selectAs(Member::getIdcardNo,ApplyDetail::getIdcardNo)
                .selectAs(Member::getName,ApplyDetail::getMemberName)
                .leftJoin(DispatchUnit.class,DispatchUnit::getId,ApplyDetail::getDuId)
                .leftJoin(Worktype.class,Worktype::getId,ApplyDetail::getWorktypeId)
                .leftJoin(Member.class,Member::getId,ApplyDetail::getMemberId)
                .leftJoin(InsuranceApply.class,InsuranceApply::getId,ApplyDetail::getApplyId)
                .leftJoin(Solutions.class,Solutions::getId,InsuranceApply::getSolutionId)
                .in(ApplyDetail::getUnionApplyId,unionApply.getId()));  
        unionApplyBXDDTO.setEndTime(DateUtil.getMontageDate(unionApplyBXDDTO.getEndTime(),2));
        //总天数
        Integer maxDays = DateUtil.calculateBetween(unionApplyBXDDTO.getStartTime(),unionApplyBXDDTO.getEndTime(),0);
        //实际已经产生费用的天数
        Integer useDays = 0 ;
        if(unionApplyBXDDTO.getStartTime().compareTo(new Date()) <= 0 && unionApplyBXDDTO.getEndTime().compareTo(new Date()) >= 0 ){
            //当前日期在开始结束日期之内
            useDays =  DateUtil.calculateBetween(unionApplyBXDDTO.getStartTime(),new Date(),0);
        }else if(unionApplyBXDDTO.getStartTime().compareTo(new Date()) <= 0&&unionApplyBXDDTO.getEndTime().compareTo(new Date()) <= 0){
            //当前日期在结束日期之后
            useDays =  -1;
        }
        BigDecimal sumFee = BigDecimal.ZERO;
        BigDecimal sumCurrFee = BigDecimal.ZERO;
        List<InsuranceApply> insuranceApplyList = insuranceApplyJoinMapper.selectList(new QueryWrapper<InsuranceApply>()
                .lambda().eq(InsuranceApply::getUnionApplyId,unionApply.getId()));
        for (InsuranceApply insuranceApply:insuranceApplyList) {
            List<ApplyDetail> applyDetails = applyDetailList.stream()
                    .filter(m->Constants.equalsInteger(m.getApplyId(),(insuranceApply.getId()))).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(applyDetails)){
                continue;
            }
            BigDecimal price = Constants.formatBigdecimal(applyDetails.get(Constants.ZERO).getPrice());
            Optional<UnionApplyBXDDetailDTO> unionApplyBXDDDetailTO= unionApplyBXDDetailDTOList.stream().filter(
                    m->m.getApplyId().equals(insuranceApply.getId())).findFirst();
            BigDecimal serverCost = BigDecimal.ZERO;
            if(unionApplyBXDDDetailTO.isPresent()){
                UnionApplyBXDDetailDTO unionApplyBXDDetailDTO = unionApplyBXDDDetailTO.get();
                serverCost = unionApplyBXDDetailDTO.getServerMoney();
                //上传保单信息
                Multifile multifile = new Multifile();
                multifile.setIsdeleted(Constants.ZERO);
                multifile.setCreator(user.getId());
                multifile.setCreateDate(new Date());
                multifile.setObjId(insuranceApply.getId());
                multifile.setObjType(Constants.MultiFile.BD_DONE_PDF.getKey());
                multifile.setType(Constants.TWO);
                multifile.setFileurl(unionApplyBXDDTO.getFileUrl());
                multifile.setName(unionApplyBXDDTO.getFileName());
                multifileMapper.insert(multifile);
                insuranceApply.setUnionApplyTbdStatus(Constants.ONE);
 
 
//                if(StringUtils.isNotBlank(unionApplyBXDDetailDTO.getFileUrl())){
//                    Multifile multifile = new Multifile();
//                    multifile.setIsdeleted(Constants.ZERO);
//                    multifile.setCreator(user.getId());
//                    multifile.setCreateDate(new Date());
//                    multifile.setObjId(insuranceApply.getId());
//                    multifile.setObjType(Constants.MultiFile.BD_DONE_PDF.getKey());
//                    multifile.setType(Constants.TWO);
//                    multifile.setFileurl(unionApplyBXDDetailDTO.getFileUrl());
//                    multifile.setName(unionApplyBXDDetailDTO.getFileName());
//                    multifileMapper.insert(multifile);
//                    insuranceApply.setUnionApplyTbdStatus(Constants.ONE);
//                }else{
//                    insuranceApply.setUnionApplyTbdStatus(Constants.ZERO);
//                }
            }
            //实际已产生费用(单人)
            BigDecimal currentFee = BigDecimal.ZERO;
            if(useDays==-1){
                currentFee = solutions.getPrice().add(serverCost);
            }else if(useDays>0){
                currentFee = Constants.produceFee(solutions,solutions.getPrice().add(serverCost)
                        ,unionApplyBXDDTO.getStartTime(),unionApplyBXDDTO.getEndTime(),
                        unionApplyBXDDTO.getStartTime()
                );
            }
            //生成投保记录
            if(CollectionUtils.isNotEmpty(applyDetailList)){
                List<MemberInsurance> memberInsuranceList = new ArrayList<>();
                for (ApplyDetail applyDetail:applyDetailList.stream()
                        .filter(m->Constants.equalsInteger(m.getApplyId(),(insuranceApply.getId()))).collect(Collectors.toList())) {
 
                    //查询人员信息是否存在相同的方案下是否存在 冲突数据
                    InsuranceApplyServiceImpl.checkStaticMemberSolution(solutions.getBaseId(),
                            applyDetail.getMemberId(),applyDetail.getIdcardNo(),applyDetail.getMemberName(),unionApply.getStartTime(),unionApply.getEndTime(),
                            applyDetailJoinMapper);
 
                    applyDetail.setPrice(price);
                    applyDetail.setFee(price.multiply(new BigDecimal(maxDays)).add(serverCost));
                    applyDetail.setStartTime(unionApplyBXDDTO.getStartTime());
                    applyDetail.setEndTime(unionApplyBXDDTO.getEndTime());
 
 
                    MemberInsurance memberInsurance = new MemberInsurance(applyDetail,user.getId());
                    memberInsurance.setBdCode(unionApplyBXDDTO.getCode());
                    memberInsurance.setRelationType(Constants.ZERO);
                    memberInsuranceList.add(memberInsurance);
                    //更新员工投保时间
                    memberMapper.update(null,new UpdateWrapper<Member>()
                            .lambda()
                            .set(Member::getStartTime,memberInsurance.getStartTime())
                            .set(Member::getEndTime,memberInsurance.getEndTime())
                            .set(Member::getDuId,memberInsurance.getDuId())
                            .set(Member::getWorktypeId,memberInsurance.getWorktypeId())
                            .eq(Member::getId, memberInsurance.getMemberId())
                    );
 
                }
                memberInsuranceJoinMapper.insert(memberInsuranceList);
            }
            BigDecimal detailFee = Constants.reduceFee(solutions,solutions.getPrice().add(serverCost),insuranceApply.getStartTime(),insuranceApply.getFinalEndTime(),
                    unionApplyBXDDTO.getStartTime(),unionApplyBXDDTO.getEndTime());
 
            BigDecimal applyFee =  detailFee.multiply(new BigDecimal(applyDetails.size()));
 
            Date finalEndTime =  endTime;
 
            //更新投保申请单
            insuranceApplyJoinMapper.update(null,new UpdateWrapper<InsuranceApply>().lambda()
                    .set(InsuranceApply::getUnionApplyTbdStatus,Constants.THREE)
                    .set(InsuranceApply::getStatus,Constants.InsuranceApplyStatus.WTB_DONE.getKey())
                    .set(InsuranceApply::getFee,applyFee)
                    .set(InsuranceApply::getCurrentFee,currentFee.multiply(new BigDecimal(applyDetails.size())))
                    .set(InsuranceApply::getStartTime,unionApplyBXDDTO.getStartTime())
                    .set(InsuranceApply::getEndTime,unionApplyBXDDTO.getEndTime())
                    .set(InsuranceApply::getEditDate,new Date())
                    .set(InsuranceApply::getEditor,user.getId())
                    .set(InsuranceApply::getServerCost,serverCost)
                    .set(InsuranceApply::getCode,unionApplyBXDDTO.getCode())
                    .set(InsuranceApply::getFinalEndTime,finalEndTime)
                    .eq(InsuranceApply::getId,insuranceApply.getId()));
            //更新投保单明细金额
            applyDetailJoinMapper.update(null,new UpdateWrapper<ApplyDetail>().lambda()
                    .set(ApplyDetail::getPrice,price)
                    .set(ApplyDetail::getFee, detailFee)
                    .set(ApplyDetail::getCurrentFee,currentFee)
                    .set(ApplyDetail::getEditDate,new Date())
                    .set(ApplyDetail::getEditor,user.getId())
                    .set(ApplyDetail::getStartTime,unionApplyBXDDTO.getStartTime())
                    .set(ApplyDetail::getEndTime,unionApplyBXDDTO.getEndTime())
                    .in(ApplyDetail::getId,applyDetails.stream().map(m->m.getId()).collect(Collectors.toList()))
            );
            sumFee = sumFee.add(applyFee);
            sumCurrFee = sumCurrFee.add(currentFee.multiply(new BigDecimal(applyDetails.size())));
        }
 
        unionApplyMapper.update(null,new UpdateWrapper<UnionApply>()
                .lambda()
                .set(UnionApply::getStatus,Constants.UnionApplyStatus.FINISH.getKey())
                .set(UnionApply::getEditDate,new Date())
                .set(UnionApply::getEditor,user.getId())
                .set(UnionApply::getStartTime,unionApplyBXDDTO.getStartTime())
                .set(UnionApply::getEndTime,unionApplyBXDDTO.getEndTime())
                .set(UnionApply::getCode,unionApplyBXDDTO.getCode())
                .set(UnionApply::getFee,sumFee)
                .set(UnionApply::getCurrentFee,sumCurrFee)
                .eq(UnionApply::getId,unionApply.getId())
        );
        //合并单 文件
        if(StringUtils.isNotBlank(unionApplyBXDDTO.getFileUrl())){
            Multifile multifile = new Multifile();
            multifile.setIsdeleted(Constants.ZERO);
            multifile.setCreator(user.getId());
            multifile.setCreateDate(new Date());
            multifile.setObjId(unionApply.getId());
            multifile.setObjType(Constants.MultiFile.WTB_BD_DONE_PDF.getKey());
            multifile.setType(Constants.TWO);
            multifile.setFileurl(unionApplyBXDDTO.getFileUrl());
            multifile.setName(unionApplyBXDDTO.getFileName());
            multifileMapper.insert(multifile);
        }
 
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.IA_HBD_UPLOAD_BXD;
        String info = "";
        if(Objects.nonNull(unionApplyBXDDTO.getStartTime())&&Objects.nonNull(unionApplyBXDDTO.getEndTime())){
            info =applyLogType.getInfo();
            info = info.replace("${param1}",DateUtil.getPlusTime2(unionApplyBXDDTO.getStartTime()));
            info = info.replace("${param2}",DateUtil.getPlusTime2(unionApplyBXDDTO.getEndTime()));
        }
        ApplyLog log = new ApplyLog(unionApply,applyLogType.getName(), info
                ,unionApply.getId(),applyLogType.getKey(),null, JSONObject.toJSONString(unionApply));
        applyLogMapper.insert(log);
 
 
    }
 
 
 
 
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public void updateUnionApplyCurrentFee(Integer id){
        List<UnionApply> unionApplyList = unionApplyJoinMapper.selectJoinList(UnionApply.class,new MPJLambdaWrapper<UnionApply>()
                .selectAll(UnionApply.class)
                .eq(UnionApply::getIsdeleted,Constants.ZERO)
                .eq(UnionApply::getStatus,Constants.UnionApplyStatus.FINISH.getKey())
                .eq(!Objects.isNull(id),UnionApply::getId,id)
                .le(UnionApply::getStartTime,DateUtil.getDate(new Date(),"yyyy-MM-dd") + " 00:00:00")
                .ge(UnionApply::getEndTime,DateUtil.getDate(new Date(),"yyyy-MM-dd") + " 23:59:59")
        );
 
        if(CollectionUtils.isNotEmpty(unionApplyList)){
            for (UnionApply unionApply:unionApplyList) {
                List<InsuranceApply> insuranceApplyList = insuranceApplyJoinMapper
                        .selectList(new QueryWrapper<InsuranceApply>().lambda()
                                .eq(InsuranceApply::getUnionApplyId,unionApply.getId()));
                if(CollectionUtils.isNotEmpty(insuranceApplyList)){
                    unionApply.setCurrentFee(insuranceApplyList.stream().map(m->m.getCurrentFee()).reduce(BigDecimal.ZERO,BigDecimal::add));
                    unionApplyMapper.updateById(unionApply);
                }
            }
        }
    }
 
 
}