BAOLH
2026-11-03 a1afc13f67a0345387065d39a6828d6573c3d364
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
/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.attendance.service.impl;
 
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.approval.domain.ApproveEvent;
import me.zhengjie.modules.approval.repository.ApproveEventRepository;
import me.zhengjie.modules.approval.service.TemplateControlFieldService;
import me.zhengjie.modules.approval.service.mapstruct.ApproveEventMapper;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.*;
import me.zhengjie.modules.attendance.service.AttendanceLeaveService;
import me.zhengjie.modules.attendance.service.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.*;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceLeaveMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.impl.WeComServiceImpl;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.SysUserLevelOtherRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.treatment.domain.CmnLevel;
import me.zhengjie.modules.treatment.repository.CmnLevelRepository;
import me.zhengjie.modules.treatment.service.dto.CmnLevelQueryCriteria;
import me.zhengjie.utils.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * @author wcd
* @website https://eladmin.vip
* @description 服务实现
* @date 2022-12-16
**/
@Service
@RequiredArgsConstructor
public class AttendanceLeaveServiceImpl implements AttendanceLeaveService {
 
    private final AttendanceLeaveRepository attendanceLeaveRepository;
    private final AttendanceLeaveMapper attendanceLeaveMapper;
    private final DictDetailRepository dictDetailRepository;
    private final AttendanceService attendanceService;
    private final SysUserLevelOtherRepository sysUserLevelOtherRepository;
    private final UserRepository userRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    private final ApproveEventRepository approveEventRepository;
    private final OvertimeConsumedRecordRepository overtimeConsumedRecordRepository;
    private final AnnualLeaveRecordRepository annualLeaveRecordRepository;
    private final CmnLevelRepository cmnLevelRepository;
    private final ApproveEventMapper approveEventMapper;
    private final WeComServiceImpl weComService;
    private final TemplateControlFieldService templateControlFieldService;
 
    private final DateTimeFormatter ymFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
 
    @Override
    public Map<String,Object> queryAll(AttendanceLeaveQueryCriteria criteria, Pageable pageable){
        Page<AttendanceLeave> page = attendanceLeaveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<AttendanceLeave, AttendanceLeaveDto> func = new Function<AttendanceLeave, AttendanceLeaveDto>(){
 
            @Override
            public AttendanceLeaveDto apply(AttendanceLeave attendanceLeave) {
                // 将实体类转换成DTO
                AttendanceLeaveDto attendanceLeaveDto = attendanceLeaveMapper.toDto(attendanceLeave);
                //查询用户信息
                User user = userRepository.findById(attendanceLeaveDto.getUserId()).orElseGet(User::new);
                attendanceLeaveDto.setUserName(user.getNickName());
                //查询审批用户名
                User appUser = userRepository.findById(attendanceLeaveDto.getApprovalUserId()).orElseGet(User::new);
                attendanceLeaveDto.setAppUserName(appUser.getNickName());
 
                // 查询企微最新审批变化记录
                if (ObjectUtils.isNotEmpty(attendanceLeave.getWecomEventId())) {
                    ApproveEvent event = approveEventRepository.findById(attendanceLeave.getWecomEventId()).orElseGet(ApproveEvent::new);
                    attendanceLeaveDto.setEvent(approveEventMapper.toDto(event));
                }
 
                return attendanceLeaveDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
 
    @Override
    public List<AttendanceLeaveDto> queryAll(AttendanceLeaveQueryCriteria criteria){
        List<AttendanceLeaveDto> attendanceLeaveDtoList = attendanceLeaveMapper.toDto(attendanceLeaveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        attendanceLeaveDtoList.forEach(attendanceLeaveDto -> {
            //查询用户信息
            User user = userRepository.findById(attendanceLeaveDto.getUserId()).orElseGet(User::new);
            attendanceLeaveDto.setUserName(user.getNickName());
            //查询审批用户名
            User appUser = userRepository.findById(attendanceLeaveDto.getApprovalUserId()).orElseGet(User::new);
            attendanceLeaveDto.setAppUserName(appUser.getNickName());
        });
        return attendanceLeaveDtoList;
    }
 
    @Override
    @Transactional
    public AttendanceLeaveDto findById(Long id) {
        AttendanceLeave attendanceLeave = attendanceLeaveRepository.findById(id).orElseGet(AttendanceLeave::new);
        ValidationUtil.isNull(attendanceLeave.getId(),"AttendanceLeave","id",id);
        return attendanceLeaveMapper.toDto(attendanceLeave);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceLeaveDto create(AttendanceLeave resources) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String LeaStartTime = df.format(resources.getLeaveStartTime());
        String LeaEndTime = df.format(resources.getLeaveEndTime());
        // 如果按天为单位请假拼接请假时间的时分秒,取上下班基准时间
        if(resources.getLeaveDurationUnit().equals(Constant.LEAVE_TIME_TYPE_DAY)) {
            //查询用户的排班时间
            User user = userRepository.getOne(resources.getUserId());
            LeaStartTime = LeaStartTime.substring(0,10) + " " + user.getSysRostering().getWorkStartTime().toString() + ":00";
            LeaEndTime = LeaEndTime.substring(0,10) + " " + user.getSysRostering().getWorkEndTime().toString() + ":00";
        }
        // 查询其他状态的表是否有重复
//        repeatValidation(LeaStartTime, LeaEndTime, resources.getUserId());
        // 验证请假时间是否冲突
        List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.checkCreateLeaveTime(LeaStartTime,LeaEndTime, resources.getUserId());
        if(attendanceLeaveList.size() > 0){
            AttendanceLeave errTime = attendanceLeaveList.get(0);
            //LocalDateTime转换为Date
            LocalDateTime strartTime = errTime.getLeaveStartTime().toLocalDateTime();
            ZonedDateTime zonedDateTime = strartTime.atZone(ZoneId.systemDefault());
            Instant instant = zonedDateTime.toInstant();
            Date strTime = Date.from(instant);
            LocalDateTime endTime = errTime.getLeaveEndTime().toLocalDateTime();
            ZonedDateTime zonedDateTime1 = endTime.atZone(ZoneId.systemDefault());
            Instant instant1 = zonedDateTime1.toInstant();
            Date endTim = Date.from(instant1);
 
            SimpleDateFormat errorFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            throw new BadRequestException("请假时间冲突," + errorFormat.format(strTime) + "至" + errorFormat.format(endTim)
                    + "已经存在请假记录,请调整时间");
        }else {
            // 获取当前登陆人信息,设置为请假发起人
            User user = userRepository.getOne(resources.getUserId());
            User approvalUser = userRepository.getOne(resources.getApprovalUserId());
            List<String> holiday = new ArrayList<>(), isWork = new ArrayList<>();
            // 查询节假日
            List<SysConfigHoliday> sysConfigHolidayList = sysConfigHolidayRepository.findAll();
            for(SysConfigHoliday sysConfigHoliday : sysConfigHolidayList){
                if(sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_WEEKDAY)){
                    //工作日
                    isWork.add(sysConfigHoliday.getHolidayDate().toString().substring(0,10));
                }else{
                    holiday.add(sysConfigHoliday.getHolidayDate().toString().substring(0,10));
                }
            }
            // 循环添加开始时间到结束时间的每一天
            List<String> dateList = getBetweenDate(resources.getLeaveStartTime().toLocalDateTime().toString(),resources.getLeaveEndTime().toLocalDateTime().toString());
            int i = 0;
            for(String date : dateList){
                LocalDate localDate = LocalDate.parse(date);
                Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
                // 不是周末并且节假日表中不存在在创建
                if((!isWeekend && !holiday.contains(date)) || (isWeekend && isWork.contains(date))){
                    AttendanceLeave attendanceLeave = getAttendanceLeave(resources,date,user,i,LeaStartTime,LeaEndTime,null);
 
                    // 判断是否提交企微审批
                    List<DictDetail> siteTypes = dictDetailRepository.findByDictName(Constant.APPROVAL_SITE_TYPE).stream().filter(siteType -> siteType.getValue().toLowerCase().equals("wecom")).collect(Collectors.toList());
                    if (siteTypes.size() > 0) {
                        // 添加企微申请参数
                        if (resources.getLeaveDurationUnit().equals(Constant.LEAVE_TIME_TYPE_HOUR)) {
                            attendanceLeave.setWecomDateType(ElAdminConstant.Constant.TEMPLATE_DATE_RANGE_TYPE_HOUR);
                            attendanceLeave.setWecomDuration(String.valueOf(new BigDecimal(attendanceLeave.getLeaveDuration()).multiply(new BigDecimal(3600)).longValue()));
                        } else {
                            attendanceLeave.setWecomDateType(ElAdminConstant.Constant.TEMPLATE_DATE_TYPE_HALFDAY);
                            attendanceLeave.setWecomDuration(String.valueOf(new BigDecimal(attendanceLeave.getLeaveDuration()).multiply(new BigDecimal(86400)).longValue()));
                        }
                        // 添加企微申请参数
                        Map<String, String> leaveTypeMap = dictDetailRepository.findByDictName(Constant.LEAVE_TYPE).stream().collect(Collectors.toMap(DictDetail::getValue, DictDetail::getLabel));
//                        attendanceLeave.setWecomOptionKey(templateService.getVacationKey(leaveTypeMap.get(attendanceLeave.getLeaveType())));
                        attendanceLeave.setWecomOptionKey(leaveTypeMap.get(attendanceLeave.getLeaveType()));
                        attendanceLeave.setWecomApproveWecomId(approvalUser.getWeComId());
                        // 提交申请
                        Map<String, String> approvalResultMap = templateControlFieldService.createWecomApproval(attendanceLeave, user.getWeComId());
                        if (approvalResultMap.containsKey("spNo")) {
                            attendanceLeave.setWecomSpNo(approvalResultMap.get("spNo"));
                        } else {
                            throw new BadRequestException(approvalResultMap.containsKey("error") ? approvalResultMap.get("error") : "企微申请提交失败");
                        }
                    }
 
                    i++;
                    AttendanceLeave attendanceLeaveSaved = attendanceLeaveRepository.save(attendanceLeave);
                    if (attendanceLeaveSaved.getLeaveType().equals(Constant.LEAVE_TYPE_REPLACE)) {
                        this.overtimeDeduction(attendanceLeaveSaved, false);
                    }
                }
            }
 
            return attendanceLeaveMapper.toDto(resources);
        }
    }
 
    /**
     * 添加多条记录
     *
     * @param resources
     * @param date
     * @param user
     * @param i
     * @param LeaStartTime
     * @param LeaEndTime
     * @return
     */
    public AttendanceLeave getAttendanceLeave(AttendanceLeave resources,String date,User user,int i,String LeaStartTime,String LeaEndTime,Long resUserId){
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        AttendanceLeave attendanceLeave = new AttendanceLeave();
        //resUserId为null说明是添加,反之
        if(resUserId == null){
            resources.setUserId(user.getId());
        }else{
            resources.setUserId(resUserId);
        }
        //日期时间单位是小时
        if(resources.getLeaveDurationUnit().equals(Constant.LEAVE_TIME_TYPE_HOUR)){
            Calculate calculate = new Calculate();
            String startTime = date + " " + LeaStartTime.substring(11,19);
            String endTime = date + " " + LeaEndTime.substring(11,19);
            //请假开始时间结束时间不相等的情况
            if(!LeaStartTime.substring(0,10).equals(LeaEndTime.substring(0,10))){
                //第一次循环用下班基准时间和请假开始时间算时长
                if(i == 0){
                    calculate.setStart(LocalDateTime.parse(startTime,sdf));
                    calculate.setEnd(LocalDateTime.parse(date + " " + user.getSysRostering().getWorkEndTime() + ":00",sdf));
                    resources.setLeaveStartTime(Timestamp.valueOf(startTime));
                    resources.setLeaveEndTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkEndTime() + ":00"));
                }else if(date.equals(LeaEndTime.substring(0,10))){
                    //最后一次循环
                    calculate.setStart(LocalDateTime.parse(date + " " + user.getSysRostering().getWorkStartTime() + ":00",sdf));
                    calculate.setEnd(LocalDateTime.parse(endTime,sdf));
                    resources.setLeaveStartTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkStartTime() + ":00"));
                    resources.setLeaveEndTime(Timestamp.valueOf(endTime));
                }else{
                    calculate.setStart(LocalDateTime.parse(date + " " + user.getSysRostering().getWorkStartTime() + ":00",sdf));
                    calculate.setEnd(LocalDateTime.parse(date + " " + user.getSysRostering().getWorkEndTime() + ":00",sdf));
                    resources.setLeaveStartTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkStartTime() + ":00"));
                    resources.setLeaveEndTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkEndTime() + ":00"));
                }
                Integer timeSeconds = attendanceService.calculateTimes(calculate, SecurityUtils.getCurrentUserId(), resources.getLeaveType().equals(Constant.LEAVE_TYPE_LACTATION_LEAVE) ? 1 : null);
                Double result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                resources.setLeaveDuration(result);
            }
        }else{
            String startTime = date + " " + user.getSysRostering().getWorkStartTime() + ":00";
            String endTime = date + " " + user.getSysRostering().getWorkEndTime() + ":00";
            resources.setLeaveStartTime(Timestamp.valueOf(startTime));
            resources.setLeaveEndTime(Timestamp.valueOf(endTime));
            resources.setLeaveDuration(Constant.NUMBER_ONE);
        }
        resources.setApprovalStatus(Constant.APPROVAL_STATUS_UNDER_APPROVAL);
        attendanceLeave.copy(resources);
        return attendanceLeave;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AttendanceLeave resources) {
        AttendanceLeave attendanceLeave = attendanceLeaveRepository.findById(resources.getId()).orElseGet(AttendanceLeave::new);
        ValidationUtil.isNull( attendanceLeave.getId(),"AttendanceLeave","id",resources.getId());
        attendanceLeave.copy(resources);
 
        //审核通过或者退回不能删除
        if(attendanceLeave.getApprovalStatus().equals(Constant.APPROVAL_STATUS_PASSED) || attendanceLeave.getApprovalStatus().equals(Constant.APPROVAL_STATUS_RETURNED)){
            throw new BadRequestException("审核通过或退回的不能进行修改");
        }
 
        //获取当前登入人信息
        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user1.getRoles().iterator().next();
        // 除超管、总经理只能修改自己信息
        if (!Constant.SUPER_LEVEL_LIST.contains(Long.valueOf(role.getLevel()))){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
 
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String LeaStartTime = df.format(resources.getLeaveStartTime());
        String LeaEndTime = df.format(resources.getLeaveEndTime());
        // 如果按天为单位请假拼接请假时间的时分秒,取上下班基准时间
        if(resources.getLeaveDurationUnit().equals(Constant.LEAVE_TIME_TYPE_DAY)){
            //查询用户的排班时间
            User user = userRepository.getOne(resources.getUserId());
            LeaStartTime = LeaStartTime.substring(0,10) + " " + user.getSysRostering().getWorkStartTime().toString() + ":00";
            LeaEndTime = LeaEndTime.substring(0,10) + " " + user.getSysRostering().getWorkEndTime().toString() + ":00";
        }
        // 查询其他状态的表是否有重复
//        repeatValidation(LeaStartTime, LeaEndTime, resources.getUserId());
        // 验证是否存在时间冲突的请假记录
        Set<Long> ids = new HashSet<>();
        ids.add(attendanceLeave.getId());
        List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.checkUpdateForLeaveTime(LeaStartTime, LeaEndTime, attendanceLeave.getUserId(), ids);
        if (attendanceLeaveList.size() > 0) {
            AttendanceLeave errorSysAskForLeave = attendanceLeaveList.get(0);
            SimpleDateFormat errorFormat = new SimpleDateFormat("yyyy年MM月dd日");
                throw new BadRequestException("请假时间冲突," + errorFormat.format(errorSysAskForLeave.getLeaveStartTime()) + "至" + errorFormat.format(errorSysAskForLeave.getLeaveEndTime())
                        + "已经存在请假记录,请调整时间");
        }else{
            //暂存userId
            Long resUserId = attendanceLeave.getUserId();
            // 删除以前的记录
            for (Long id : ids) {
                AttendanceLeave delAttendanceLeave = new AttendanceLeave();
                delAttendanceLeave.setId(id);
                this.overtimeDeduction(delAttendanceLeave, true);
                attendanceLeaveRepository.deleteById(id);
            }
            // 获取当前登陆人信息,设置为请假发起人
            User user = userRepository.getOne(resources.getUserId());
            List<String> holiday = new ArrayList<>(), isWork = new ArrayList<>();
            // 查询节假日
            List<SysConfigHoliday> sysConfigHolidayList = sysConfigHolidayRepository.findAll();
            for(SysConfigHoliday sysConfigHoliday : sysConfigHolidayList){
                if(sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_WEEKDAY)){
                    //工作日
                    isWork.add(sysConfigHoliday.getHolidayDate().toString().substring(0,10));
                }else{
                    holiday.add(sysConfigHoliday.getHolidayDate().toString().substring(0,10));
                }
            }
            // 循环添加开始时间到结束时间的每一天
            List<String> dateList = getBetweenDate(resources.getLeaveStartTime().toLocalDateTime().toString(),resources.getLeaveEndTime().toLocalDateTime().toString());
            int i = 0;
            for(String date : dateList){
                LocalDate localDate = LocalDate.parse(date);
                Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
                // 不是周末并且节假日表中不存在在创建
                if((!isWeekend && !holiday.contains(date)) || (isWeekend && isWork.contains(date))){
                    AttendanceLeave attendanceLeave1 = getAttendanceLeave(resources,date,user,i,LeaStartTime,LeaEndTime,resUserId);
                    i++;
                    AttendanceLeave attendanceLeaveSaved = attendanceLeaveRepository.save(attendanceLeave1);
                    if (attendanceLeaveSaved.getLeaveType().equals(Constant.LEAVE_TYPE_REPLACE)) {
                        this.overtimeDeduction(attendanceLeaveSaved, false);
                    }
                }
            }
        }
    }
 
    /**
     * 验证其他状态的表是否有重复
     *
     * @param startTime
     * @param endTime
     * @param userId
     */
    public void repeatValidation(String startTime, String endTime, Long userId){
        // 查询外出表
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.checkCreateTime(startTime, endTime, userId);
        if(attendanceGoOutList.size() > 0) {
            AttendanceGoOut errorSysAskForLeave = attendanceGoOutList.get(0);
            SimpleDateFormat errorFormat = new SimpleDateFormat("yyyy年MM月dd日");
            throw new BadRequestException("外出时间冲突," + errorFormat.format(errorSysAskForLeave.getOutStartTime()) + "至" + errorFormat.format(errorSysAskForLeave.getOutEndTime())
                    + "已经存在外出记录,请调整时间");
        }
        // 查询出差表
        List<AttendanceBusinessTravel> attendanceBusinessTravelList = attendanceBusinessTravelRepository.checkCreateTime(startTime.substring(0,10),endTime.substring(0,10), userId);
        if(attendanceBusinessTravelList.size() > 0){
            AttendanceBusinessTravel errorSysAskForLeave = attendanceBusinessTravelList.get(0);
            SimpleDateFormat errorFormat = new SimpleDateFormat("yyyy年MM月dd日");
            throw new BadRequestException("出差时间冲突," + errorFormat.format(errorSysAskForLeave.getTravelStartTime()) + "至" + errorFormat.format(errorSysAskForLeave.getTravelEndTime())
                    + "已经存在出差记录,请调整时间");
        }
    }
 
 
    /**
     * 获取两个日期之间的所有日期
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public List<String> getBetweenDate(String startTime, String endTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 声明保存日期集合
        List<String> list = new ArrayList<String>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);
 
            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime()<=endDate.getTime()) {
                // 把日期添加到集合
                list.add(sdf.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把日期增加一天
                calendar.add(Calendar.DATE, 1);
                // 获取增加后的日期
                startDate=calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }
 
    /**
     * 计算请假时长
     *
     * @param resources /
     * @return
     * @throws Exception
     */
    @Override
    public AttendanceLeaveDto calcTimeLength(AttendanceLeave resources) throws Exception {
        AttendanceLeaveDto attendanceLeaveDto = new AttendanceLeaveDto();
        // 根据字典名称查询
        List<DictDetail> dictDetailList = dictDetailRepository.findByDictName("leave_type");
        List<String> leaveTypes = new ArrayList<>();
        for (DictDetail dictDetail : dictDetailList) {
            if (dictDetail.getValue().equals(Constant.LEAVE_TYPE_ANNUAL_LEAVE) || dictDetail.getValue().equals(Constant.LEAVE_TYPE_REPLACE) || dictDetail.getValue().equals(Constant.LEAVE_TYPE_COMPASSIONATE_LEAVE) || dictDetail.getValue().equals(Constant.LEAVE_TYPE_LACTATION_LEAVE)) {
                // 事假/年假/调休假/哺乳假
                leaveTypes.add(dictDetail.getValue());
            }
        }
        Calculate calculate = new Calculate();
        calculate.setStart(resources.getLeaveStartTime().toLocalDateTime());
        calculate.setEnd(resources.getLeaveEndTime().toLocalDateTime());
        Double result = new Double(0.00);
        // 判断集合是否包含年假或事假,包含计算以时为单位,反之以天为单位进行计算
        if (leaveTypes.contains(resources.getLeaveType())) {
            // 以小时为单位计算
            Integer timeSeconds = attendanceService.calculateTimes(calculate, SecurityUtils.getCurrentUserId(), resources.getLeaveType().equals(Constant.LEAVE_TYPE_LACTATION_LEAVE) ? 1 : null);
            result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            attendanceLeaveDto.setLeaveDurationUnit(Constant.LEAVE_TIME_TYPE_HOUR);
            if (result < 1) {
                throw new BadRequestException("请假时间不可低于1小时");
            }
        } else {
            // 以天为单位计算
            Integer days = attendanceService.calculateDays(calculate);
            result = Double.valueOf(new BigDecimal(days).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            attendanceLeaveDto.setLeaveDurationUnit(Constant.LEAVE_TIME_TYPE_DAY);
        }
        attendanceLeaveDto.setLeaveDuration(result);
        return attendanceLeaveDto;
    }
 
    /**
     * 获取用户年假剩余时长
     */
    @Override
    public Double getYearTimeLength(Long userId, String year) {
        // 默认参数
        LocalDate targetDate;
        if (StringUtils.isBlank(year)) {
            // 未指定年度
            targetDate = LocalDate.now();
        } else {
            // 指定年度
            if (LocalDate.now().getYear() == Integer.parseInt(year)) {
                // 当年
                targetDate = LocalDate.now();
            } else {
                // 往年
                targetDate = LocalDate.now().withYear(Integer.parseInt(year)).plusYears(1).withDayOfYear(1).minusDays(1);
            }
        }
 
        // 年假配额
        BigDecimal surplusYearTime = BigDecimal.valueOf(getAnnualLeaveQuota(userId, year));
 
        // 当年使用年假时长
        String startTime = targetDate.withDayOfYear(1).atTime(4, 0, 0, 0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endTime = targetDate.withDayOfYear(1).plusYears(1).atTime(3, 59, 59, 0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Double usedYearTime = attendanceLeaveRepository.getSurplusYearTime(userId, startTime, endTime);
 
        // 计算本年度剩余年假时长
        surplusYearTime = surplusYearTime.subtract(new BigDecimal(usedYearTime == null ? 0.0 : usedYearTime));
 
        return surplusYearTime.doubleValue();
    }
 
    /**
     * 获取用户调休假剩余时长
     */
    @Override
    public Double getOverTimeLength(Long userId, LocalDateTime localDateTime) {
        LocalDateTime startLocalDateTime = localDateTime.minusMonths(2L).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endLocalDateTime = localDateTime.withDayOfMonth(1).plusMonths(1).minusDays(1).withHour(23).withMinute(59).withSecond(59);
 
        // 查询可用调休申请
        AttendanceOvertimeQueryCriteria overtimeCriteria = new AttendanceOvertimeQueryCriteria();
        overtimeCriteria.setOvertimeStartTime(Arrays.asList(Timestamp.valueOf(startLocalDateTime), Timestamp.valueOf(endLocalDateTime)));
        overtimeCriteria.setApprovalStatus(Constant.OVERTIME_PASS);
        overtimeCriteria.setUserId(userId);
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, overtimeCriteria, criteriaBuilder), Sort.by(Sort.Direction.ASC, "overtimeStartTime"));
 
        return attendanceOvertimeList.stream().collect(Collectors.summingDouble(AttendanceOvertime::getRemainingDuration));
    }
 
    /**
     * 获取用户调休假剩余时长
     */
    @Override
    public Double getOverTimeLength(Long userId, String yearMonth) {
        LocalDateTime localDateTime = LocalDateTime.parse(yearMonth + "-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime startLocalDateTime = localDateTime.minusMonths(2L).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endLocalDateTime = localDateTime.withDayOfMonth(1).plusMonths(1).minusDays(1).withHour(23).withMinute(59).withSecond(59);
 
        // 因换休3个月后会被结算,只能统计未结算的,仅当前时间3个月内(只参考月份)的可统计。
        LocalDateTime currentStartLocalDateTime = localDateTime.now().minusMonths(2L).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime currentEndLocalDateTime = localDateTime.now().withDayOfMonth(1).plusMonths(1).minusDays(1).withHour(23).withMinute(59).withSecond(59).withNano(0);
        Calculate finalCalculate = new Calculate(currentStartLocalDateTime, currentEndLocalDateTime).getOverlap(new Calculate(startLocalDateTime, endLocalDateTime));
        if (finalCalculate != null) {
            startLocalDateTime = finalCalculate.getStart();
            endLocalDateTime = finalCalculate.getEnd();
        } else {
            return Double.valueOf(0);
        }
 
        // 查询可用调休申请
        AttendanceOvertimeQueryCriteria overtimeCriteria = new AttendanceOvertimeQueryCriteria();
        overtimeCriteria.setOvertimeStartTime(Arrays.asList(Timestamp.valueOf(startLocalDateTime), Timestamp.valueOf(endLocalDateTime)));
        overtimeCriteria.setApprovalStatus(Constant.OVERTIME_PASS);
        overtimeCriteria.setUserId(userId);
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, overtimeCriteria, criteriaBuilder), Sort.by(Sort.Direction.ASC, "overtimeStartTime"));
 
        return attendanceOvertimeList.stream().collect(Collectors.summingDouble(AttendanceOvertime::getRemainingDuration));
    }
 
    /**
     * 获取用户待结算(下月即将结算)调休假时长
     */
    @Override
    public Double getOverTimeCloseLength(Long userId, LocalDateTime localDateTime) {
        LocalDateTime startLocalDateTime = localDateTime.minusMonths(2L).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endLocalDateTime = localDateTime.minusMonths(1L).withDayOfMonth(1).minusDays(1).withHour(23).withMinute(59).withSecond(59);
 
        // 查询可用调休申请
        AttendanceOvertimeQueryCriteria overtimeCriteria = new AttendanceOvertimeQueryCriteria();
        overtimeCriteria.setOvertimeStartTime(Arrays.asList(Timestamp.valueOf(startLocalDateTime), Timestamp.valueOf(endLocalDateTime)));
        overtimeCriteria.setApprovalStatus(Constant.OVERTIME_PASS);
        overtimeCriteria.setUserId(userId);
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, overtimeCriteria, criteriaBuilder), Sort.by(Sort.Direction.ASC, "overtimeStartTime"));
 
        return attendanceOvertimeList.stream().collect(Collectors.summingDouble(AttendanceOvertime::getRemainingDuration));
    }
 
    /**
     * 获取用户当月结算调休假时长
     */
    @Override
    public Double getOverTimeCurrentCloseLength(Long userId, LocalDateTime localDateTime) {
        LocalDateTime startLocalDateTime = localDateTime.minusMonths(3L).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endLocalDateTime = localDateTime.minusMonths(2L).withDayOfMonth(1).minusDays(1).withHour(23).withMinute(59).withSecond(59);
 
        // 查询可用调休申请
        AttendanceOvertimeQueryCriteria overtimeCriteria = new AttendanceOvertimeQueryCriteria();
        overtimeCriteria.setOvertimeStartTime(Arrays.asList(Timestamp.valueOf(startLocalDateTime), Timestamp.valueOf(endLocalDateTime)));
        overtimeCriteria.setApprovalStatus(Constant.OVERTIME_PASS);
        overtimeCriteria.setUserId(userId);
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, overtimeCriteria, criteriaBuilder), Sort.by(Sort.Direction.ASC, "overtimeStartTime"));
 
        return attendanceOvertimeList.stream().collect(Collectors.summingDouble(AttendanceOvertime::getRemainingDuration));
    }
 
    /**
     * 审核功能
     *
     * @param resources /
     */
    @Override
    public void updateApprove(AttendanceLeave resources) throws Exception {
        AttendanceLeave attendanceLeave = attendanceLeaveRepository.findById(resources.getId()).orElseGet(AttendanceLeave::new);
        ValidationUtil.isNull( attendanceLeave.getId(),"AttendanceLeave","id",resources.getId());
        attendanceLeave.copy(resources);
        AttendanceLeave attendanceLeaveSaved = attendanceLeaveRepository.save(attendanceLeave);
        if (attendanceLeaveSaved.getLeaveType().equals(Constant.LEAVE_TYPE_REPLACE) && attendanceLeaveSaved.getApprovalStatus().equals(Constant.APPROVAL_STATUS_RETURNED)) {
            this.overtimeDeduction(attendanceLeaveSaved, true);
        }
        // 调用定时任务修改考勤记录
        List<User> userList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(attendanceLeave.getUserId())) {
            User user = userRepository.findById(attendanceLeave.getUserId()).orElseGet(User::new);
            userList.add(user);
        }
        if (attendanceLeave.getLeaveStartTime().before(new Date())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String attendanceDate = df.format(attendanceLeave.getLeaveStartTime());
            weComService.getWeComAttendanceListOfNoonOrNight(attendanceDate,userList);
        }
    }
 
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //根据id查询记录
            Optional<AttendanceLeave> attendanceLeave = attendanceLeaveRepository.findById(id);
            //审核通过或者退回不能删除
            if(attendanceLeave.get().getApprovalStatus().equals(Constant.APPROVAL_STATUS_PASSED) || attendanceLeave.get().getApprovalStatus().equals(Constant.APPROVAL_STATUS_RETURNED)){
                throw new BadRequestException("审核通过或退回的不能进行删除");
            }
 
            //获取当前登入人信息
            User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
            Role role = user.getRoles().iterator().next();
            //根据id查询记录
            Optional<AttendanceLeave> attendanceLeave1 = attendanceLeaveRepository.findById(id);
            // 除超管、总经理只能删除自己信息
            if(!Constant.SUPER_LEVEL_LIST.contains(Long.valueOf(role.getLevel()))){
                if (!Long.valueOf(attendanceLeave1.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            if (attendanceLeave.get().getLeaveType().equals(Constant.LEAVE_TYPE_REPLACE)) {
                this.overtimeDeduction(attendanceLeave.get(), true);
            }
            attendanceLeaveRepository.deleteById(id);
        }
    }
 
    /**
     * 批量审核
     *
     * @param request
     */
    @Override
    public void updateAgree(AgreeUpdateRequest request) throws Exception {
        // 循环ID列表
        for (Long id : request.getIds()) {
            AttendanceLeave attendanceLeave = attendanceLeaveRepository.findById(id).orElseGet(AttendanceLeave::new);
            ValidationUtil.isNull( attendanceLeave.getId(),"AttendanceLeave","id",id);
            if (request.getNum().equals(Long.valueOf(1))) {
                attendanceLeave.setApprovalStatus(Constant.APPROVAL_STATUS_PASSED);
            } else {
                attendanceLeave.setApprovalStatus(Constant.APPROVAL_STATUS_RETURNED);
            }
            AttendanceLeave attendanceLeaveSaved = attendanceLeaveRepository.save(attendanceLeave);
            if (attendanceLeaveSaved.getLeaveType().equals(Constant.LEAVE_TYPE_REPLACE)) {
                this.overtimeDeduction(attendanceLeaveSaved, false);
            }
 
            // 调用定时任务修改考勤记录
            List<User> userList = new ArrayList<>();
            if(ObjectUtils.isNotEmpty(attendanceLeave.getUserId())){
                User user = userRepository.findById(attendanceLeave.getUserId()).orElseGet(User::new);
                userList.add(user);
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String attendanceDate = df.format(attendanceLeave.getLeaveStartTime());
            weComService.getWeComAttendanceListOfNoonOrNight(attendanceDate,userList);
        }
    }
 
    @Override
    public void download(List<AttendanceLeaveDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceLeaveDto attendanceLeave : all) {
            String leavrType = attendanceLeave.getLeaveType() != null ? dictDetailRepository.findByDictNameAndValue(Constant.LEAVE_TYPE, attendanceLeave.getLeaveType()).getLabel() : "";
            String leaveStatus = attendanceLeave.getApprovalStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.APPROVAL_STATUS, attendanceLeave.getApprovalStatus()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请者", attendanceLeave.getUserName());
            map.put("审批者", attendanceLeave.getAppUserName());
            map.put("请假类型", leavrType);
            map.put("请假开始时间", attendanceLeave.getLeaveStartTime());
            map.put("请假结束时间", attendanceLeave.getLeaveEndTime());
            map.put("请假时长", attendanceLeave.getLeaveDuration());
            map.put("请假原因", attendanceLeave.getLeaveReason());
            map.put("审批状态", leaveStatus);
            map.put("审批说明", attendanceLeave.getApprovalDescription());
            map.put("备注", attendanceLeave.getRemarks());
            map.put("创建者", attendanceLeave.getCreateBy());
            map.put("创建时间", attendanceLeave.getCreateTime());
            map.put("更新者", attendanceLeave.getUpdateBy());
            map.put("更新时间", attendanceLeave.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
 
    /**
     * 结算去年剩余年假
     */
    @Override
    public Double settlementLastYearTime(Long userId, String year) {
        // 默认参数
        LocalDate targetDate;
        if (StringUtils.isBlank(year)) {
            // 未指定年度
            targetDate = LocalDate.now();
        } else {
            // 指定年度
            if (LocalDate.now().getYear() == Integer.parseInt(year)) {
                // 当年
                targetDate = LocalDate.now();
            } else {
                // 往年
                targetDate = LocalDate.now().withYear(Integer.parseInt(year)).plusYears(1).withDayOfYear(1).minusDays(1);
            }
        }
 
        // 年假配额
        BigDecimal surplusYearTime = BigDecimal.valueOf(getAnnualLeaveQuota(userId, year));
 
        // 判断是否已结算
        AnnualLeaveRecordQueryCriteria settlementCriteria = new AnnualLeaveRecordQueryCriteria();
        settlementCriteria.setUserId(userId);
        settlementCriteria.setYear(String.valueOf(targetDate.getYear()));
        AnnualLeaveRecord annualLeaveRecord = annualLeaveRecordRepository.findOne((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, settlementCriteria, criteriaBuilder)).orElse(null);
        if (annualLeaveRecord == null) {
            // 当年使用年假时长
            String startTime = targetDate.withDayOfYear(1).atTime(4, 0, 0, 0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String endTime = targetDate.withDayOfYear(1).plusYears(1).atTime(3, 59, 59, 0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Double usedYearTime = attendanceLeaveRepository.getSurplusYearTime(userId, startTime, endTime);
 
            // 计算本年度剩余年假时长
            surplusYearTime = surplusYearTime.subtract(new BigDecimal(usedYearTime == null ? 0.0 : usedYearTime));
 
            AnnualLeaveRecord lastRecord = new AnnualLeaveRecord();
            lastRecord.setUserId(userId);
            lastRecord.setYear(String.valueOf(targetDate.getYear()));
            lastRecord.setSurplusHour(surplusYearTime.doubleValue());
            annualLeaveRecordRepository.save(lastRecord);
 
            if (lastRecord.getSurplusHour() >= 1) {
                // 剩余年假大于1H时转为调休保存
                AttendanceOvertime attendanceOvertime = new AttendanceOvertime();
                attendanceOvertime.setUserId(userId);
                attendanceOvertime.setApprovalUserId(0L);
                attendanceOvertime.setOvertimeStartTime(Timestamp.valueOf(targetDate.plusYears(1).withDayOfYear(1).atTime(4, 0, 1)));
                attendanceOvertime.setOvertimeEndTime(Timestamp.valueOf(targetDate.plusYears(1).withDayOfYear(1).atTime(4, 0, 2)));
                attendanceOvertime.setOvertimeDuration(surplusYearTime.setScale(0, RoundingMode.DOWN).doubleValue());
                // 设置为休息日普通结算
                attendanceOvertime.setDateType(Constant.DATE_TYPE_WEEKEND);
                attendanceOvertime.setApprovalStatus(Constant.OVERTIME_PASS);
                attendanceOvertime.setRemarks(targetDate.getYear() + "年度年假结算剩余转换");
                attendanceOvertime.setRemainingDuration(surplusYearTime.setScale(0, RoundingMode.DOWN).doubleValue());
 
                attendanceOvertimeRepository.save(attendanceOvertime);
            }
        } else {
            return annualLeaveRecord.getSurplusHour();
        }
 
        return surplusYearTime.doubleValue();
    }
 
    /**
     * 获取年度年假额度
     */
    @Override
    public Double getAnnualLeaveQuota(Long userId, String year) {
        // 默认参数
        LocalDate targetDate;
        if (StringUtils.isBlank(year)) {
            // 未指定年度
            targetDate = LocalDate.now();
        } else {
            // 指定年度
            if (LocalDate.now().getYear() == Integer.parseInt(year)) {
                // 当年
                targetDate = LocalDate.now();
            } else {
                // 往年
                targetDate = LocalDate.now().withYear(Integer.parseInt(year)).plusYears(1).withDayOfYear(1).minusDays(1);
            }
        }
 
        // 获取年假剩余(新)
        BigDecimal surplusYearTime = BigDecimal.ZERO;
 
        // 判断年份是否在用户创建之前
        User user = userRepository.findById(userId).orElse(null);
        if (targetDate.getYear() < user.getCreateTime().toLocalDateTime().getYear()) {
            return surplusYearTime.doubleValue();
        }
 
        // 判断用户是否为实习生(实习生无年假)
        CmnLevelQueryCriteria levelQueryCriteria = new CmnLevelQueryCriteria();
        levelQueryCriteria.setName("实习");
        List<CmnLevel> internshipLevelList = cmnLevelRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, levelQueryCriteria, criteriaBuilder));
        if (internshipLevelList.size() > 0) {
            internshipLevelList.stream().map(CmnLevel::getId).collect(Collectors.toList());
            SysUserLevelOther targetSysUserLevelOther = sysUserLevelOtherRepository.findByUserIdAndData(userId, targetDate.format(DateTimeFormatter.ofPattern("yyyy-MM")));
            if (targetSysUserLevelOther != null && internshipLevelList.stream().map(CmnLevel::getId).anyMatch(id -> id.equals(targetSysUserLevelOther.getLevelId()))) {
                return surplusYearTime.doubleValue();
            }
        }
 
        // 根据用户查询
        List<SysUserLevelOther> sysUserLevelOtherList = sysUserLevelOtherRepository.findByUserId(userId);
        YearMonth targetYearMonth = YearMonth.from(targetDate);
        SysUserLevelOther sysUserLevelOther = sysUserLevelOtherList.stream().filter(sulo -> {
            if (StringUtils.isNotBlank(sulo.getYearMonth())) {
                YearMonth yearMonth = YearMonth.parse(sulo.getYearMonth(), ymFormatter);
                return targetYearMonth.compareTo(yearMonth) >= 0;
            }
            return false;
        }).sorted(Comparator.comparing(SysUserLevelOther::getYearMonth).reversed()).findFirst().orElse(null);
        if (sysUserLevelOther != null) {
            // 年假可用时长
            BigDecimal yearTime = new BigDecimal(sysUserLevelOther.getAnnualLeaveDays() == null ? 0 : sysUserLevelOther.getAnnualLeaveDays() * 8);
            // 当年的需要等比例扣除(刚转正的情况)
            yearTime = calcRemainingYearTime(user, targetDate, yearTime, internshipLevelList, sysUserLevelOtherList);
            surplusYearTime = yearTime;
        }
 
        return surplusYearTime.doubleValue();
    }
 
    /**
     * 计算剩余年假
     * @param user / 用户信息
     * @param targetDate / 目标日期
     * @param yearTime / 年假总时长
     * @param internshipLevelList / 实习等级记录
     * @param sysUserLevelOtherList / 用户等级记录
     * @return
     */
    public BigDecimal calcRemainingYearTime(User user, LocalDate targetDate, BigDecimal yearTime, List<CmnLevel> internshipLevelList, List<SysUserLevelOther> sysUserLevelOtherList) {
        // 正式入职日期(无实习期按照账户创建时间计算)
        YearMonth firstRegularYearMonth = YearMonth.from(user.getCreateTime().toLocalDateTime());
        if (CollectionUtils.isNotEmpty(internshipLevelList) && CollectionUtils.isNotEmpty(sysUserLevelOtherList)) {
            List<Long> internshipLevelIds = internshipLevelList.stream().map(CmnLevel::getId).collect(Collectors.toList());
            YearMonth internshipYearMonth = sysUserLevelOtherList.stream()
                    .filter(sulo -> internshipLevelIds.contains(sulo.getLevelId()))
                    .map(sulo -> YearMonth.parse(sulo.getYearMonth(), ymFormatter))
                    .sorted(Comparator.reverseOrder()).findFirst().orElse(null);
            if (internshipYearMonth != null) {
                firstRegularYearMonth = sysUserLevelOtherList.stream()
                        .map(sulo -> YearMonth.parse(sulo.getYearMonth(), ymFormatter))
                        .filter(ym -> ym.compareTo(internshipYearMonth) > 0)
                        .sorted().findFirst().orElse(YearMonth.from(user.getCreateTime().toLocalDateTime()));
            }
        }
 
        if (firstRegularYearMonth != null && targetDate.getYear() == firstRegularYearMonth.getYear()) {
            return yearTime.multiply(BigDecimal.valueOf(12).subtract(BigDecimal.valueOf(firstRegularYearMonth.getMonthValue()).subtract(BigDecimal.ONE))).divide(BigDecimal.valueOf(12), 1, RoundingMode.DOWN);
        }
        return yearTime;
    }
 
    /**
     * 调休假扣除方法
     * @param attendanceLeave
     * @param onlyRollback
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public synchronized void overtimeDeduction(AttendanceLeave attendanceLeave, Boolean onlyRollback) {
        // 回退旧分配记录
        OvertimeConsumedRecordQueryCriteria consumedCriteria = new OvertimeConsumedRecordQueryCriteria();
        consumedCriteria.setLeaveId(attendanceLeave.getId());
        List<OvertimeConsumedRecord> overtimeConsumedRecordList = overtimeConsumedRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, consumedCriteria, criteriaBuilder));
        Map<Long, Double> rollbackData = overtimeConsumedRecordList.stream().collect(Collectors.groupingBy(OvertimeConsumedRecord::getOvertimeId, Collectors.summingDouble(OvertimeConsumedRecord::getConsumedDuration)));
        for (Long overtimeId : rollbackData.keySet()) {
            AttendanceOvertime backAttendanceOvertime = attendanceOvertimeRepository.getById(overtimeId);
            backAttendanceOvertime.setRemainingDuration(backAttendanceOvertime.getRemainingDuration() + rollbackData.get(overtimeId));
            attendanceOvertimeRepository.save(backAttendanceOvertime);
        }
        overtimeConsumedRecordRepository.deleteAll(overtimeConsumedRecordList);
 
        if (onlyRollback) {
            return;
        }
 
        // 重新分配调休额度
        List<OvertimeConsumedRecord> consumedRecordList = new ArrayList<>();
        double remainingDuration = attendanceLeave.getLeaveDuration();
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(attendanceLeave.getLeaveStartTime().getTime() / 1000, 0, OffsetDateTime.now().getOffset());
        LocalDateTime startLocalDateTime = localDateTime.minusMonths(2L).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endLocalDateTime = localDateTime.withDayOfMonth(1).plusMonths(1).minusDays(1).withHour(23).withMinute(59).withSecond(59);
 
        // 查询可用调休申请
        AttendanceOvertimeQueryCriteria overtimeCriteria = new AttendanceOvertimeQueryCriteria();
        overtimeCriteria.setApprovalStatus(Constant.OVERTIME_PASS);
        overtimeCriteria.setUserId(attendanceLeave.getUserId());
        overtimeCriteria.setOvertimeStartTime(Arrays.asList(Timestamp.valueOf(startLocalDateTime), Timestamp.valueOf(endLocalDateTime)));
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, overtimeCriteria, criteriaBuilder), Sort.by(Sort.Direction.ASC, "overtimeStartTime"));
 
        AttendanceOvertime currentAttendanceOvertime = new AttendanceOvertime();
 
        // 使用最早的额度依次扣减
        while (remainingDuration > 0 && currentAttendanceOvertime != null) {
            // 查看最早额度
            currentAttendanceOvertime = attendanceOvertimeList.stream().filter(ao -> ao.getRemainingDuration() > 0).findFirst().orElse(null);
 
            if (currentAttendanceOvertime != null) {
                // 获得扣除后剩余待扣除数额
                double deducted = currentAttendanceOvertime.subtractDuration(remainingDuration);
 
                // 生成扣减记录
                OvertimeConsumedRecord consumedRecord = new OvertimeConsumedRecord();
                consumedRecord.setLeaveId(attendanceLeave.getId());
                consumedRecord.setOvertimeId(currentAttendanceOvertime.getId());
                consumedRecord.setUserId(attendanceLeave.getUserId());
                consumedRecord.setConsumedDuration(remainingDuration - deducted);
                consumedRecordList.add(consumedRecord);
 
                remainingDuration = deducted;
            }
        }
 
        // 如果还有未扣减的额度,记录警告或异常
        if (remainingDuration > 0) {
            System.out.println("员工 " + attendanceLeave.getUserId() + " 的额度不足,剩余 " + remainingDuration + "H 未扣减");
            throw new BadRequestException("调休假额度不足");
        }
 
        // 保存记录
        attendanceOvertimeRepository.saveAll(attendanceOvertimeList);
        overtimeConsumedRecordRepository.saveAll(consumedRecordList);
    }
}