yaozc2021
2024-11-22 0799f543beca64dd1c6007e18cb8d8388b2fc391
update
2 files added
53 files modified
27599 ■■■■■ changed files
eladmin-master/eladmin-system/pom.xml 254 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/domain/AttendanceOvertime.java 181 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/repository/AttendanceOvertimeRepository.java 80 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/rest/AttendanceGoOutController.java 252 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/AttendanceGoOutService.java 208 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/AttendanceService.java 245 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/dto/AttendanceOvertimeDto.java 139 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceCardreplacementServiceImpl.java 787 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceGoOutServiceImpl.java 1137 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceLeaveServiceImpl.java 1144 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceOvertimeServiceImpl.java 515 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceServiceImpl.java 1450 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/domain/ProjectProgress.java 256 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/domain/ProjectProgressDetail.java 96 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/ProjectCostService.java 190 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/dto/ProjectProgressDetailDto.java 57 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/dto/ProjectProgressDto.java 165 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/impl/ProjectCostServiceImpl.java 966 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/impl/ProjectProgressServiceImpl.java 648 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/impl/ProjectServiceImpl.java 1621 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/quartz/service/impl/DingTalkServiceImpl.java 1526 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/salary/service/impl/NewSalaryServiceImpl.java 1603 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/domain/Dict.java 106 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/repository/DictRepository.java 86 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/UserServiceImpl.java 3024 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/domain/TaskDaliyMongo.java 160 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/domain/TaskUserMongo.java 174 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/rest/TaskController.java 412 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/TaskService.java 268 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/dto/TaskUserMongoDto.java 214 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskServiceImpl.java 2169 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskUserServiceImpl.java 2705 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/domain/UserLevelWage.java 198 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/repository/UserInsuranceRepository.java 138 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/repository/UserLevelWageRepository.java 128 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/service/dto/UserLevelWageDto.java 139 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/service/impl/UserInsuranceServiceImpl.java 420 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/service/impl/UserLevelWageServiceImpl.java 570 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/resources/config/application-dev.yml 11 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/main/resources/config/application.yml 130 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/test/java/me/zhengjie/AttendanceTest.java 343 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/test/java/me/zhengjie/ProjectTest.java 904 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/src/test/java/me/zhengjie/UserTest.java 1114 ●●●●● patch | view | raw | blame | history
eladmin-master/pom.xml 493 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/api/attendance/attendanceGoOut.js 10 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/router/index.js 6 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/attendance/attendanceGoOut/index.vue 35 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/project/project/index.vue 2 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/project/projectProgress/index.vue 41 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/salary/newSalary/index.vue 2 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/system/configProportion/index.vue 4 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/task/task/index.vue 2 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/task/taskDaliy/index.vue 37 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/task/taskUser/index.vue 18 ●●●●● patch | view | raw | blame | history
eladmin-web-master/src/views/treatment/userLevelWage/index.vue 16 ●●●●● patch | view | raw | blame | history
eladmin-master/eladmin-system/pom.xml
@@ -1,124 +1,130 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>eladmin</artifactId>
        <groupId>me.zhengjie</groupId>
        <version>2.6</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>eladmin-system</artifactId>
    <name>核心模块</name>
    <properties>
        <jjwt.version>0.11.2</jjwt.version>
        <!-- oshi监控需要指定jna版本, 问题详见 https://github.com/oshi/oshi/issues/1040 -->
        <jna.version>5.8.0</jna.version>
    </properties>
    <dependencies>
        <!-- 代码生成模块 -->
        <dependency>
            <groupId>me.zhengjie</groupId>
            <artifactId>eladmin-generator</artifactId>
            <version>2.6</version>
            <exclusions>
                <exclusion>
                    <groupId>me.zhengjie</groupId>
                    <artifactId>eladmin-common</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- tools 模块包含了 common 和 logging 模块 -->
        <dependency>
            <groupId>me.zhengjie</groupId>
            <artifactId>eladmin-tools</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- Spring boot websocket -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <!-- jwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>${jjwt.version}</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>${jjwt.version}</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>${jjwt.version}</version>
        </dependency>
        <!-- quartz -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
        </dependency>
        <!-- linux的管理 -->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>
        <!-- 获取系统信息 -->
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-core</artifactId>
            <version>6.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>alibaba-dingtalk-service-sdk</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>nl.basjes.parse.useragent</groupId>
            <artifactId>yauaa</artifactId>
            <version>5.23</version>
        </dependency>
        <!-- 消息队列 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
    </dependencies>
    <!-- 打包 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- 跳过单元测试 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>eladmin</artifactId>
        <groupId>me.zhengjie</groupId>
        <version>2.6</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>eladmin-system</artifactId>
    <name>核心模块</name>
    <properties>
        <jjwt.version>0.11.2</jjwt.version>
        <!-- oshi监控需要指定jna版本, 问题详见 https://github.com/oshi/oshi/issues/1040 -->
        <jna.version>5.8.0</jna.version>
    </properties>
    <dependencies>
        <!-- 代码生成模块 -->
        <dependency>
            <groupId>me.zhengjie</groupId>
            <artifactId>eladmin-generator</artifactId>
            <version>2.6</version>
            <exclusions>
                <exclusion>
                    <groupId>me.zhengjie</groupId>
                    <artifactId>eladmin-common</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- tools 模块包含了 common 和 logging 模块 -->
        <dependency>
            <groupId>me.zhengjie</groupId>
            <artifactId>eladmin-tools</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- Spring boot websocket -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <!-- jwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>${jjwt.version}</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>${jjwt.version}</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>${jjwt.version}</version>
        </dependency>
        <!-- quartz -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
        </dependency>
        <!-- linux的管理 -->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>
        <!-- 获取系统信息 -->
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-core</artifactId>
            <version>6.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>alibaba-dingtalk-service-sdk</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>nl.basjes.parse.useragent</groupId>
            <artifactId>yauaa</artifactId>
            <version>5.23</version>
        </dependency>
        <!-- 消息队列 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.14</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <!-- 打包 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- 跳过单元测试 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/domain/AttendanceOvertime.java
@@ -1,88 +1,93 @@
/*
*  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.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import me.zhengjie.base.BaseEntity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @website https://eladmin.vip
* @description /
* @author weicd
* @date 2023-11-24
**/
@Entity
@Data
@Table(name="attendance_overtime")
public class AttendanceOvertime extends BaseEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "`id`")
    @ApiModelProperty(value = "ID")
    private Long id;
    @Column(name = "`user_id`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "用户ID")
    private Long userId;
    @Column(name = "`approval_user_id`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "审批用户ID")
    private Long approvalUserId;
    @Column(name = "`overtime_start_time`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "加班开始时间")
    private Timestamp overtimeStartTime;
    @Column(name = "`overtime_end_time`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "加班结束时间")
    private Timestamp overtimeEndTime;
    @Column(name = "`overtime_duration`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "加班时长")
    private Double overtimeDuration;
    @Column(name = "`approval_status`")
    @ApiModelProperty(value = "审批状态")
    private String approvalStatus;
    @Column(name = "`approval_description`")
    @ApiModelProperty(value = "审批说明")
    private String approvalDescription;
    @Column(name = "`remarks`")
    @ApiModelProperty(value = "备注")
    private String remarks;
    public void copy(AttendanceOvertime source){
        BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
    }
}
/*
*  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.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import me.zhengjie.base.BaseEntity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @website https://eladmin.vip
* @description /
* @author weicd
* @date 2023-11-24
**/
@Entity
@Data
@Table(name="attendance_overtime")
public class AttendanceOvertime extends BaseEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "`id`")
    @ApiModelProperty(value = "ID")
    private Long id;
    @Column(name = "`user_id`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "用户ID")
    private Long userId;
    @Column(name = "`approval_user_id`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "审批用户ID")
    private Long approvalUserId;
    @Column(name = "`overtime_start_time`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "加班开始时间")
    private Timestamp overtimeStartTime;
    @Column(name = "`overtime_end_time`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "加班结束时间")
    private Timestamp overtimeEndTime;
    @Column(name = "`overtime_duration`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "加班时长")
    private Double overtimeDuration;
    @Column(name = "`date_type`",nullable = false)
    @NotBlank
    @ApiModelProperty(value = "日期类型")
    private String dateType;
    @Column(name = "`approval_status`")
    @ApiModelProperty(value = "审批状态")
    private String approvalStatus;
    @Column(name = "`approval_description`")
    @ApiModelProperty(value = "审批说明")
    private String approvalDescription;
    @Column(name = "`remarks`")
    @ApiModelProperty(value = "备注")
    private String remarks;
    public void copy(AttendanceOvertime source){
        BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/repository/AttendanceOvertimeRepository.java
@@ -1,40 +1,42 @@
/*
*  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.repository;
import me.zhengjie.modules.attendance.domain.AttendanceOvertime;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDateTime;
import java.util.List;
/**
* @website https://eladmin.vip
* @author weicd
* @date 2023-11-24
**/
public interface AttendanceOvertimeRepository extends JpaRepository<AttendanceOvertime, Long>, JpaSpecificationExecutor<AttendanceOvertime> {
    @Query(value = "SELECT SUM(overtime_duration) from attendance_overtime where user_id = ?1 and overtime_start_time >= ?2 and overtime_end_time < ?3 and approval_status in ('overtime_pass')", nativeQuery = true)
    Double findByUserIdAndYearMonth(Long userId, LocalDateTime startDate, LocalDateTime endDate);
    @Query(value = "SELECT * from attendance_overtime where user_id = ?1 and overtime_start_time >= ?2 and overtime_end_time < ?3 and approval_status in ('overtime_pass')", nativeQuery = true)
    List<AttendanceOvertime> findByUserIdAndDate(Long userId, LocalDateTime startDate, LocalDateTime endDate);
    List<AttendanceOvertime> findByUserId(Long userId);
/*
*  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.repository;
import me.zhengjie.modules.attendance.domain.AttendanceOvertime;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDateTime;
import java.util.List;
/**
* @website https://eladmin.vip
* @author weicd
* @date 2023-11-24
**/
public interface AttendanceOvertimeRepository extends JpaRepository<AttendanceOvertime, Long>, JpaSpecificationExecutor<AttendanceOvertime> {
    @Query(value = "SELECT SUM(overtime_duration) from attendance_overtime where user_id = ?1 and overtime_start_time >= ?2 and overtime_end_time < ?3 and approval_status in ('overtime_pass')", nativeQuery = true)
    Double findByUserIdAndYearMonth(Long userId, LocalDateTime startDate, LocalDateTime endDate);
    @Query(value = "SELECT * from attendance_overtime where user_id = ?1 and overtime_start_time >= ?2 and overtime_end_time < ?3 and approval_status in ('overtime_pass')", nativeQuery = true)
    List<AttendanceOvertime> findByUserIdAndDate(Long userId, LocalDateTime startDate, LocalDateTime endDate);
    List<AttendanceOvertime> findByUserId(Long userId);
    List<AttendanceOvertime> findByUserIdAndApprovalStatus(Long userId, String overtimePass);
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/rest/AttendanceGoOutController.java
@@ -1,124 +1,130 @@
/*
*  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.rest;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.attendance.domain.AgreeUpdateRequest;
import me.zhengjie.modules.attendance.domain.AttendanceBusinessTravel;
import me.zhengjie.modules.attendance.domain.AttendanceGoOut;
import me.zhengjie.modules.attendance.domain.AttendanceLeave;
import me.zhengjie.modules.attendance.service.AttendanceGoOutService;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutQueryCriteria;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @author wcd
* @date 2023-01-04
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "考勤外出管理")
@RequestMapping("/api/attendanceGoOut")
public class AttendanceGoOutController {
    private final AttendanceGoOutService attendanceGoOutService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('attendanceGoOut:list')")
    public void exportAttendanceGoOut(HttpServletResponse response, AttendanceGoOutQueryCriteria criteria) throws IOException {
        attendanceGoOutService.download(attendanceGoOutService.queryAll(criteria), response);
    }
    @GetMapping
    @Log("查询考勤外出")
    @ApiOperation("查询考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:list')")
    public ResponseEntity<Object> queryAttendanceGoOut(AttendanceGoOutQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(attendanceGoOutService.queryAll(criteria,pageable),HttpStatus.OK);
    }
    @GetMapping(value = "/all")
    @Log("查询考勤外出")
    @ApiOperation("查询考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:list')")
    public ResponseEntity<Object> queryAttendanceGoOut(AttendanceGoOutQueryCriteria criteria){
        return new ResponseEntity<>(attendanceGoOutService.queryAll(criteria),HttpStatus.OK);
    }
    @PostMapping
    @Log("新增考勤外出")
    @ApiOperation("新增考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:add')")
    public ResponseEntity<Object> createAttendanceGoOut(@Validated @RequestBody AttendanceGoOut resources) throws Exception {
        return new ResponseEntity<>(attendanceGoOutService.create(resources),HttpStatus.CREATED);
    }
    @PutMapping
    @Log("修改考勤外出")
    @ApiOperation("修改考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:edit')")
    public ResponseEntity<Object> updateAttendanceGoOut(@Validated @RequestBody AttendanceGoOut resources){
        attendanceGoOutService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    @DeleteMapping
    @Log("删除考勤外出")
    @ApiOperation("删除考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:del')")
    public ResponseEntity<Object> deleteAttendanceGoOut(@RequestBody Long[] ids) {
        attendanceGoOutService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    @PostMapping(value = "/getRemainingTime")
    @Log("获取外出时长")
    @ApiOperation("获取外出时长")
    public ResponseEntity<Object> getRemainingTime(@Validated @RequestBody AttendanceGoOut resources){
        return new ResponseEntity<>(attendanceGoOutService.getRemainingTime(resources),HttpStatus.CREATED);
    }
    @PutMapping(value = "/approve")
    @Log("审核/撤销功能")
    @ApiOperation("审核/撤销功能")
    @PreAuthorize("@el.check('attendanceGoOut:approve')")
    public ResponseEntity<Object> checkApprove(@Validated @RequestBody AttendanceGoOut resources) throws Exception {
        attendanceGoOutService.updateApprove(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    @PutMapping(value = "/updateAgree")
    @Log("批量审核")
    @ApiOperation("批量审核")
    @PreAuthorize("@el.check('attendanceGoOut:updateAgree')")
    public ResponseEntity<Object> editIsAgree(@Validated @RequestBody AgreeUpdateRequest request) throws Exception {
        attendanceGoOutService.updateAgree(request);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
/*
*  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.rest;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.attendance.domain.AgreeUpdateRequest;
import me.zhengjie.modules.attendance.domain.AttendanceBusinessTravel;
import me.zhengjie.modules.attendance.domain.AttendanceGoOut;
import me.zhengjie.modules.attendance.domain.AttendanceLeave;
import me.zhengjie.modules.attendance.service.AttendanceGoOutService;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutQueryCriteria;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @author wcd
* @date 2023-01-04
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "考勤外出管理")
@RequestMapping("/api/attendanceGoOut")
public class AttendanceGoOutController {
    private final AttendanceGoOutService attendanceGoOutService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('attendanceGoOut:list')")
    public void exportAttendanceGoOut(HttpServletResponse response, AttendanceGoOutQueryCriteria criteria) throws IOException {
        attendanceGoOutService.download(attendanceGoOutService.queryAll(criteria), response);
    }
    @GetMapping
    @Log("查询考勤外出")
    @ApiOperation("查询考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:list')")
    public ResponseEntity<Object> queryAttendanceGoOut(AttendanceGoOutQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(attendanceGoOutService.queryAll(criteria,pageable),HttpStatus.OK);
    }
    @GetMapping(value = "/all")
    @Log("查询考勤外出")
    @ApiOperation("查询考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:list')")
    public ResponseEntity<Object> queryAttendanceGoOut(AttendanceGoOutQueryCriteria criteria){
        return new ResponseEntity<>(attendanceGoOutService.queryAll(criteria),HttpStatus.OK);
    }
    @PostMapping
    @Log("新增考勤外出")
    @ApiOperation("新增考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:add')")
    public ResponseEntity<Object> createAttendanceGoOut(@Validated @RequestBody AttendanceGoOut resources) throws Exception {
        return new ResponseEntity<>(attendanceGoOutService.create(resources),HttpStatus.CREATED);
    }
    @PutMapping
    @Log("修改考勤外出")
    @ApiOperation("修改考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:edit')")
    public ResponseEntity<Object> updateAttendanceGoOut(@Validated @RequestBody AttendanceGoOut resources){
        attendanceGoOutService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    @DeleteMapping
    @Log("删除考勤外出")
    @ApiOperation("删除考勤外出")
    @PreAuthorize("@el.check('attendanceGoOut:del')")
    public ResponseEntity<Object> deleteAttendanceGoOut(@RequestBody Long[] ids) {
        attendanceGoOutService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    @PostMapping(value = "/getRemainingTime")
    @Log("获取外出时长")
    @ApiOperation("获取外出时长")
    public ResponseEntity<Object> getRemainingTime(@Validated @RequestBody AttendanceGoOut resources){
        return new ResponseEntity<>(attendanceGoOutService.getRemainingTime(resources),HttpStatus.CREATED);
    }
    @PutMapping(value = "/reflashTime")
    public ResponseEntity<Object> getRemainingTime(@RequestBody Long[] ids) {
        attendanceGoOutService.reflashTime(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    @PutMapping(value = "/approve")
    @Log("审核/撤销功能")
    @ApiOperation("审核/撤销功能")
    @PreAuthorize("@el.check('attendanceGoOut:approve')")
    public ResponseEntity<Object> checkApprove(@Validated @RequestBody AttendanceGoOut resources) throws Exception {
        attendanceGoOutService.updateApprove(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    @PutMapping(value = "/updateAgree")
    @Log("批量审核")
    @ApiOperation("批量审核")
    @PreAuthorize("@el.check('attendanceGoOut:updateAgree')")
    public ResponseEntity<Object> editIsAgree(@Validated @RequestBody AgreeUpdateRequest request) throws Exception {
        attendanceGoOutService.updateAgree(request);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/AttendanceGoOutService.java
@@ -1,104 +1,106 @@
/*
*  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;
import me.zhengjie.modules.attendance.domain.AgreeUpdateRequest;
import me.zhengjie.modules.attendance.domain.AttendanceGoOut;
import me.zhengjie.modules.attendance.domain.AttendanceLeave;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @description 服务接口
* @author wcd
* @date 2023-01-04
**/
public interface AttendanceGoOutService {
    /**
    * 查询数据分页
    * @param criteria 条件
    * @param pageable 分页参数
    * @return Map<String,Object>
    */
    Map<String,Object> queryAll(AttendanceGoOutQueryCriteria criteria, Pageable pageable);
    /**
    * 查询所有数据不分页
    * @param criteria 条件参数
    * @return List<AttendanceGoOutDto>
    */
    List<AttendanceGoOutDto> queryAll(AttendanceGoOutQueryCriteria criteria);
    /**
     * 根据ID查询
     * @param id ID
     * @return AttendanceGoOutDto
     */
    AttendanceGoOutDto findById(Long id);
    /**
    * 创建
    * @param resources /
    * @return AttendanceGoOutDto
    */
    AttendanceGoOutDto create(AttendanceGoOut resources) throws Exception;
    /**
    * 编辑
    * @param resources /
    */
    void update(AttendanceGoOut resources);
    /**
    * 多选删除
    * @param ids /
    */
    void deleteAll(Long[] ids);
    /**
    * 导出数据
    * @param all 待导出的数据
    * @param response /
    * @throws IOException /
    */
    void download(List<AttendanceGoOutDto> all, HttpServletResponse response) throws IOException;
    /**
     * 获取时长
     * @param attendanceGoOut
     * @return
     */
    Double getRemainingTime(AttendanceGoOut attendanceGoOut);
    /**
     * 审核功能
     * @param resources /
     */
    void updateApprove(AttendanceGoOut resources) throws Exception;
    /**
     * 批量审核(外出)
     * @param
     */
    void updateAgree(AgreeUpdateRequest request) throws Exception;
/*
*  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;
import me.zhengjie.modules.attendance.domain.AgreeUpdateRequest;
import me.zhengjie.modules.attendance.domain.AttendanceGoOut;
import me.zhengjie.modules.attendance.domain.AttendanceLeave;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @description 服务接口
* @author wcd
* @date 2023-01-04
**/
public interface AttendanceGoOutService {
    /**
    * 查询数据分页
    * @param criteria 条件
    * @param pageable 分页参数
    * @return Map<String,Object>
    */
    Map<String,Object> queryAll(AttendanceGoOutQueryCriteria criteria, Pageable pageable);
    /**
    * 查询所有数据不分页
    * @param criteria 条件参数
    * @return List<AttendanceGoOutDto>
    */
    List<AttendanceGoOutDto> queryAll(AttendanceGoOutQueryCriteria criteria);
    /**
     * 根据ID查询
     * @param id ID
     * @return AttendanceGoOutDto
     */
    AttendanceGoOutDto findById(Long id);
    /**
    * 创建
    * @param resources /
    * @return AttendanceGoOutDto
    */
    AttendanceGoOutDto create(AttendanceGoOut resources) throws Exception;
    /**
    * 编辑
    * @param resources /
    */
    void update(AttendanceGoOut resources);
    /**
    * 多选删除
    * @param ids /
    */
    void deleteAll(Long[] ids);
    /**
    * 导出数据
    * @param all 待导出的数据
    * @param response /
    * @throws IOException /
    */
    void download(List<AttendanceGoOutDto> all, HttpServletResponse response) throws IOException;
    /**
     * 获取时长
     * @param attendanceGoOut
     * @return
     */
    Double getRemainingTime(AttendanceGoOut attendanceGoOut);
    void reflashTime(Long[] ids);
    /**
     * 审核功能
     * @param resources /
     */
    void updateApprove(AttendanceGoOut resources) throws Exception;
    /**
     * 批量审核(外出)
     * @param
     */
    void updateAgree(AgreeUpdateRequest request) throws Exception;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/AttendanceService.java
@@ -1,119 +1,128 @@
/*
*  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;
import me.zhengjie.modules.attendance.domain.Attendance;
import me.zhengjie.modules.attendance.domain.Calculate;
import me.zhengjie.modules.attendance.service.dto.AttendanceDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @description 服务接口
* @author wcd
* @date 2022-12-14
**/
public interface AttendanceService {
    /**
    * 查询数据分页
    * @param criteria 条件
    * @param pageable 分页参数
    * @return Map<String,Object>
    */
    Map<String,Object> queryAll(AttendanceQueryCriteria criteria, Pageable pageable);
    /**
    * 查询所有数据不分页
    * @param criteria 条件参数
    * @return List<AttendanceDto>
    */
    List<AttendanceDto> queryAll(AttendanceQueryCriteria criteria);
    /**
     * 根据ID查询
     * @param id ID
     * @return AttendanceDto
     */
    AttendanceDto findById(Long id);
    /**
    * 创建
    * @param resources /
    * @return AttendanceDto
    */
    AttendanceDto create(Attendance resources);
    /**
    * 编辑
    * @param resources /
    */
    void update(Attendance resources);
    /**
     * 计算时长(小时)
     * @param userId
     * @return
     */
    Integer calculateTimes(Calculate calculate, Long userId);
    /**
     * 计算时长(天)
     *
     * @return
     */
    Integer calculateDays(Calculate calculate);
    /**
    * 多选删除
    * @param ids /
    */
    void deleteAll(Long[] ids);
    /**
    * 导出数据
    * @param all 待导出的数据
    * @param response /
    * @throws IOException /
    */
    void download(List<AttendanceDto> all, HttpServletResponse response) throws IOException;
    Double queryAttendanceHours(Long userId, String date);
    /**
     * 查询某月出勤小时数
     * @param criteria 条件参数
     * @return List<AttendanceDto>
     */
    Double queryAttendanceHours(AttendanceQueryCriteria criteria);
    void getUserMakeUpCard(String userId);
    /**
     * 补充考勤信息
     * @param attendance
     */
    void addAttendanceInfo(Attendance attendance) throws Exception;
/*
*  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;
import me.zhengjie.modules.attendance.domain.Attendance;
import me.zhengjie.modules.attendance.domain.Calculate;
import me.zhengjie.modules.attendance.service.dto.AttendanceDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @description 服务接口
* @author wcd
* @date 2022-12-14
**/
public interface AttendanceService {
    /**
    * 查询数据分页
    * @param criteria 条件
    * @param pageable 分页参数
    * @return Map<String,Object>
    */
    Map<String,Object> queryAll(AttendanceQueryCriteria criteria, Pageable pageable);
    /**
    * 查询所有数据不分页
    * @param criteria 条件参数
    * @return List<AttendanceDto>
    */
    List<AttendanceDto> queryAll(AttendanceQueryCriteria criteria);
    /**
     * 根据ID查询
     * @param id ID
     * @return AttendanceDto
     */
    AttendanceDto findById(Long id);
    /**
    * 创建
    * @param resources /
    * @return AttendanceDto
    */
    AttendanceDto create(Attendance resources);
    /**
    * 编辑
    * @param resources /
    */
    void update(Attendance resources);
    /**
     * 计算时长(小时)
     * @param userId
     * @return
     */
    Integer calculateTimes(Calculate calculate, Long userId);
    /**
     * 计算时长(天)
     *
     * @return
     */
    Integer calculateDays(Calculate calculate);
    /**
    * 多选删除
    * @param ids /
    */
    void deleteAll(Long[] ids);
    /**
    * 导出数据
    * @param all 待导出的数据
    * @param response /
    * @throws IOException /
    */
    void download(List<AttendanceDto> all, HttpServletResponse response) throws IOException;
    Double queryAttendanceHours(Long userId, String date);
    /**
     * 查询某月出勤小时数
     * @param criteria 条件参数
     * @return List<AttendanceDto>
     */
    Double queryAttendanceHours(AttendanceQueryCriteria criteria);
    Double queryAttendanceHolidaysOverTimeHours(AttendanceQueryCriteria criteria);
    /**
     * 查询某月平日加班小时数
     * @param criteria 条件参数
     * @return List<AttendanceDto>
     */
    Double queryAttendanceOverTimeHours(AttendanceQueryCriteria criteria);
    void getUserMakeUpCard(String userId);
    /**
     * 补充考勤信息
     * @param attendance
     */
    void addAttendanceInfo(Attendance attendance) throws Exception;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/dto/AttendanceOvertimeDto.java
@@ -1,69 +1,72 @@
/*
*  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.dto;
import lombok.Data;
import me.zhengjie.base.BaseDTO;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @website https://eladmin.vip
* @description /
* @author weicd
* @date 2023-11-24
**/
@Data
public class AttendanceOvertimeDto extends BaseDTO implements Serializable {
    /** ID */
    private Long id;
    /** 用户ID */
    private Long userId;
    /** 审批用户ID */
    private Long approvalUserId;
    /** 加班开始时间 */
    private Timestamp overtimeStartTime;
    /** 加班结束时间 */
    private Timestamp overtimeEndTime;
    /** 加班时长 */
    private Double overtimeDuration;
    /** 加班时长单位 */
    private String overtimeDurationUnit;
    /** 审批状态 */
    private String approvalStatus;
    /** 审批说明 */
    private String approvalDescription;
    /** 备注 */
    private String remarks;
    /** 用户名 */
    private String userName;
    /** 审批用户名 */
    private String appUserName;
/*
*  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.dto;
import lombok.Data;
import me.zhengjie.base.BaseDTO;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @website https://eladmin.vip
* @description /
* @author weicd
* @date 2023-11-24
**/
@Data
public class AttendanceOvertimeDto extends BaseDTO implements Serializable {
    /** ID */
    private Long id;
    /** 用户ID */
    private Long userId;
    /** 审批用户ID */
    private Long approvalUserId;
    /** 加班开始时间 */
    private Timestamp overtimeStartTime;
    /** 加班结束时间 */
    private Timestamp overtimeEndTime;
    /** 加班时长 */
    private Double overtimeDuration;
    /** 加班时长单位 */
    private String overtimeDurationUnit;
    /** 日期类型 */
    private String dateType;
    /** 审批状态 */
    private String approvalStatus;
    /** 审批说明 */
    private String approvalDescription;
    /** 备注 */
    private String remarks;
    /** 用户名 */
    private String userName;
    /** 审批用户名 */
    private String appUserName;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceCardreplacementServiceImpl.java
@@ -1,366 +1,423 @@
/*
*  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 me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.AgreeUpdateRequest;
import me.zhengjie.modules.attendance.domain.Attendance;
import me.zhengjie.modules.attendance.domain.AttendanceCardreplacement;
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
import me.zhengjie.modules.attendance.service.dto.AttendanceDto;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.SysConfigProportion;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.modules.system.repository.SysConfigProportionRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.attendance.repository.AttendanceCardreplacementRepository;
import me.zhengjie.modules.attendance.service.AttendanceCardreplacementService;
import me.zhengjie.modules.attendance.service.dto.AttendanceCardreplacementDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceCardreplacementQueryCriteria;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceCardreplacementMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.function.Function;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author wcd
* @date 2022-12-21
**/
@Service
@RequiredArgsConstructor
public class AttendanceCardreplacementServiceImpl implements AttendanceCardreplacementService {
    private final AttendanceCardreplacementRepository attendanceCardreplacementRepository;
    private final AttendanceCardreplacementMapper attendanceCardreplacementMapper;
    private final UserRepository userRepository;
    private final OpaiDingTalkService opaiDingTalkService;
    private final RoleRepository roleRepository;
    private final AttendanceRepository attendanceRepository;
    private final SysConfigProportionRepository sysConfigProportionRepository;
    private final DictDetailRepository dictDetailRepository;
    @Override
    public Map<String,Object> queryAll(AttendanceCardreplacementQueryCriteria criteria, Pageable pageable){
        //查询当前登录人
        User user = userRepository.findById(SecurityUtils.getCurrentUserId()).get();
        Page<AttendanceCardreplacement> page = attendanceCardreplacementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<AttendanceCardreplacement, AttendanceCardreplacementDto> func = new Function<AttendanceCardreplacement,AttendanceCardreplacementDto >(){
            @Override
            public AttendanceCardreplacementDto apply(AttendanceCardreplacement attendanceCardreplacement) {
                // 将实体类转换成DTO
                AttendanceCardreplacementDto attendanceCardreplacementDto = attendanceCardreplacementMapper.toDto(attendanceCardreplacement);
                //查询申请人信息
                User user = userRepository.findById(attendanceCardreplacementDto.getUserId()).orElseGet(User::new);
                attendanceCardreplacementDto.setUserName(user.getNickName());
                //查询申请人信息
                User appUser = userRepository.findById(attendanceCardreplacementDto.getApprovalUserId()).orElseGet(User::new);
                attendanceCardreplacementDto.setAppUserName(appUser.getNickName());
                return attendanceCardreplacementDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<AttendanceCardreplacementDto> queryAll(AttendanceCardreplacementQueryCriteria criteria) {
        List<AttendanceCardreplacementDto> attendanceCardreplacementList = attendanceCardreplacementMapper.toDto(attendanceCardreplacementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        attendanceCardreplacementList.forEach(attendanceCardreplacementDto -> {
            //查询申请人信息
            User user = userRepository.findById(attendanceCardreplacementDto.getUserId()).orElseGet(User::new);
            attendanceCardreplacementDto.setUserName(user.getNickName());
            //查询申请人信息
            User appUser = userRepository.findById(attendanceCardreplacementDto.getApprovalUserId()).orElseGet(User::new);
            attendanceCardreplacementDto.setAppUserName(appUser.getNickName());
        });
        return attendanceCardreplacementList;
    }
    @Override
    @Transactional
    public AttendanceCardreplacementDto findById(Long id) {
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findById(id).orElseGet(AttendanceCardreplacement::new);
        ValidationUtil.isNull(attendanceCardreplacement.getId(),"AttendanceCardreplacement","id",id);
        return attendanceCardreplacementMapper.toDto(attendanceCardreplacement);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceCardreplacementDto create(AttendanceCardreplacement resources) throws Exception {
        //查询补卡次数(每个月5次)
        getCardreplacement(resources.getCardReplacementTime(), resources.getUserId());
        //查询补卡记录是否存在
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findByUserIdAndCardReplacementTime(resources.getUserId(),resources.getCardReplacementTime());
        if(ObjectUtils.isNotEmpty(attendanceCardreplacement)) {
            throw new BadRequestException("补卡记录已存在");
        }
        //查询考勤表是否有记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String attDate = sdf.format(resources.getCardReplacementTime());
        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
        if(ObjectUtils.isEmpty(attendance)){
            throw new BadRequestException("考勤记录不存在");
        }
        resources.setApprovalStatus(Constant.CARD_APPROVE_STATUS_REVIEWED);
        //发送给审批者
        List<String> sendList = new ArrayList<>();
        //查询申请人信息
        User user = userRepository.getOne(resources.getUserId());
        //查询审批者信息
        User appUser = userRepository.getOne(resources.getApprovalUserId());
        sendList.add(appUser.getDingding());
        opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了补卡审批,请登录PMS系统处理", "card");
        return attendanceCardreplacementMapper.toDto(attendanceCardreplacementRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AttendanceCardreplacement resources) {
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findById(resources.getId()).orElseGet(AttendanceCardreplacement::new);
        ValidationUtil.isNull( attendanceCardreplacement.getId(),"AttendanceCardreplacement","id",resources.getId());
        attendanceCardreplacement.copy(resources);
        //查询考勤表是否有记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String attDate = sdf.format(resources.getCardReplacementTime());
        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
        if(ObjectUtils.isEmpty(attendance)){
            throw new BadRequestException("考勤记录不存在");
        }
        //查询补卡次数(每个月5次)
        getCardreplacement(resources.getCardReplacementTime(), resources.getUserId());
        //获取当前登入人信息
        User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
        //审核通过或者退回不能删除
        if(attendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE) || attendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REFUSE)){
            throw new BadRequestException("审核通过或退回的不能进行修改");
        }
        attendanceCardreplacementRepository.save(attendanceCardreplacement);
    }
    /**
     * 查询剩余补卡次数
     */
    public void getCardreplacement(Timestamp cardReplacementTime, Long userId){
        // 日期时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 补卡时间字符串
        String cardReplacementTimeStr = sdf.format(cardReplacementTime);
        // 查询当月的补卡记录的条数
        Integer count = attendanceCardreplacementRepository.count(userId, cardReplacementTimeStr.substring(0,7));
        // 查询配置表的每月补卡次数
        SysConfigProportion sysConfigProportion = sysConfigProportionRepository.findByTitle("每月可补卡次数");
        if(count >= sysConfigProportion.getProportion()){
            throw new BadRequestException("补卡次数用尽,请联系管理员");
        }
    }
    /**
     * 审核功能
     * @param resources
     */
    @Override
    public void updateApprove(AttendanceCardreplacement resources) {
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findById(resources.getId()).orElseGet(AttendanceCardreplacement::new);
        ValidationUtil.isNull(attendanceCardreplacement.getId(), "AttendanceCardreplacement", "id", resources.getId());
        attendanceCardreplacement.copy(resources);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String attDate = sdf.format(resources.getCardReplacementTime());
        // 根据userId和日期查询考勤记录表
        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(), attDate.substring(0, 10));
        // 判断是上班补卡还是下班补卡
        if (resources.getCardReplacementDistinguish().equals(Constant.CARD_REPLACEMENT_DIFFERENTIATION_GOON)) {
            // 通过
            if (resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE)) {
                // set考勤打卡时间和打卡状态
                attendance.setActualWorkStartTime(resources.getCardReplacementTime());
                attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NORMAL);
                attendance.setStartLocationResults(Constant.LOCATION_RESULTS_NORMAL);
            }else if (resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REFUSE)){
                attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
                attendance.setStartLocationResults(Constant.LOCATION_RESULTS_NOTSIGNED);
            }
        } else {
            // 通过
            if (resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE)) {
                // set考勤打卡时间和打卡状态
                attendance.setActualWorkEndTime(resources.getCardReplacementTime());
                attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NORMAL);
                attendance.setEndLocationResults(Constant.LOCATION_RESULTS_NORMAL);
            }else if (resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REFUSE)){
                attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
                attendance.setEndLocationResults(Constant.LOCATION_RESULTS_NOTSIGNED);
            }
        }
        attendanceRepository.save(attendance);
        attendanceCardreplacementRepository.save(attendanceCardreplacement);
    }
    /**
     * 补卡批量审核
     * @param
     */
    @Override
    public void updateAgree(AgreeUpdateRequest request) {
        // 循环ID列表
        for (Long id : request.getIds()) {
            AttendanceCardreplacement AttendanceCardreplacement = attendanceCardreplacementRepository.findById(id).orElseGet(AttendanceCardreplacement::new);
            ValidationUtil.isNull(AttendanceCardreplacement.getId(), "AttendanceCardreplacement", "id", id);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String attDate = sdf.format(AttendanceCardreplacement.getCardReplacementTime());
            // 根据userId和日期查询考勤记录表
            Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(AttendanceCardreplacement.getUserId(), attDate.substring(0, 10));
            // 判断是上班补卡还是下班补卡
            if (AttendanceCardreplacement.getCardReplacementDistinguish().equals(Constant.CARD_REPLACEMENT_DIFFERENTIATION_GOON)) {
                // 通过
                if (AttendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REVIEWED) && request.getNum().equals(Long.valueOf(1))) {
                    // set考勤打卡时间和打卡状态
                    attendance.setActualWorkStartTime(AttendanceCardreplacement.getCardReplacementTime());
                    attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NORMAL);
                    attendance.setStartLocationResults(Constant.LOCATION_RESULTS_NORMAL);
                    AttendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_AGREE);
                }else if (AttendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REVIEWED) && request.getNum().equals(Long.valueOf(2))){
                    attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
                    attendance.setStartLocationResults(Constant.LOCATION_RESULTS_NOTSIGNED);
                    AttendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_REFUSE);
                }
            } else {
                // 通过
                if (AttendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REVIEWED) && request.getNum().equals(Long.valueOf(1))) {
                    // set考勤打卡时间和打卡状态
                    attendance.setActualWorkEndTime(AttendanceCardreplacement.getCardReplacementTime());
                    attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NORMAL);
                    attendance.setEndLocationResults(Constant.LOCATION_RESULTS_NORMAL);
                    AttendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_AGREE);
                }else if (AttendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REVIEWED) && request.getNum().equals(Long.valueOf(2))){
                    attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
                    attendance.setEndLocationResults(Constant.LOCATION_RESULTS_NOTSIGNED);
                    AttendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_REFUSE);
                }
            }
            attendanceRepository.save(attendance);
            attendanceCardreplacementRepository.save(AttendanceCardreplacement);
        }
    }
    /**
     * 补卡撤销
     * @param resources
     */
    @Override
    public void cardRevoke(AttendanceCardreplacement resources) {
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findById(resources.getId()).orElseGet(AttendanceCardreplacement::new);
        ValidationUtil.isNull( attendanceCardreplacement.getId(),"AttendanceCardreplacement","id",resources.getId());
        attendanceCardreplacement.copy(resources);
        //如果审批状态为已通过,补卡次数加回来?
        if(resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE)) {
        }
        attendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_REVIEWED);
        String sfd = resources.getCardReplacementTime().toLocalDateTime().toString().substring(0,10);
        //查询考勤记录状态改为等待
        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),resources.getCardReplacementTime().toLocalDateTime().toString().substring(0,10));
        // 判断是上班补卡还是下班补卡
        if (resources.getCardReplacementDistinguish().equals(Constant.CARD_REPLACEMENT_DIFFERENTIATION_GOON)) {
            attendance.setActualWorkStartTime(null);
            attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
            attendance.setStartLocationResults(null);
        }else{
            attendance.setActualWorkEndTime(null);
            attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
            attendance.setEndLocationResults(null);
        }
        attendanceCardreplacementRepository.save(attendanceCardreplacement);
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //获取当前登入人信息
            User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
            Role role = user.getRoles().iterator().next();
            //根据id查询记录
            Optional<AttendanceCardreplacement> attendanceCardreplacement = attendanceCardreplacementRepository.findById(id);
            //除超管、总经理只能删除自己信息
            if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
                if (!Long.valueOf(attendanceCardreplacement.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            //审核通过或者退回不能删除
            if(attendanceCardreplacement.get().getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE) || attendanceCardreplacement.get().getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REFUSE)){
                throw new BadRequestException("审核通过或退回的不能进行删除");
            }
            attendanceCardreplacementRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<AttendanceCardreplacementDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceCardreplacementDto attendanceCardreplacement : all) {
            String attCardreplacementType = attendanceCardreplacement.getApprovalStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.CARD_APPROVE_STATUS, attendanceCardreplacement.getApprovalStatus()).getLabel() : "";
            String attCardReplacementDistinguish = attendanceCardreplacement.getCardReplacementDistinguish() != null ? dictDetailRepository.findByDictNameAndValue(Constant.CARD_REPLACEMENT_DIFFERENTIATION, attendanceCardreplacement.getCardReplacementDistinguish()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请者", attendanceCardreplacement.getUserName());
            map.put("审批者", attendanceCardreplacement.getAppUserName());
            map.put("补卡时间", attendanceCardreplacement.getCardReplacementTime());
            map.put("补卡原因", attendanceCardreplacement.getCardReplacementReason());
            map.put("审批状态", attCardreplacementType);
            map.put("审批说明", attendanceCardreplacement.getApprovalDescription());
            map.put("补卡区分", attCardReplacementDistinguish);
            map.put("备注", attendanceCardreplacement.getRemarks());
            map.put("创建者", attendanceCardreplacement.getCreateBy());
            map.put("创建时间", attendanceCardreplacement.getCreateTime());
            map.put("更新者", attendanceCardreplacement.getUpdateBy());
            map.put("更新时间", attendanceCardreplacement.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
/*
*  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 me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.AgreeUpdateRequest;
import me.zhengjie.modules.attendance.domain.Attendance;
import me.zhengjie.modules.attendance.domain.AttendanceCardreplacement;
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
import me.zhengjie.modules.attendance.service.dto.AttendanceDto;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.repository.*;
import me.zhengjie.modules.system.service.SysConfigHolidayService;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.attendance.repository.AttendanceCardreplacementRepository;
import me.zhengjie.modules.attendance.service.AttendanceCardreplacementService;
import me.zhengjie.modules.attendance.service.dto.AttendanceCardreplacementDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceCardreplacementQueryCriteria;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceCardreplacementMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.function.Function;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author wcd
* @date 2022-12-21
**/
@Service
@RequiredArgsConstructor
public class AttendanceCardreplacementServiceImpl implements AttendanceCardreplacementService {
    private final AttendanceCardreplacementRepository attendanceCardreplacementRepository;
    private final AttendanceCardreplacementMapper attendanceCardreplacementMapper;
    private final UserRepository userRepository;
    private final OpaiDingTalkService opaiDingTalkService;
    private final RoleRepository roleRepository;
    private final AttendanceRepository attendanceRepository;
    private final SysConfigProportionRepository sysConfigProportionRepository;
    private final DictDetailRepository dictDetailRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    @Override
    public Map<String,Object> queryAll(AttendanceCardreplacementQueryCriteria criteria, Pageable pageable){
        //查询当前登录人
        User user = userRepository.findById(SecurityUtils.getCurrentUserId()).get();
        Page<AttendanceCardreplacement> page = attendanceCardreplacementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<AttendanceCardreplacement, AttendanceCardreplacementDto> func = new Function<AttendanceCardreplacement,AttendanceCardreplacementDto >(){
            @Override
            public AttendanceCardreplacementDto apply(AttendanceCardreplacement attendanceCardreplacement) {
                // 将实体类转换成DTO
                AttendanceCardreplacementDto attendanceCardreplacementDto = attendanceCardreplacementMapper.toDto(attendanceCardreplacement);
                //查询申请人信息
                User user = userRepository.findById(attendanceCardreplacementDto.getUserId()).orElseGet(User::new);
                attendanceCardreplacementDto.setUserName(user.getNickName());
                //查询申请人信息
                User appUser = userRepository.findById(attendanceCardreplacementDto.getApprovalUserId()).orElseGet(User::new);
                attendanceCardreplacementDto.setAppUserName(appUser.getNickName());
                return attendanceCardreplacementDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<AttendanceCardreplacementDto> queryAll(AttendanceCardreplacementQueryCriteria criteria) {
        List<AttendanceCardreplacementDto> attendanceCardreplacementList = attendanceCardreplacementMapper.toDto(attendanceCardreplacementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        attendanceCardreplacementList.forEach(attendanceCardreplacementDto -> {
            //查询申请人信息
            User user = userRepository.findById(attendanceCardreplacementDto.getUserId()).orElseGet(User::new);
            attendanceCardreplacementDto.setUserName(user.getNickName());
            //查询申请人信息
            User appUser = userRepository.findById(attendanceCardreplacementDto.getApprovalUserId()).orElseGet(User::new);
            attendanceCardreplacementDto.setAppUserName(appUser.getNickName());
        });
        return attendanceCardreplacementList;
    }
    @Override
    @Transactional
    public AttendanceCardreplacementDto findById(Long id) {
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findById(id).orElseGet(AttendanceCardreplacement::new);
        ValidationUtil.isNull(attendanceCardreplacement.getId(),"AttendanceCardreplacement","id",id);
        return attendanceCardreplacementMapper.toDto(attendanceCardreplacement);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceCardreplacementDto create(AttendanceCardreplacement resources) throws Exception {
        //查询补卡次数(每个月5次)
        getCardreplacement(resources.getCardReplacementTime(), resources.getUserId());
        //查询补卡记录是否存在
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findByUserIdAndCardReplacementTime(resources.getUserId(),resources.getCardReplacementTime());
        if(ObjectUtils.isNotEmpty(attendanceCardreplacement)) {
            throw new BadRequestException("补卡记录已存在");
        }
        //查询考勤表是否有记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String attDate = sdf.format(resources.getCardReplacementTime());
        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
        if(ObjectUtils.isEmpty(attendance)){
            throw new BadRequestException("考勤记录不存在");
        }
        resources.setApprovalStatus(Constant.CARD_APPROVE_STATUS_REVIEWED);
        //发送给审批者
        List<String> sendList = new ArrayList<>();
        //查询申请人信息
        User user = userRepository.getOne(resources.getUserId());
        //查询审批者信息
        User appUser = userRepository.getOne(resources.getApprovalUserId());
        sendList.add(appUser.getDingding());
        opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了补卡审批,请登录PMS系统处理", "card");
        return attendanceCardreplacementMapper.toDto(attendanceCardreplacementRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AttendanceCardreplacement resources) {
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findById(resources.getId()).orElseGet(AttendanceCardreplacement::new);
        ValidationUtil.isNull( attendanceCardreplacement.getId(),"AttendanceCardreplacement","id",resources.getId());
        attendanceCardreplacement.copy(resources);
        //查询考勤表是否有记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String attDate = sdf.format(resources.getCardReplacementTime());
        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
        if(ObjectUtils.isEmpty(attendance)){
            throw new BadRequestException("考勤记录不存在");
        }
        //查询补卡次数(每个月5次)
        getCardreplacement(resources.getCardReplacementTime(), resources.getUserId());
        //获取当前登入人信息
        User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
        //审核通过或者退回不能删除
        if(attendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE) || attendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REFUSE)){
            throw new BadRequestException("审核通过或退回的不能进行修改");
        }
        attendanceCardreplacementRepository.save(attendanceCardreplacement);
    }
    /**
     * 只能补3个工作日的卡
     * @param resources
     */
    public void checkCardreplacement(AttendanceCardreplacement resources) {
        LocalDate toLocalDate = resources.getCardReplacementTime().toLocalDateTime().toLocalDate();
        LocalDate localDate = LocalDate.now();
        int count = 0;
        while (localDate.isAfter(toLocalDate)) {
            if (count >= 3) {
                throw new BadRequestException("只能申请3个工作日的补卡");
            }
            if (localDate.getDayOfWeek().getValue() == 6 || localDate.getDayOfWeek().getValue() == 7) {
                SysConfigHoliday holidayDate = sysConfigHolidayRepository.findByHolidayDate(localDate.toString());
                if (holidayDate != null && holidayDate.getDateType().equals(Constant.DATE_TYPE_WEEKDAY)) {
                    count++;
                }
            } else {
                SysConfigHoliday holidayDate = sysConfigHolidayRepository.findByHolidayDate(localDate.toString());
                if (holidayDate == null || holidayDate.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS) || holidayDate.getDateType().equals(Constant.DATE_TYPE_HOLIDAYS)) {
                    count++;
                }
            }
            localDate = localDate.plusDays(-1);
            count++;
        }
    }
    /**
     * 返回前三个工作日的日期
     * @param resources
     */
    public List<String> getCardreplacementAbleDateList(AttendanceCardreplacement resources) {
        List<String> dateList = new ArrayList<>();
        LocalDate toLocalDate = resources.getCardReplacementTime().toLocalDateTime().toLocalDate();
        LocalDate localDate = LocalDate.now();
        int count = 0;
        while (localDate.isAfter(toLocalDate)) {
            if (count >= 3) {
                break;
            }
            if (localDate.getDayOfWeek().getValue() == 6 || localDate.getDayOfWeek().getValue() == 7) {
                SysConfigHoliday holidayDate = sysConfigHolidayRepository.findByHolidayDate(localDate.toString());
                if (holidayDate != null && holidayDate.getDateType().equals(Constant.DATE_TYPE_WEEKDAY)) {
                    dateList.add(localDate.toString());
                    count++;
                }
            } else {
                SysConfigHoliday holidayDate = sysConfigHolidayRepository.findByHolidayDate(localDate.toString());
                if (holidayDate == null || holidayDate.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS) || holidayDate.getDateType().equals(Constant.DATE_TYPE_HOLIDAYS)) {
                    dateList.add(localDate.toString());
                    count++;
                }
            }
            localDate = localDate.plusDays(-1);
            count++;
        }
        return dateList;
    }
    /**
     * 查询剩余补卡次数
     */
    public void getCardreplacement(Timestamp cardReplacementTime, Long userId){
        // 日期时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 补卡时间字符串
        String cardReplacementTimeStr = sdf.format(cardReplacementTime);
        // 查询当月的补卡记录的条数
        Integer count = attendanceCardreplacementRepository.count(userId, cardReplacementTimeStr.substring(0,7));
        // 查询配置表的每月补卡次数
        SysConfigProportion sysConfigProportion = sysConfigProportionRepository.findByTitle("每月可补卡次数");
        if(count >= sysConfigProportion.getProportion()){
            throw new BadRequestException("补卡次数用尽,请联系管理员");
        }
    }
    /**
     * 审核功能
     * @param resources
     */
    @Override
    public void updateApprove(AttendanceCardreplacement resources) {
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findById(resources.getId()).orElseGet(AttendanceCardreplacement::new);
        ValidationUtil.isNull(attendanceCardreplacement.getId(), "AttendanceCardreplacement", "id", resources.getId());
        attendanceCardreplacement.copy(resources);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String attDate = sdf.format(resources.getCardReplacementTime());
        // 根据userId和日期查询考勤记录表
        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(), attDate.substring(0, 10));
        // 判断是上班补卡还是下班补卡
        if (resources.getCardReplacementDistinguish().equals(Constant.CARD_REPLACEMENT_DIFFERENTIATION_GOON)) {
            // 通过
            if (resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE)) {
                // set考勤打卡时间和打卡状态
                attendance.setActualWorkStartTime(resources.getCardReplacementTime());
                attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NORMAL);
                attendance.setStartLocationResults(Constant.LOCATION_RESULTS_NORMAL);
            }else if (resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REFUSE)){
                attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
                attendance.setStartLocationResults(Constant.LOCATION_RESULTS_NOTSIGNED);
            }
        } else {
            // 通过
            if (resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE)) {
                // set考勤打卡时间和打卡状态
                attendance.setActualWorkEndTime(resources.getCardReplacementTime());
                attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NORMAL);
                attendance.setEndLocationResults(Constant.LOCATION_RESULTS_NORMAL);
            }else if (resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REFUSE)){
                attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
                attendance.setEndLocationResults(Constant.LOCATION_RESULTS_NOTSIGNED);
            }
        }
        attendanceRepository.save(attendance);
        attendanceCardreplacementRepository.save(attendanceCardreplacement);
    }
    /**
     * 补卡批量审核
     * @param
     */
    @Override
    public void updateAgree(AgreeUpdateRequest request) {
        // 循环ID列表
        for (Long id : request.getIds()) {
            AttendanceCardreplacement AttendanceCardreplacement = attendanceCardreplacementRepository.findById(id).orElseGet(AttendanceCardreplacement::new);
            ValidationUtil.isNull(AttendanceCardreplacement.getId(), "AttendanceCardreplacement", "id", id);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String attDate = sdf.format(AttendanceCardreplacement.getCardReplacementTime());
            // 根据userId和日期查询考勤记录表
            Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(AttendanceCardreplacement.getUserId(), attDate.substring(0, 10));
            // 判断是上班补卡还是下班补卡
            if (AttendanceCardreplacement.getCardReplacementDistinguish().equals(Constant.CARD_REPLACEMENT_DIFFERENTIATION_GOON)) {
                // 通过
                if (AttendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REVIEWED) && request.getNum().equals(Long.valueOf(1))) {
                    // set考勤打卡时间和打卡状态
                    attendance.setActualWorkStartTime(AttendanceCardreplacement.getCardReplacementTime());
                    attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NORMAL);
                    attendance.setStartLocationResults(Constant.LOCATION_RESULTS_NORMAL);
                    AttendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_AGREE);
                }else if (AttendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REVIEWED) && request.getNum().equals(Long.valueOf(2))){
                    attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
                    attendance.setStartLocationResults(Constant.LOCATION_RESULTS_NOTSIGNED);
                    AttendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_REFUSE);
                }
            } else {
                // 通过
                if (AttendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REVIEWED) && request.getNum().equals(Long.valueOf(1))) {
                    // set考勤打卡时间和打卡状态
                    attendance.setActualWorkEndTime(AttendanceCardreplacement.getCardReplacementTime());
                    attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NORMAL);
                    attendance.setEndLocationResults(Constant.LOCATION_RESULTS_NORMAL);
                    AttendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_AGREE);
                }else if (AttendanceCardreplacement.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REVIEWED) && request.getNum().equals(Long.valueOf(2))){
                    attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
                    attendance.setEndLocationResults(Constant.LOCATION_RESULTS_NOTSIGNED);
                    AttendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_REFUSE);
                }
            }
            attendanceRepository.save(attendance);
            attendanceCardreplacementRepository.save(AttendanceCardreplacement);
        }
    }
    /**
     * 补卡撤销
     * @param resources
     */
    @Override
    public void cardRevoke(AttendanceCardreplacement resources) {
        AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findById(resources.getId()).orElseGet(AttendanceCardreplacement::new);
        ValidationUtil.isNull( attendanceCardreplacement.getId(),"AttendanceCardreplacement","id",resources.getId());
        attendanceCardreplacement.copy(resources);
        //如果审批状态为已通过,补卡次数加回来?
        if(resources.getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE)) {
        }
        attendanceCardreplacement.setApprovalStatus(Constant.CARD_APPROVE_STATUS_REVIEWED);
        String sfd = resources.getCardReplacementTime().toLocalDateTime().toString().substring(0,10);
        //查询考勤记录状态改为等待
        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),resources.getCardReplacementTime().toLocalDateTime().toString().substring(0,10));
        // 判断是上班补卡还是下班补卡
        if (resources.getCardReplacementDistinguish().equals(Constant.CARD_REPLACEMENT_DIFFERENTIATION_GOON)) {
            attendance.setActualWorkStartTime(null);
            attendance.setStartClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
            attendance.setStartLocationResults(null);
        }else{
            attendance.setActualWorkEndTime(null);
            attendance.setEndClockResults(Constant.ATTENDANCE_STATE_NOTSIGNED);
            attendance.setEndLocationResults(null);
        }
        attendanceCardreplacementRepository.save(attendanceCardreplacement);
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //获取当前登入人信息
            User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
            Role role = user.getRoles().iterator().next();
            //根据id查询记录
            Optional<AttendanceCardreplacement> attendanceCardreplacement = attendanceCardreplacementRepository.findById(id);
            //除超管、总经理只能删除自己信息
            if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
                if (!Long.valueOf(attendanceCardreplacement.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            //审核通过或者退回不能删除
            if(attendanceCardreplacement.get().getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_AGREE) || attendanceCardreplacement.get().getApprovalStatus().equals(Constant.CARD_APPROVE_STATUS_REFUSE)){
                throw new BadRequestException("审核通过或退回的不能进行删除");
            }
            attendanceCardreplacementRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<AttendanceCardreplacementDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceCardreplacementDto attendanceCardreplacement : all) {
            String attCardreplacementType = attendanceCardreplacement.getApprovalStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.CARD_APPROVE_STATUS, attendanceCardreplacement.getApprovalStatus()).getLabel() : "";
            String attCardReplacementDistinguish = attendanceCardreplacement.getCardReplacementDistinguish() != null ? dictDetailRepository.findByDictNameAndValue(Constant.CARD_REPLACEMENT_DIFFERENTIATION, attendanceCardreplacement.getCardReplacementDistinguish()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请者", attendanceCardreplacement.getUserName());
            map.put("审批者", attendanceCardreplacement.getAppUserName());
            map.put("补卡时间", attendanceCardreplacement.getCardReplacementTime());
            map.put("补卡原因", attendanceCardreplacement.getCardReplacementReason());
            map.put("审批状态", attCardreplacementType);
            map.put("审批说明", attendanceCardreplacement.getApprovalDescription());
            map.put("补卡区分", attCardReplacementDistinguish);
            map.put("备注", attendanceCardreplacement.getRemarks());
            map.put("创建者", attendanceCardreplacement.getCreateBy());
            map.put("创建时间", attendanceCardreplacement.getCreateTime());
            map.put("更新者", attendanceCardreplacement.getUpdateBy());
            map.put("更新时间", attendanceCardreplacement.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceGoOutServiceImpl.java
@@ -1,565 +1,574 @@
/*
*  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 lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.AttendanceBusinessTravelRepository;
import me.zhengjie.modules.attendance.repository.AttendanceGoOutRepository;
import me.zhengjie.modules.attendance.repository.AttendanceLeaveRepository;
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
import me.zhengjie.modules.attendance.service.AttendanceGoOutService;
import me.zhengjie.modules.attendance.service.AttendanceOvertimeService;
import me.zhengjie.modules.attendance.service.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutQueryCriteria;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceGoOutMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.quartz.service.impl.DingTalkServiceImpl;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.SysRostering;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.SysConfigHolidayService;
import me.zhengjie.modules.system.service.dto.SysConfigHolidayDto;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author wcd
* @date 2023-01-04
**/
@Service
@RequiredArgsConstructor
public class AttendanceGoOutServiceImpl implements AttendanceGoOutService {
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceOvertimeService attendanceOvertimeService;
    private final AttendanceGoOutMapper attendanceGoOutMapper;
    private final UserRepository userRepository;
    private final AttendanceService attendanceService;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceLeaveServiceImpl attendanceLeaveService;
    private final OpaiDingTalkService opaiDingTalkService;
    private final AttendanceRepository attendanceRepository;
    private final AttendanceLeaveRepository attendanceLeaveRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final DictDetailRepository dictDetailRepository;
    private final DingTalkServiceImpl dingTalkService;
    private final SysConfigHolidayService sysConfigHolidayService;
    @Override
    public Map<String,Object> queryAll(AttendanceGoOutQueryCriteria criteria, Pageable pageable){
        Page<AttendanceGoOut> page = attendanceGoOutRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<AttendanceGoOut, AttendanceGoOutDto> func = new Function<AttendanceGoOut, AttendanceGoOutDto>(){
            @Override
            public AttendanceGoOutDto apply(AttendanceGoOut attendanceGoOut) {
                // 将实体类转换成DTO
                AttendanceGoOutDto attendanceGoOutDto = attendanceGoOutMapper.toDto(attendanceGoOut);
                //查询用户信息
                User user = userRepository.findById(attendanceGoOutDto.getUserId()).orElseGet(User::new);
                attendanceGoOutDto.setUserName(user.getNickName());
                //查询审批用户名
                User appUser = userRepository.findById(attendanceGoOutDto.getApprovalUserId()).orElseGet(User::new);
                attendanceGoOutDto.setAppUserName(appUser.getNickName());
                return attendanceGoOutDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<AttendanceGoOutDto> queryAll(AttendanceGoOutQueryCriteria criteria){
        List<AttendanceGoOutDto> attendanceGoOutDtoList = attendanceGoOutMapper.toDto(attendanceGoOutRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        attendanceGoOutDtoList.forEach(attendanceGoOutDto -> {
            //查询用户信息
            User user = userRepository.findById(attendanceGoOutDto.getUserId()).orElseGet(User::new);
            attendanceGoOutDto.setUserName(user.getNickName());
            //查询审批用户名
            User appUser = userRepository.findById(attendanceGoOutDto.getApprovalUserId()).orElseGet(User::new);
            attendanceGoOutDto.setAppUserName(appUser.getNickName());
        });
        return attendanceGoOutDtoList;
    }
    @Override
    @Transactional
    public AttendanceGoOutDto findById(Long id) {
        AttendanceGoOut attendanceGoOut = attendanceGoOutRepository.findById(id).orElseGet(AttendanceGoOut::new);
        ValidationUtil.isNull(attendanceGoOut.getId(),"AttendanceGoOut","id",id);
        return attendanceGoOutMapper.toDto(attendanceGoOut);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceGoOutDto create(AttendanceGoOut resources) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String goStartTime = df.format(resources.getOutStartTime());
        String goEndTime = df.format(resources.getOutEndTime());
//        // 查询其他状态的表是否有重复
//        repeatValidation(goStartTime, goEndTime, resources.getUserId() == null ? SecurityUtils.getCurrentUserId() : resources.getUserId());
        // 验证请假时间是否冲突
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.checkCreateTime(goStartTime, goEndTime, resources.getUserId());
        if (attendanceGoOutList.size() > 0) {
            AttendanceGoOut errTime = attendanceGoOutList.get(0);
            //LocalDateTime转换为Date
            LocalDateTime strartTime = errTime.getOutStartTime().toLocalDateTime();
            ZonedDateTime zonedDateTime = strartTime.atZone(ZoneId.systemDefault());
            Instant instant = zonedDateTime.toInstant();
            Date strTime = Date.from(instant);
            LocalDateTime endTime = errTime.getOutEndTime().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() == null ? SecurityUtils.getCurrentUserId() : resources.getUserId());
            LocalDate startDate = resources.getOutStartTime().toLocalDateTime().toLocalDate();
            LocalDate endDate = resources.getOutEndTime().toLocalDateTime().toLocalDate();
            LocalTime startTime = resources.getOutStartTime().toLocalDateTime().toLocalTime();
            LocalTime endTime = resources.getOutEndTime().toLocalDateTime().toLocalTime();
            long distance = ChronoUnit.DAYS.between(startDate, endDate);
            Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(localDate -> {
//                SysConfigHolidayDto sysConfigHolidayDto = sysConfigHolidayService.queryByHolidayDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//                Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
//                if ((sysConfigHolidayDto == null && !isWeekend) ||
//                        sysConfigHolidayDto != null && Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHolidayDto.getDateType())) {
                    AttendanceGoOut attendanceGoOut = new AttendanceGoOut();
                    //resUserId为null说明是添加,反之
                    if (resources.getUserId() == null) {
                        resources.setUserId(user.getId());
                    }
                    resources.setOutStartTime(Timestamp.valueOf(localDate.atTime(startTime)));
                    resources.setOutEndTime(Timestamp.valueOf(localDate.atTime(endTime)));
                    Double result = getRemainingTime(resources);
                    resources.setOutDuration(result);
                    resources.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_REVIEWED);
                    attendanceGoOut.copy(resources);
                    attendanceGoOutRepository.save(attendanceGoOut);
//                }
//                SysConfigHolidayDto sysConfigHolidayDto = sysConfigHolidayService.queryByHolidayDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//                Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
//                if ((sysConfigHolidayDto == null && isWeekend) ||
//                        sysConfigHolidayDto != null && Constant.DATE_TYPE_HOLIDAYS.equals(sysConfigHolidayDto.getDateType())) {
//                    AttendanceOvertime attendanceOvertime = new AttendanceOvertime();
//                    attendanceOvertime.setUserId(resources.getUserId());
//                    attendanceOvertime.setApprovalUserId(resources.getApprovalUserId());
//                    attendanceOvertime.setOvertimeStartTime(resources.getOutStartTime());
//                    attendanceOvertime.setOvertimeEndTime(resources.getOutEndTime());
//                    attendanceOvertime.setOvertimeDuration(resources.getOutDuration());
//                    attendanceOvertime.setApprovalStatus(resources.getApprovalStatus());
//                    attendanceOvertime.setRemarks(resources.getRemarks());
//                    attendanceOvertimeService.create(attendanceOvertime);
//                }
            });
//
//            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 = attendanceLeaveService.getBetweenDate(resources.getOutStartTime().toLocalDateTime().toString(),resources.getOutEndTime().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))){
//                    AttendanceGoOut attendanceGoOut = getAttendanceOut(resources,date,user,i,goStartTime,goEndTime,null);
//                    i++;
//                    attendanceGoOutRepository.save(attendanceGoOut);
//                }
//            }
            //发送钉钉给审批人
            List<String> sendList = new ArrayList<>();
            //查询审批者信息
            User appUser = userRepository.getOne(resources.getApprovalUserId());
            sendList.add(appUser.getDingding());
            opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了外出审批,请登录PMS系统处理", "card");
        }
        return attendanceGoOutMapper.toDto(resources);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AttendanceGoOut resources) {
        AttendanceGoOut attendanceGoOut = attendanceGoOutRepository.findById(resources.getId()).orElseGet(AttendanceGoOut::new);
        ValidationUtil.isNull( attendanceGoOut.getId(),"AttendanceGoOut","id",resources.getId());
        attendanceGoOut.copy(resources);
        //审核通过或者退回不能修改
        if(attendanceGoOut.getApprovalStatus().equals(Constant.GOOUT_APPROVE_STATUS_AGREE) || attendanceGoOut.getApprovalStatus().equals(Constant.GOOUT_APPROVE_STATUS_REFUSE)){
            throw new BadRequestException("审核通过或退回的不能进行修改");
        }
        //获取当前登入人信息
        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user1.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String goStartTime = df.format(resources.getOutStartTime());
        String goEndTime = df.format(resources.getOutEndTime());
//        // 查询其他状态的表是否有重复
//        repeatValidation(goStartTime, goEndTime, resources.getUserId());
        // 验证是否存在时间冲突的请假记录
        Set<Long> ids = new HashSet<>();
        ids.add(attendanceGoOut.getId());
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.checkCreateUpdateTime(goStartTime, goEndTime, resources.getUserId(), ids);
        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())
                    + "已经存在外出记录,请调整时间");
        } else {
            // 获取当前登陆人信息,设置为请假发起人
            User user = userRepository.getOne(resources.getUserId() == null ? SecurityUtils.getCurrentUserId() : resources.getUserId());
            LocalDate startDate = resources.getOutStartTime().toLocalDateTime().toLocalDate();
            LocalDate endDate = resources.getOutEndTime().toLocalDateTime().toLocalDate();
            LocalTime startTime = resources.getOutStartTime().toLocalDateTime().toLocalTime();
            LocalTime endTime = resources.getOutEndTime().toLocalDateTime().toLocalTime();
            long distance = ChronoUnit.DAYS.between(startDate, endDate);
            Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(localDate -> {
                SysConfigHolidayDto sysConfigHolidayDto = sysConfigHolidayService.queryByHolidayDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
                if ((sysConfigHolidayDto == null && !isWeekend) ||
                        sysConfigHolidayDto != null && Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHolidayDto.getDateType())) {
                    AttendanceGoOut attendanceGoOut1 = new AttendanceGoOut();
                    //resUserId为null说明是添加,反之
                    if (resources.getUserId() == null) {
                        resources.setUserId(user.getId());
                    }
                    resources.setOutStartTime(Timestamp.valueOf(localDate.atTime(startTime)));
                    resources.setOutEndTime(Timestamp.valueOf(localDate.atTime(endTime)));
                    long timeSeconds = ChronoUnit.SECONDS.between(startTime, endTime);
                    Double result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    resources.setOutDuration(result);
                    resources.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_REVIEWED);
                    attendanceGoOut1.copy(resources);
                    attendanceGoOutRepository.save(attendanceGoOut1);
                }
            });
//            //暂存userId
//            Long resUserId = attendanceGoOut.getUserId();
//            // 删除以前的记录
//            for (Long id : ids) {
//                attendanceGoOutRepository.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 = attendanceLeaveService.getBetweenDate(resources.getOutStartTime().toLocalDateTime().toString(),resources.getOutEndTime().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))){
//                    AttendanceGoOut attendanceGoOut1 = getAttendanceOut(resources,date,user,i,goStartTime,goEndTime,resUserId);
//                    i++;
//                    attendanceGoOutRepository.save(attendanceGoOut1);
//                }
//            }
        }
    }
//    /**
//     * 添加多条记录
//     * @param resources
//     * @param date
//     * @param user
//     * @param i
//     * @param LeaStartTime
//     * @param LeaEndTime
//     * @param resUserId
//     * @return
//     */
//    public AttendanceGoOut getAttendanceOut(AttendanceGoOut resources, User user, LocalDateTime LeaStartTime, LocalDateTime LeaEndTime){
//        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        AttendanceGoOut attendanceGoOut = new AttendanceGoOut();
//        //resUserId为null说明是添加,反之
//        if (resUserId == null) {
//            resources.setUserId(user.getId());
//        } else {
//            resources.setUserId(resUserId);
//        }
//            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.setOutStartTime(Timestamp.valueOf(startTime));
//                    resources.setOutEndTime(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.setOutStartTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkStartTime() + ":00"));
//                    resources.setOutEndTime(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.setOutStartTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkStartTime() + ":00"));
//                    resources.setOutEndTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkEndTime() + ":00"));
//                }
//                Integer timeSeconds = attendanceService.calculateTimes(calculate, SecurityUtils.getCurrentUserId());
//                Double result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
//                resources.setOutDuration(result);
//            }
//        resources.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_REVIEWED);
//        attendanceGoOut.copy(resources);
//        return attendanceGoOut;
//    }
    /**
     * 验证其他状态的表是否有重复
     * @param goStartTime
     * @param goEndTime
     */
    public void repeatValidation(String goStartTime, String goEndTime, Long userId){
        // 查询请假表(时单位)
        List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.checkCreateLeaveTime(goStartTime,goEndTime, userId);
        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())
                    + "已经存在请假记录,请调整时间");
        }
        // 查询出差表
        List<AttendanceBusinessTravel> attendanceBusinessTravelList = attendanceBusinessTravelRepository.checkCreateTime(goStartTime.substring(0,10),goEndTime.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())
                    + "已经存在出差记录,请调整时间");
        }
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //根据id查询记录
            Optional<AttendanceGoOut> attendanceGoOut = attendanceGoOutRepository.findById(id);
            //审核通过或者退回不能删除
            if(attendanceGoOut.get().getApprovalStatus().equals(Constant.GOOUT_APPROVE_STATUS_AGREE) || attendanceGoOut.get().getApprovalStatus().equals(Constant.GOOUT_APPROVE_STATUS_REFUSE)){
                throw new BadRequestException("审核通过或退回的不能进行删除");
            }
            //获取当前登入人信息
            User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
            Role role = user.getRoles().iterator().next();
            //除超管、总经理只能删除自己信息
            if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
                if (!Long.valueOf(attendanceGoOut.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            attendanceGoOutRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<AttendanceGoOutDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceGoOutDto attendanceGoOut : all) {
            String outOfOfficeType = attendanceGoOut.getOutOfOfficeType() != null ? dictDetailRepository.findByDictNameAndValue("go_out_type", attendanceGoOut.getOutOfOfficeType()).getLabel() : "";
            String outDurationUnit = attendanceGoOut.getDurationUnit() != null ? dictDetailRepository.findByDictNameAndValue(Constant.LEAVE_TIME_TYPE, attendanceGoOut.getDurationUnit()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请者", attendanceGoOut.getUserName());
            map.put("审批者", attendanceGoOut.getAppUserName());
            map.put("外出开始时间", attendanceGoOut.getOutStartTime());
            map.put("外出结束时间", attendanceGoOut.getOutEndTime());
            map.put("外出时长", attendanceGoOut.getOutDuration());
            map.put("时长单位", outDurationUnit);
            map.put("外出类型", outOfOfficeType);
            map.put("外出原因", attendanceGoOut.getOutReason());
            map.put("审批状态", attendanceGoOut.getApprovalStatus());
            map.put("审批说明", attendanceGoOut.getApprovalDescription());
            map.put("备注", attendanceGoOut.getRemarks());
            map.put("创建者", attendanceGoOut.getCreateBy());
            map.put("创建时间", attendanceGoOut.getCreateTime());
            map.put("更新者", attendanceGoOut.getUpdateBy());
            map.put("更新时间", attendanceGoOut.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    /**
     * 计算外出时长
     * @param attendanceGoOut
     * @return
     */
    @Override
    public Double getRemainingTime(AttendanceGoOut attendanceGoOut) {
        Calculate calculate = new Calculate();
        calculate.setStart(attendanceGoOut.getOutStartTime().toLocalDateTime());
        calculate.setEnd(attendanceGoOut.getOutEndTime().toLocalDateTime());
        long timeSeconds = calculateTimes(calculate, SecurityUtils.getCurrentUserId());
        Double result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        return result;
    }
    private Long calculateTimes(Calculate calculate, Long userId) {
        User userInfo = userRepository.getOne(userId);
        SysRostering sysRostering = userInfo.getSysRostering();
        LocalDate startDate = calculate.getStart().toLocalDate();
        LocalDate endDate = calculate.getEnd().toLocalDate();
        LocalTime startTime = calculate.getStart().toLocalTime();
        LocalTime endTime = calculate.getEnd().toLocalTime();
        long distance = ChronoUnit.DAYS.between(startDate, endDate);
        return Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).map(localDate -> {
            SysConfigHolidayDto sysConfigHolidayDto = sysConfigHolidayService.queryByHolidayDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
            if ((sysConfigHolidayDto == null && !isWeekend) ||
                    sysConfigHolidayDto != null && Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHolidayDto.getDateType())) {
                LocalDateTime goOutStartTime = localDate.atTime(startTime);
                LocalDateTime goOutEndTime = localDate.atTime(endTime);
                LocalDateTime lunchStartTime = localDate.atTime(sysRostering.getLunchStartTime());
                LocalDateTime lunchEndTime = localDate.atTime(sysRostering.getLunchEndTime());
                if (goOutEndTime.isBefore(lunchStartTime) || goOutStartTime.isAfter(lunchEndTime)) {
                    return ChronoUnit.SECONDS.between(goOutStartTime, goOutEndTime);
                } else if (!goOutEndTime.isBefore(lunchStartTime) && !goOutEndTime.isAfter(lunchEndTime)) {
                    return ChronoUnit.SECONDS.between(goOutStartTime, lunchStartTime);
                } else if (!goOutStartTime.isBefore(lunchStartTime) && !goOutStartTime.isAfter(lunchEndTime)) {
                    return ChronoUnit.SECONDS.between(lunchEndTime, goOutEndTime);
                } else {
                    return ChronoUnit.SECONDS.between(goOutStartTime, goOutEndTime) - 3600;
                }
            } else {
                LocalDateTime goOutStartTime = localDate.atTime(startTime);
                LocalDateTime goOutEndTime = localDate.atTime(endTime);
                return ChronoUnit.SECONDS.between(goOutStartTime, goOutEndTime);
            }
        }).reduce(0L, (result, current) -> result + current);
    }
    /**
     * 审核/撤销功能
     * @param resources /
     */
    @Override
    public void updateApprove(AttendanceGoOut resources) throws Exception {
        AttendanceGoOut attendanceGoOut = attendanceGoOutRepository.findById(resources.getId()).orElseGet(AttendanceGoOut::new);
        ValidationUtil.isNull( attendanceGoOut.getId(),"AttendanceGoOut","id",resources.getId());
        attendanceGoOut.copy(resources);
        attendanceGoOutRepository.save(attendanceGoOut);
        // 调用定时任务修改考勤记录
        List<User> userList = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(attendanceGoOut.getUserId())){
            User user = userRepository.findById(attendanceGoOut.getUserId()).orElseGet(User::new);
            userList.add(user);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String attendanceDate = df.format(attendanceGoOut.getOutStartTime());
        dingTalkService.getDingTalkAttendanceListOfNoonOrNight(attendanceDate,userList);
    }
    /**
     * 批量审核(外出)
     * @param request
     * @throws Exception
     */
    @Override
    public void updateAgree(AgreeUpdateRequest request) throws Exception {
        for (Long id : request.getIds()) {
            AttendanceGoOut attendanceGoOut = attendanceGoOutRepository.findById(id).orElseGet(AttendanceGoOut::new);
            ValidationUtil.isNull( attendanceGoOut.getId(),"AttendanceGoOut","id",id);
            if (request.getNum().equals(Long.valueOf(1))){
                attendanceGoOut.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_AGREE);
            } else {
                attendanceGoOut.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_REFUSE);
            }
            attendanceGoOutRepository.save(attendanceGoOut);
            // 调用定时任务修改考勤记录
            List<User> userList = new ArrayList<>();
            if(ObjectUtils.isNotEmpty(attendanceGoOut.getUserId())){
                User user = userRepository.findById(attendanceGoOut.getUserId()).orElseGet(User::new);
                userList.add(user);
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String attendanceDate = df.format(attendanceGoOut.getOutStartTime());
            dingTalkService.getDingTalkAttendanceListOfNoonOrNight(attendanceDate,userList);
        }
    }
/*
*  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 lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.AttendanceBusinessTravelRepository;
import me.zhengjie.modules.attendance.repository.AttendanceGoOutRepository;
import me.zhengjie.modules.attendance.repository.AttendanceLeaveRepository;
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
import me.zhengjie.modules.attendance.service.AttendanceGoOutService;
import me.zhengjie.modules.attendance.service.AttendanceOvertimeService;
import me.zhengjie.modules.attendance.service.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutQueryCriteria;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceGoOutMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.quartz.service.impl.DingTalkServiceImpl;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.SysRostering;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.SysConfigHolidayService;
import me.zhengjie.modules.system.service.dto.SysConfigHolidayDto;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author wcd
* @date 2023-01-04
**/
@Service
@RequiredArgsConstructor
public class AttendanceGoOutServiceImpl implements AttendanceGoOutService {
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceOvertimeService attendanceOvertimeService;
    private final AttendanceGoOutMapper attendanceGoOutMapper;
    private final UserRepository userRepository;
    private final AttendanceService attendanceService;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceLeaveServiceImpl attendanceLeaveService;
    private final OpaiDingTalkService opaiDingTalkService;
    private final AttendanceRepository attendanceRepository;
    private final AttendanceLeaveRepository attendanceLeaveRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final DictDetailRepository dictDetailRepository;
    private final DingTalkServiceImpl dingTalkService;
    private final SysConfigHolidayService sysConfigHolidayService;
    @Override
    public Map<String,Object> queryAll(AttendanceGoOutQueryCriteria criteria, Pageable pageable){
        Page<AttendanceGoOut> page = attendanceGoOutRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<AttendanceGoOut, AttendanceGoOutDto> func = new Function<AttendanceGoOut, AttendanceGoOutDto>(){
            @Override
            public AttendanceGoOutDto apply(AttendanceGoOut attendanceGoOut) {
                // 将实体类转换成DTO
                AttendanceGoOutDto attendanceGoOutDto = attendanceGoOutMapper.toDto(attendanceGoOut);
                //查询用户信息
                User user = userRepository.findById(attendanceGoOutDto.getUserId()).orElseGet(User::new);
                attendanceGoOutDto.setUserName(user.getNickName());
                //查询审批用户名
                User appUser = userRepository.findById(attendanceGoOutDto.getApprovalUserId()).orElseGet(User::new);
                attendanceGoOutDto.setAppUserName(appUser.getNickName());
                return attendanceGoOutDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<AttendanceGoOutDto> queryAll(AttendanceGoOutQueryCriteria criteria){
        List<AttendanceGoOutDto> attendanceGoOutDtoList = attendanceGoOutMapper.toDto(attendanceGoOutRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        attendanceGoOutDtoList.forEach(attendanceGoOutDto -> {
            //查询用户信息
            User user = userRepository.findById(attendanceGoOutDto.getUserId()).orElseGet(User::new);
            attendanceGoOutDto.setUserName(user.getNickName());
            //查询审批用户名
            User appUser = userRepository.findById(attendanceGoOutDto.getApprovalUserId()).orElseGet(User::new);
            attendanceGoOutDto.setAppUserName(appUser.getNickName());
        });
        return attendanceGoOutDtoList;
    }
    @Override
    @Transactional
    public AttendanceGoOutDto findById(Long id) {
        AttendanceGoOut attendanceGoOut = attendanceGoOutRepository.findById(id).orElseGet(AttendanceGoOut::new);
        ValidationUtil.isNull(attendanceGoOut.getId(),"AttendanceGoOut","id",id);
        return attendanceGoOutMapper.toDto(attendanceGoOut);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceGoOutDto create(AttendanceGoOut resources) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String goStartTime = df.format(resources.getOutStartTime());
        String goEndTime = df.format(resources.getOutEndTime());
//        // 查询其他状态的表是否有重复
//        repeatValidation(goStartTime, goEndTime, resources.getUserId() == null ? SecurityUtils.getCurrentUserId() : resources.getUserId());
        // 验证请假时间是否冲突
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.checkCreateTime(goStartTime, goEndTime, resources.getUserId());
        if (attendanceGoOutList.size() > 0) {
            AttendanceGoOut errTime = attendanceGoOutList.get(0);
            //LocalDateTime转换为Date
            LocalDateTime strartTime = errTime.getOutStartTime().toLocalDateTime();
            ZonedDateTime zonedDateTime = strartTime.atZone(ZoneId.systemDefault());
            Instant instant = zonedDateTime.toInstant();
            Date strTime = Date.from(instant);
            LocalDateTime endTime = errTime.getOutEndTime().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() == null ? SecurityUtils.getCurrentUserId() : resources.getUserId());
            LocalDate startDate = resources.getOutStartTime().toLocalDateTime().toLocalDate();
            LocalDate endDate = resources.getOutEndTime().toLocalDateTime().toLocalDate();
            LocalTime startTime = resources.getOutStartTime().toLocalDateTime().toLocalTime();
            LocalTime endTime = resources.getOutEndTime().toLocalDateTime().toLocalTime();
            long distance = ChronoUnit.DAYS.between(startDate, endDate);
            Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(localDate -> {
//                SysConfigHolidayDto sysConfigHolidayDto = sysConfigHolidayService.queryByHolidayDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//                Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
//                if ((sysConfigHolidayDto == null && !isWeekend) ||
//                        sysConfigHolidayDto != null && Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHolidayDto.getDateType())) {
                    AttendanceGoOut attendanceGoOut = new AttendanceGoOut();
                    //resUserId为null说明是添加,反之
                    if (resources.getUserId() == null) {
                        resources.setUserId(user.getId());
                    }
                    resources.setOutStartTime(Timestamp.valueOf(localDate.atTime(startTime)));
                    resources.setOutEndTime(Timestamp.valueOf(localDate.atTime(endTime)));
                    Double result = getRemainingTime(resources);
                    resources.setOutDuration(result);
                    resources.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_REVIEWED);
                    attendanceGoOut.copy(resources);
                    attendanceGoOutRepository.save(attendanceGoOut);
//                }
//                SysConfigHolidayDto sysConfigHolidayDto = sysConfigHolidayService.queryByHolidayDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//                Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
//                if ((sysConfigHolidayDto == null && isWeekend) ||
//                        sysConfigHolidayDto != null && Constant.DATE_TYPE_HOLIDAYS.equals(sysConfigHolidayDto.getDateType())) {
//                    AttendanceOvertime attendanceOvertime = new AttendanceOvertime();
//                    attendanceOvertime.setUserId(resources.getUserId());
//                    attendanceOvertime.setApprovalUserId(resources.getApprovalUserId());
//                    attendanceOvertime.setOvertimeStartTime(resources.getOutStartTime());
//                    attendanceOvertime.setOvertimeEndTime(resources.getOutEndTime());
//                    attendanceOvertime.setOvertimeDuration(resources.getOutDuration());
//                    attendanceOvertime.setApprovalStatus(resources.getApprovalStatus());
//                    attendanceOvertime.setRemarks(resources.getRemarks());
//                    attendanceOvertimeService.create(attendanceOvertime);
//                }
            });
//
//            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 = attendanceLeaveService.getBetweenDate(resources.getOutStartTime().toLocalDateTime().toString(),resources.getOutEndTime().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))){
//                    AttendanceGoOut attendanceGoOut = getAttendanceOut(resources,date,user,i,goStartTime,goEndTime,null);
//                    i++;
//                    attendanceGoOutRepository.save(attendanceGoOut);
//                }
//            }
            //发送钉钉给审批人
            List<String> sendList = new ArrayList<>();
            //查询审批者信息
            User appUser = userRepository.getOne(resources.getApprovalUserId());
            sendList.add(appUser.getDingding());
            opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了外出审批,请登录PMS系统处理", "card");
        }
        return attendanceGoOutMapper.toDto(resources);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AttendanceGoOut resources) {
        AttendanceGoOut attendanceGoOut = attendanceGoOutRepository.findById(resources.getId()).orElseGet(AttendanceGoOut::new);
        ValidationUtil.isNull( attendanceGoOut.getId(),"AttendanceGoOut","id",resources.getId());
        attendanceGoOut.copy(resources);
        //审核通过或者退回不能修改
        if(attendanceGoOut.getApprovalStatus().equals(Constant.GOOUT_APPROVE_STATUS_AGREE) || attendanceGoOut.getApprovalStatus().equals(Constant.GOOUT_APPROVE_STATUS_REFUSE)){
            throw new BadRequestException("审核通过或退回的不能进行修改");
        }
        //获取当前登入人信息
        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user1.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String goStartTime = df.format(resources.getOutStartTime());
        String goEndTime = df.format(resources.getOutEndTime());
//        // 查询其他状态的表是否有重复
//        repeatValidation(goStartTime, goEndTime, resources.getUserId());
        // 验证是否存在时间冲突的请假记录
        Set<Long> ids = new HashSet<>();
        ids.add(attendanceGoOut.getId());
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.checkCreateUpdateTime(goStartTime, goEndTime, resources.getUserId(), ids);
        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())
                    + "已经存在外出记录,请调整时间");
        } else {
            // 获取当前登陆人信息,设置为请假发起人
            User user = userRepository.getOne(resources.getUserId() == null ? SecurityUtils.getCurrentUserId() : resources.getUserId());
            LocalDate startDate = resources.getOutStartTime().toLocalDateTime().toLocalDate();
            LocalDate endDate = resources.getOutEndTime().toLocalDateTime().toLocalDate();
            LocalTime startTime = resources.getOutStartTime().toLocalDateTime().toLocalTime();
            LocalTime endTime = resources.getOutEndTime().toLocalDateTime().toLocalTime();
            long distance = ChronoUnit.DAYS.between(startDate, endDate);
            Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(localDate -> {
                SysConfigHolidayDto sysConfigHolidayDto = sysConfigHolidayService.queryByHolidayDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
                if ((sysConfigHolidayDto == null && !isWeekend) ||
                        sysConfigHolidayDto != null && Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHolidayDto.getDateType())) {
                    AttendanceGoOut attendanceGoOut1 = new AttendanceGoOut();
                    //resUserId为null说明是添加,反之
                    if (resources.getUserId() == null) {
                        resources.setUserId(user.getId());
                    }
                    resources.setOutStartTime(Timestamp.valueOf(localDate.atTime(startTime)));
                    resources.setOutEndTime(Timestamp.valueOf(localDate.atTime(endTime)));
                    long timeSeconds = ChronoUnit.SECONDS.between(startTime, endTime);
                    Double result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    resources.setOutDuration(result);
                    resources.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_REVIEWED);
                    attendanceGoOut1.copy(resources);
                    attendanceGoOutRepository.save(attendanceGoOut1);
                }
            });
//            //暂存userId
//            Long resUserId = attendanceGoOut.getUserId();
//            // 删除以前的记录
//            for (Long id : ids) {
//                attendanceGoOutRepository.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 = attendanceLeaveService.getBetweenDate(resources.getOutStartTime().toLocalDateTime().toString(),resources.getOutEndTime().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))){
//                    AttendanceGoOut attendanceGoOut1 = getAttendanceOut(resources,date,user,i,goStartTime,goEndTime,resUserId);
//                    i++;
//                    attendanceGoOutRepository.save(attendanceGoOut1);
//                }
//            }
        }
    }
//    /**
//     * 添加多条记录
//     * @param resources
//     * @param date
//     * @param user
//     * @param i
//     * @param LeaStartTime
//     * @param LeaEndTime
//     * @param resUserId
//     * @return
//     */
//    public AttendanceGoOut getAttendanceOut(AttendanceGoOut resources, User user, LocalDateTime LeaStartTime, LocalDateTime LeaEndTime){
//        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        AttendanceGoOut attendanceGoOut = new AttendanceGoOut();
//        //resUserId为null说明是添加,反之
//        if (resUserId == null) {
//            resources.setUserId(user.getId());
//        } else {
//            resources.setUserId(resUserId);
//        }
//            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.setOutStartTime(Timestamp.valueOf(startTime));
//                    resources.setOutEndTime(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.setOutStartTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkStartTime() + ":00"));
//                    resources.setOutEndTime(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.setOutStartTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkStartTime() + ":00"));
//                    resources.setOutEndTime(Timestamp.valueOf(date + " " + user.getSysRostering().getWorkEndTime() + ":00"));
//                }
//                Integer timeSeconds = attendanceService.calculateTimes(calculate, SecurityUtils.getCurrentUserId());
//                Double result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
//                resources.setOutDuration(result);
//            }
//        resources.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_REVIEWED);
//        attendanceGoOut.copy(resources);
//        return attendanceGoOut;
//    }
    /**
     * 验证其他状态的表是否有重复
     * @param goStartTime
     * @param goEndTime
     */
    public void repeatValidation(String goStartTime, String goEndTime, Long userId){
        // 查询请假表(时单位)
        List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.checkCreateLeaveTime(goStartTime,goEndTime, userId);
        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())
                    + "已经存在请假记录,请调整时间");
        }
        // 查询出差表
        List<AttendanceBusinessTravel> attendanceBusinessTravelList = attendanceBusinessTravelRepository.checkCreateTime(goStartTime.substring(0,10),goEndTime.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())
                    + "已经存在出差记录,请调整时间");
        }
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //根据id查询记录
            Optional<AttendanceGoOut> attendanceGoOut = attendanceGoOutRepository.findById(id);
            //审核通过或者退回不能删除
            if(attendanceGoOut.get().getApprovalStatus().equals(Constant.GOOUT_APPROVE_STATUS_AGREE) || attendanceGoOut.get().getApprovalStatus().equals(Constant.GOOUT_APPROVE_STATUS_REFUSE)){
                throw new BadRequestException("审核通过或退回的不能进行删除");
            }
            //获取当前登入人信息
            User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
            Role role = user.getRoles().iterator().next();
            //除超管、总经理只能删除自己信息
            if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
                if (!Long.valueOf(attendanceGoOut.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            attendanceGoOutRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<AttendanceGoOutDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceGoOutDto attendanceGoOut : all) {
            String outOfOfficeType = attendanceGoOut.getOutOfOfficeType() != null ? dictDetailRepository.findByDictNameAndValue("go_out_type", attendanceGoOut.getOutOfOfficeType()).getLabel() : "";
            String outDurationUnit = attendanceGoOut.getDurationUnit() != null ? dictDetailRepository.findByDictNameAndValue(Constant.LEAVE_TIME_TYPE, attendanceGoOut.getDurationUnit()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请者", attendanceGoOut.getUserName());
            map.put("审批者", attendanceGoOut.getAppUserName());
            map.put("外出开始时间", attendanceGoOut.getOutStartTime());
            map.put("外出结束时间", attendanceGoOut.getOutEndTime());
            map.put("外出时长", attendanceGoOut.getOutDuration());
            map.put("时长单位", outDurationUnit);
            map.put("外出类型", outOfOfficeType);
            map.put("外出原因", attendanceGoOut.getOutReason());
            map.put("审批状态", attendanceGoOut.getApprovalStatus());
            map.put("审批说明", attendanceGoOut.getApprovalDescription());
            map.put("备注", attendanceGoOut.getRemarks());
            map.put("创建者", attendanceGoOut.getCreateBy());
            map.put("创建时间", attendanceGoOut.getCreateTime());
            map.put("更新者", attendanceGoOut.getUpdateBy());
            map.put("更新时间", attendanceGoOut.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    /**
     * 计算外出时长
     * @param attendanceGoOut
     * @return
     */
    @Override
    public Double getRemainingTime(AttendanceGoOut attendanceGoOut) {
        Calculate calculate = new Calculate();
        calculate.setStart(attendanceGoOut.getOutStartTime().toLocalDateTime());
        calculate.setEnd(attendanceGoOut.getOutEndTime().toLocalDateTime());
        long timeSeconds = calculateTimes(calculate, SecurityUtils.getCurrentUserId());
        Double result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        return result;
    }
    @Override
    public void reflashTime(Long[] ids) {
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findAllById(Arrays.asList(ids));
        attendanceGoOutList.forEach(attendanceGoOut -> {
            attendanceGoOut.setOutDuration(getRemainingTime(attendanceGoOut));
            attendanceGoOutRepository.save(attendanceGoOut);
        });
    }
    private Long calculateTimes(Calculate calculate, Long userId) {
        User userInfo = userRepository.getOne(userId);
        SysRostering sysRostering = userInfo.getSysRostering();
        LocalDate startDate = calculate.getStart().toLocalDate();
        LocalDate endDate = calculate.getEnd().toLocalDate();
        LocalTime startTime = calculate.getStart().toLocalTime();
        LocalTime endTime = calculate.getEnd().toLocalTime();
        long distance = ChronoUnit.DAYS.between(startDate, endDate);
        return Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).map(localDate -> {
            SysConfigHolidayDto sysConfigHolidayDto = sysConfigHolidayService.queryByHolidayDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            Boolean isWeekend = localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY;
            if ((sysConfigHolidayDto == null && !isWeekend) ||
                    sysConfigHolidayDto != null && Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHolidayDto.getDateType())) {
                LocalDateTime goOutStartTime = localDate.atTime(startTime);
                LocalDateTime goOutEndTime = localDate.atTime(endTime);
                LocalDateTime lunchStartTime = localDate.atTime(sysRostering.getLunchStartTime());
                LocalDateTime lunchEndTime = localDate.atTime(sysRostering.getLunchEndTime());
                if (goOutEndTime.isBefore(lunchStartTime) || goOutStartTime.isAfter(lunchEndTime)) {
                    return ChronoUnit.SECONDS.between(goOutStartTime, goOutEndTime);
                } else if (!goOutEndTime.isBefore(lunchStartTime) && !goOutEndTime.isAfter(lunchEndTime)) {
                    return ChronoUnit.SECONDS.between(goOutStartTime, lunchStartTime);
                } else if (!goOutStartTime.isBefore(lunchStartTime) && !goOutStartTime.isAfter(lunchEndTime)) {
                    return ChronoUnit.SECONDS.between(lunchEndTime, goOutEndTime);
                } else {
                    return ChronoUnit.SECONDS.between(goOutStartTime, goOutEndTime) - 3600;
                }
            } else {
                LocalDateTime goOutStartTime = localDate.atTime(startTime);
                LocalDateTime goOutEndTime = localDate.atTime(endTime);
                return ChronoUnit.SECONDS.between(goOutStartTime, goOutEndTime);
            }
        }).reduce(0L, (result, current) -> result + current);
    }
    /**
     * 审核/撤销功能
     * @param resources /
     */
    @Override
    public void updateApprove(AttendanceGoOut resources) throws Exception {
        AttendanceGoOut attendanceGoOut = attendanceGoOutRepository.findById(resources.getId()).orElseGet(AttendanceGoOut::new);
        ValidationUtil.isNull( attendanceGoOut.getId(),"AttendanceGoOut","id",resources.getId());
        attendanceGoOut.copy(resources);
        attendanceGoOutRepository.save(attendanceGoOut);
        // 调用定时任务修改考勤记录
        List<User> userList = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(attendanceGoOut.getUserId())){
            User user = userRepository.findById(attendanceGoOut.getUserId()).orElseGet(User::new);
            userList.add(user);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String attendanceDate = df.format(attendanceGoOut.getOutStartTime());
        dingTalkService.getDingTalkAttendanceListOfNoonOrNight(attendanceDate,userList);
    }
    /**
     * 批量审核(外出)
     * @param request
     * @throws Exception
     */
    @Override
    public void updateAgree(AgreeUpdateRequest request) throws Exception {
        for (Long id : request.getIds()) {
            AttendanceGoOut attendanceGoOut = attendanceGoOutRepository.findById(id).orElseGet(AttendanceGoOut::new);
            ValidationUtil.isNull( attendanceGoOut.getId(),"AttendanceGoOut","id",id);
            if (request.getNum().equals(Long.valueOf(1))){
                attendanceGoOut.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_AGREE);
            } else {
                attendanceGoOut.setApprovalStatus(Constant.GOOUT_APPROVE_STATUS_REFUSE);
            }
            attendanceGoOutRepository.save(attendanceGoOut);
            // 调用定时任务修改考勤记录
            List<User> userList = new ArrayList<>();
            if(ObjectUtils.isNotEmpty(attendanceGoOut.getUserId())){
                User user = userRepository.findById(attendanceGoOut.getUserId()).orElseGet(User::new);
                userList.add(user);
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String attendanceDate = df.format(attendanceGoOut.getOutStartTime());
            dingTalkService.getDingTalkAttendanceListOfNoonOrNight(attendanceDate,userList);
        }
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceLeaveServiceImpl.java
@@ -1,573 +1,573 @@
/*
*  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 lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
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.AttendanceLeaveDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveQueryCriteria;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceLeaveMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.quartz.service.impl.DingTalkServiceImpl;
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.utils.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
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;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author wcd
* @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 OpaiDingTalkService opaiDingTalkService;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceRepository attendanceRepository;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    private final DingTalkServiceImpl dingTalkService;
    @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());
                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());
            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);
                i++;
                attendanceLeaveRepository.save(attendanceLeave);
                }
            }
            //发送钉钉给审批人
            List<String> sendList = new ArrayList<>();
            //查询审批者信息
            User appUser = userRepository.getOne(resources.getApprovalUserId());
            sendList.add(appUser.getDingding());
            opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了请假审批,请登录PMS系统处理", "card");
            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());
                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(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            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) {
                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++;
                    attendanceLeaveRepository.save(attendanceLeave1);
                }
            }
        }
    }
    /**
     * 验证其他状态的表是否有重复
     * @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)){
                //事假和年假
                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());
            result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            attendanceLeaveDto.setLeaveDurationUnit(Constant.LEAVE_TIME_TYPE_HOUR);
        }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) {
        //获取年假剩余(新)
        Double surplusYearTime = new Double(0.00);
        // 根据用户查询
        List<SysUserLevelOther> sysUserLevelOtherList = sysUserLevelOtherRepository.findByUserId(userId);
        if (sysUserLevelOtherList.size() > 0) {
            for (SysUserLevelOther sysUserLevelOther : sysUserLevelOtherList) {
                // 获取今年
                int year = Calendar.getInstance().get(Calendar.YEAR);
                if (!sysUserLevelOther.getYearMonth().isEmpty() && sysUserLevelOther.getYearMonth().substring(0,4).equals(String.valueOf(year))) {
                    //年假总时长
                    Double yearTime = Double.valueOf(sysUserLevelOther.getAnnualLeaveDays() == null ? 0 : sysUserLevelOther.getAnnualLeaveDays() * 8);
                    String startTime = year + "-01-01 00:00:00";
                    String endTime = year + "-12-31 23:59:59";
                    Double usedYearTime = attendanceLeaveRepository.getSurplusYearTime(sysUserLevelOther.getUserId(), startTime, endTime);
                    surplusYearTime = yearTime - (usedYearTime == null ? 0.0 : usedYearTime);
                }
            }
        }
        return surplusYearTime;
    }
    /**
     * 获取用户调休假剩余时长
     */
    @Override
    public Double getOverTimeLength(Long userId) {
        //获取年假剩余(新)
        Double surplusYearTime = new Double(0.00);
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findByUserId(userId);
        if (attendanceOvertimeList.size() > 0) {
            surplusYearTime = attendanceOvertimeList.stream()
                    .filter(attendanceOvertime -> attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_PASS))
                    .map(attendanceOvertime -> attendanceOvertime.getOvertimeDuration()).reduce(0.0, (o1, o2) -> o1 + o2);
            Double usedTime = attendanceLeaveRepository.sumLeaveDurationByUserIdAndLeaveType(userId, Constant.LEAVE_TYPE_REPLACE);
            if (usedTime != null) {
                surplusYearTime = surplusYearTime - usedTime;
            }
        }
        return surplusYearTime;
    }
    /**
     * 审核功能
     * @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);
        attendanceLeaveRepository.save(attendanceLeave);
        // 调用定时任务修改考勤记录
        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());
        dingTalkService.getDingTalkAttendanceListOfNoonOrNight(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(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
                if (!Long.valueOf(attendanceLeave1.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            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);
            }
            attendanceLeaveRepository.save(attendanceLeave);
            // 调用定时任务修改考勤记录
            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());
            dingTalkService.getDingTalkAttendanceListOfNoonOrNight(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);
    }
/*
*  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 lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
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.AttendanceLeaveDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveQueryCriteria;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceLeaveMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.quartz.service.impl.DingTalkServiceImpl;
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.utils.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
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;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author wcd
* @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 OpaiDingTalkService opaiDingTalkService;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceRepository attendanceRepository;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    private final DingTalkServiceImpl dingTalkService;
    @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());
                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());
            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);
                i++;
                attendanceLeaveRepository.save(attendanceLeave);
                }
            }
            //发送钉钉给审批人
            List<String> sendList = new ArrayList<>();
            //查询审批者信息
            User appUser = userRepository.getOne(resources.getApprovalUserId());
            sendList.add(appUser.getDingding());
            opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了请假审批,请登录PMS系统处理", "card");
            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());
                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(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            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) {
                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++;
                    attendanceLeaveRepository.save(attendanceLeave1);
                }
            }
        }
    }
    /**
     * 验证其他状态的表是否有重复
     * @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)){
                //事假和年假
                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());
            result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            attendanceLeaveDto.setLeaveDurationUnit(Constant.LEAVE_TIME_TYPE_HOUR);
        }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) {
        //获取年假剩余(新)
        Double surplusYearTime = new Double(0.00);
        // 根据用户查询
        List<SysUserLevelOther> sysUserLevelOtherList = sysUserLevelOtherRepository.findByUserId(userId);
        if (sysUserLevelOtherList.size() > 0) {
            for (SysUserLevelOther sysUserLevelOther : sysUserLevelOtherList) {
                // 获取今年
                int year = Calendar.getInstance().get(Calendar.YEAR);
                if (!sysUserLevelOther.getYearMonth().isEmpty() && sysUserLevelOther.getYearMonth().substring(0,4).equals(String.valueOf(year))) {
                    //年假总时长
                    Double yearTime = Double.valueOf(sysUserLevelOther.getAnnualLeaveDays() == null ? 0 : sysUserLevelOther.getAnnualLeaveDays() * 8);
                    String startTime = year + "-01-01 00:00:00";
                    String endTime = year + "-12-31 23:59:59";
                    Double usedYearTime = attendanceLeaveRepository.getSurplusYearTime(sysUserLevelOther.getUserId(), startTime, endTime);
                    surplusYearTime = yearTime - (usedYearTime == null ? 0.0 : usedYearTime);
                }
            }
        }
        return surplusYearTime;
    }
    /**
     * 获取用户调休假剩余时长
     */
    @Override
    public Double getOverTimeLength(Long userId) {
        //获取年假剩余(新)
        Double surplusYearTime = new Double(0.00);
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findByUserIdAndApprovalStatus(userId, Constant.OVERTIME_PASS);
        if (attendanceOvertimeList.size() > 0) {
            surplusYearTime = attendanceOvertimeList.stream()
                    .filter(attendanceOvertime -> !attendanceOvertime.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS))
                    .map(attendanceOvertime -> attendanceOvertime.getOvertimeDuration()).reduce(0.0, (o1, o2) -> o1 + o2);
            Double usedTime = attendanceLeaveRepository.sumLeaveDurationByUserIdAndLeaveType(userId, Constant.LEAVE_TYPE_REPLACE);
            if (usedTime != null) {
                surplusYearTime = surplusYearTime - usedTime;
            }
        }
        return surplusYearTime;
    }
    /**
     * 审核功能
     * @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);
        attendanceLeaveRepository.save(attendanceLeave);
        // 调用定时任务修改考勤记录
        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());
        dingTalkService.getDingTalkAttendanceListOfNoonOrNight(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(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
                if (!Long.valueOf(attendanceLeave1.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            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);
            }
            attendanceLeaveRepository.save(attendanceLeave);
            // 调用定时任务修改考勤记录
            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());
            dingTalkService.getDingTalkAttendanceListOfNoonOrNight(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);
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceOvertimeServiceImpl.java
@@ -1,245 +1,272 @@
/*
*  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 lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.AttendanceOvertimeRepository;
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
import me.zhengjie.modules.attendance.service.AttendanceOvertimeService;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceOvertimeDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceOvertimeQueryCriteria;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceOvertimeMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.SysRostering;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.UserRepository;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author weicd
* @date 2023-11-24
**/
@Service
@RequiredArgsConstructor
public class AttendanceOvertimeServiceImpl implements AttendanceOvertimeService {
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    private final AttendanceOvertimeMapper attendanceOvertimeMapper;
    private final AttendanceRepository attendanceRepository;
    private final DictDetailRepository dictDetailRepository;
    private final UserRepository userRepository;
    private final OpaiDingTalkService opaiDingTalkService;
    @Override
    public Map<String,Object> queryAll(AttendanceOvertimeQueryCriteria criteria, Pageable pageable){
        Page<AttendanceOvertime> page = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<AttendanceOvertime, AttendanceOvertimeDto> func = new Function<AttendanceOvertime, AttendanceOvertimeDto>(){
            @Override
            public AttendanceOvertimeDto apply(AttendanceOvertime attendanceOvertime) {
                // 将实体类转换成DTO
                AttendanceOvertimeDto attendanceOvertimeDto = attendanceOvertimeMapper.toDto(attendanceOvertime);
                //查询用户信息
                User user = userRepository.findById(attendanceOvertimeDto.getUserId()).orElseGet(User::new);
                attendanceOvertimeDto.setUserName(user.getNickName());
                //查询审批用户名
                User appUser = userRepository.findById(attendanceOvertimeDto.getApprovalUserId()).orElseGet(User::new);
                attendanceOvertimeDto.setAppUserName(appUser.getNickName());
                return attendanceOvertimeDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<AttendanceOvertimeDto> queryAll(AttendanceOvertimeQueryCriteria criteria) {
        List<AttendanceOvertimeDto> attendanceOvertimeDtoList = attendanceOvertimeMapper.toDto(attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        attendanceOvertimeDtoList.forEach(attendanceOvertimeDto -> {
            //查询用户信息
            User user = userRepository.findById(attendanceOvertimeDto.getUserId()).orElseGet(User::new);
            attendanceOvertimeDto.setUserName(user.getNickName());
            //查询审批用户名
            User appUser = userRepository.findById(attendanceOvertimeDto.getApprovalUserId()).orElseGet(User::new);
            attendanceOvertimeDto.setAppUserName(appUser.getNickName());
        });
        return attendanceOvertimeDtoList;
    }
    @Override
    @Transactional
    public AttendanceOvertimeDto findById(Long id) {
        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(id).orElseGet(AttendanceOvertime::new);
        ValidationUtil.isNull(attendanceOvertime.getId(),"AttendanceOvertime","id",id);
        return attendanceOvertimeMapper.toDto(attendanceOvertime);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceOvertimeDto create(AttendanceOvertime resources) {
        //查询考勤表是否有记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String attDate = sdf.format(resources.getOvertimeStartTime());
//        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
//        if(ObjectUtils.isEmpty(attendance)){
//            throw new BadRequestException("考勤记录不存在");
//        }
        resources.setApprovalStatus(Constant.OVERTIME_APPROVAL);
        try {
            //发送给审批者
            List<String> sendList = new ArrayList<>();
            //查询申请人信息
            User user = userRepository.getOne(resources.getUserId());
            //查询审批者信息
            User appUser = userRepository.getOne(resources.getApprovalUserId());
            sendList.add(appUser.getDingding());
            opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了加班审批,请登录PMS系统处理", "card");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return attendanceOvertimeMapper.toDto(attendanceOvertimeRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AttendanceOvertime resources) {
        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(resources.getId()).orElseGet(AttendanceOvertime::new);
        ValidationUtil.isNull( attendanceOvertime.getId(),"AttendanceOvertime","id",resources.getId());
        attendanceOvertime.copy(resources);
        //审核通过或者退回不能修改
        if(attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_PASS) || attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_RETURN)){
            throw new BadRequestException("审核通过或退回的不能进行修改");
        }
        //获取当前登入人信息
        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user1.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
        //查询考勤表是否有记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String attDate = sdf.format(resources.getOvertimeStartTime());
//        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
//        if(ObjectUtils.isEmpty(attendance)){
//            throw new BadRequestException("考勤记录不存在");
//        }
        attendanceOvertimeRepository.save(attendanceOvertime);
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            attendanceOvertimeRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<AttendanceOvertimeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceOvertimeDto attendanceOvertime : all) {
            String overtimeStatus = attendanceOvertime.getApprovalStatus() != null ? dictDetailRepository.findByDictNameAndValue("overtime_status", attendanceOvertime.getApprovalStatus()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请者", attendanceOvertime.getUserName());
            map.put("审批者", attendanceOvertime.getAppUserName());
            map.put("加班开始时间", attendanceOvertime.getOvertimeStartTime());
            map.put("加班结束时间", attendanceOvertime.getOvertimeEndTime());
            map.put("加班时长", attendanceOvertime.getOvertimeDuration());
            map.put("加班时长单位", attendanceOvertime.getOvertimeDurationUnit());
            map.put("审批状态", overtimeStatus);
            map.put("审批说明", attendanceOvertime.getApprovalDescription());
            map.put("备注", attendanceOvertime.getRemarks());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    /**
     * 计算加班时长
     * @param resources
     * @return
     */
    @Override
    public AttendanceOvertimeDto calcTimeLength(AttendanceOvertime resources) {
        AttendanceOvertimeDto attendanceOvertimeDto = new AttendanceOvertimeDto();
        User userInfo = userRepository.getOne(resources.getUserId());
        SysRostering sysRostering = userInfo.getSysRostering();
        long minutes = 0;
        if ((resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime()))
                && (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime()) )) {
            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes() - 60;
        } else if (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime()) ||
                resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime())) {
            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes();
        } else if (resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) && resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchStartTime()) &&
                (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchEndTime()))){
            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime().toLocalTime(), sysRostering.getLunchStartTime()).toMinutes();
        } else if ((resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime())) && resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime())) {
            minutes = Duration.between(sysRostering.getLunchEndTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes();
        }
        double hours = new BigDecimal((double) minutes / 60).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        attendanceOvertimeDto.setOvertimeDuration(hours);
        return attendanceOvertimeDto;
    }
    /**
     * 审核
     * @param resources /
     */
    @Override
    public void updateApprove(AttendanceOvertime resources) {
        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(resources.getId()).orElseGet(AttendanceOvertime::new);
        ValidationUtil.isNull( attendanceOvertime.getId(),"AttendanceOvertime","id",resources.getId());
        attendanceOvertime.copy(resources);
        attendanceOvertimeRepository.save(attendanceOvertime);
    }
/*
*  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 lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.AttendanceOvertimeRepository;
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
import me.zhengjie.modules.attendance.service.AttendanceOvertimeService;
import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceOvertimeDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceOvertimeQueryCriteria;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceOvertimeMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.SysRostering;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.UserRepository;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author weicd
* @date 2023-11-24
**/
@Service
@RequiredArgsConstructor
public class AttendanceOvertimeServiceImpl implements AttendanceOvertimeService {
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    private final AttendanceOvertimeMapper attendanceOvertimeMapper;
    private final AttendanceRepository attendanceRepository;
    private final DictDetailRepository dictDetailRepository;
    private final UserRepository userRepository;
    private final OpaiDingTalkService opaiDingTalkService;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    @Override
    public Map<String,Object> queryAll(AttendanceOvertimeQueryCriteria criteria, Pageable pageable){
        Page<AttendanceOvertime> page = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<AttendanceOvertime, AttendanceOvertimeDto> func = new Function<AttendanceOvertime, AttendanceOvertimeDto>(){
            @Override
            public AttendanceOvertimeDto apply(AttendanceOvertime attendanceOvertime) {
                // 将实体类转换成DTO
                AttendanceOvertimeDto attendanceOvertimeDto = attendanceOvertimeMapper.toDto(attendanceOvertime);
                //查询用户信息
                User user = userRepository.findById(attendanceOvertimeDto.getUserId()).orElseGet(User::new);
                attendanceOvertimeDto.setUserName(user.getNickName());
                //查询审批用户名
                User appUser = userRepository.findById(attendanceOvertimeDto.getApprovalUserId()).orElseGet(User::new);
                attendanceOvertimeDto.setAppUserName(appUser.getNickName());
                return attendanceOvertimeDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<AttendanceOvertimeDto> queryAll(AttendanceOvertimeQueryCriteria criteria) {
        List<AttendanceOvertimeDto> attendanceOvertimeDtoList = attendanceOvertimeMapper.toDto(attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        attendanceOvertimeDtoList.forEach(attendanceOvertimeDto -> {
            //查询用户信息
            User user = userRepository.findById(attendanceOvertimeDto.getUserId()).orElseGet(User::new);
            attendanceOvertimeDto.setUserName(user.getNickName());
            //查询审批用户名
            User appUser = userRepository.findById(attendanceOvertimeDto.getApprovalUserId()).orElseGet(User::new);
            attendanceOvertimeDto.setAppUserName(appUser.getNickName());
        });
        return attendanceOvertimeDtoList;
    }
    @Override
    @Transactional
    public AttendanceOvertimeDto findById(Long id) {
        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(id).orElseGet(AttendanceOvertime::new);
        ValidationUtil.isNull(attendanceOvertime.getId(),"AttendanceOvertime","id",id);
        return attendanceOvertimeMapper.toDto(attendanceOvertime);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceOvertimeDto create(AttendanceOvertime resources) {
        //查询考勤表是否有记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String attDate = sdf.format(resources.getOvertimeStartTime());
//        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
//        if(ObjectUtils.isEmpty(attendance)){
//            throw new BadRequestException("考勤记录不存在");
//        }
        SysConfigHoliday sysConfigHoliday = sysConfigHolidayRepository.findByHolidayDate(resources.getOvertimeStartTime().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        if (sysConfigHoliday != null && sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
            resources.setDateType(Constant.DATE_TYPE_LEGAL_HOLIDAYS);
        } else {
            resources.setDateType(Constant.DATE_TYPE_WEEKEND);
        }
        resources.setApprovalStatus(Constant.OVERTIME_APPROVAL);
        try {
            //发送给审批者
            List<String> sendList = new ArrayList<>();
            //查询申请人信息
            User user = userRepository.getOne(resources.getUserId());
            //查询审批者信息
            User appUser = userRepository.getOne(resources.getApprovalUserId());
            sendList.add(appUser.getDingding());
            opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了加班审批,请登录PMS系统处理", "card");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return attendanceOvertimeMapper.toDto(attendanceOvertimeRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AttendanceOvertime resources) {
        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(resources.getId()).orElseGet(AttendanceOvertime::new);
        ValidationUtil.isNull( attendanceOvertime.getId(),"AttendanceOvertime","id",resources.getId());
        attendanceOvertime.copy(resources);
        //审核通过或者退回不能修改
        if(attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_PASS) || attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_RETURN)){
            throw new BadRequestException("审核通过或退回的不能进行修改");
        }
        SysConfigHoliday sysConfigHoliday = sysConfigHolidayRepository.findByHolidayDate(resources.getOvertimeStartTime().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        if (sysConfigHoliday != null && sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
            resources.setDateType(Constant.DATE_TYPE_LEGAL_HOLIDAYS);
        } else {
            resources.setDateType(Constant.DATE_TYPE_WEEKEND);
        }
        //获取当前登入人信息
        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user1.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
//        //查询考勤表是否有记录
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String attDate = sdf.format(resources.getOvertimeStartTime());
//        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
//        if(ObjectUtils.isEmpty(attendance)){
//            throw new BadRequestException("考勤记录不存在");
//        }
        attendanceOvertimeRepository.save(attendanceOvertime);
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            attendanceOvertimeRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<AttendanceOvertimeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceOvertimeDto attendanceOvertime : all) {
            String overtimeStatus = attendanceOvertime.getApprovalStatus() != null ? dictDetailRepository.findByDictNameAndValue("overtime_status", attendanceOvertime.getApprovalStatus()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请者", attendanceOvertime.getUserName());
            map.put("审批者", attendanceOvertime.getAppUserName());
            map.put("加班开始时间", attendanceOvertime.getOvertimeStartTime());
            map.put("加班结束时间", attendanceOvertime.getOvertimeEndTime());
            map.put("加班时长", attendanceOvertime.getOvertimeDuration());
            map.put("加班时长单位", attendanceOvertime.getOvertimeDurationUnit());
            map.put("审批状态", overtimeStatus);
            map.put("审批说明", attendanceOvertime.getApprovalDescription());
            map.put("备注", attendanceOvertime.getRemarks());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    /**
     * 计算加班时长
     * @param resources
     * @return
     */
    @Override
    public AttendanceOvertimeDto calcTimeLength(AttendanceOvertime resources) {
        AttendanceOvertimeDto attendanceOvertimeDto = new AttendanceOvertimeDto();
        User userInfo = userRepository.getOne(resources.getUserId());
        SysRostering sysRostering = userInfo.getSysRostering();
        long minutes = 0;
        if (sysRostering.getWorkEndTime().isBefore(resources.getOvertimeEndTime().toLocalDateTime().toLocalTime()) &&
                sysRostering.getWorkEndTime().plusMinutes(30).isAfter(resources.getOvertimeEndTime().toLocalDateTime().toLocalTime())) {
            resources.setOvertimeEndTime(Timestamp.valueOf(resources.getOvertimeEndTime().toLocalDateTime().with(sysRostering.getWorkEndTime())));
        }
        if ((resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime()))
                && (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime()) )) {
            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes() - 60;
        } else if (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime()) ||
                resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime())) {
            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes();
        } else if (resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) && resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchStartTime()) &&
                (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchEndTime()))){
            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime().toLocalTime(), sysRostering.getLunchStartTime()).toMinutes();
        } else if ((resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime())) && resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime())) {
            minutes = Duration.between(sysRostering.getLunchEndTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes();
        }
        if (sysRostering.getWorkEndTime().isBefore(resources.getOvertimeEndTime().toLocalDateTime().toLocalTime())) {
            minutes -= 30;
        }
        double hours = new BigDecimal((double) minutes / 60).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        attendanceOvertimeDto.setOvertimeDuration(hours);
        return attendanceOvertimeDto;
    }
    /**
     * 审核
     * @param resources /
     */
    @Override
    public void updateApprove(AttendanceOvertime resources) {
        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(resources.getId()).orElseGet(AttendanceOvertime::new);
        ValidationUtil.isNull( attendanceOvertime.getId(),"AttendanceOvertime","id",resources.getId());
        attendanceOvertime.copy(resources);
        attendanceOvertimeRepository.save(attendanceOvertime);
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceServiceImpl.java
@@ -1,656 +1,796 @@
/*
*  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 lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.*;
import me.zhengjie.modules.attendance.service.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.*;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.impl.DingTalkServiceImpl;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.SysRostering;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.dto.SysConfigHolidayQueryCriteria;
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.stereotype.Service;
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.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author wcd
* @date 2022-12-14
**/
@Service
@RequiredArgsConstructor
public class AttendanceServiceImpl implements AttendanceService {
    private final AttendanceRepository attendanceRepository;
    private final AttendanceMapper attendanceMapper;
    private final UserRepository userRepository;
    private final DictDetailRepository dictDetailRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceLeaveRepository attendanceLeaveRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    private final DingTalkServiceImpl dingTalkService;
    @Override
    public Map<String,Object> queryAll(AttendanceQueryCriteria criteria, Pageable pageable){
        Page<Attendance> page = attendanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<Attendance, AttendanceDto> func = new Function<Attendance, AttendanceDto>(){
            @Override
            public AttendanceDto apply(Attendance attendance) {
                // 将实体类转换成DTO
                AttendanceDto attendanceDto = attendanceMapper.toDto(attendance);
                //查询用户信息
                User user = userRepository.findById(attendanceDto.getUserId()).orElseGet(User::new);
                attendanceDto.setUserName(user.getNickName());
                return attendanceDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<AttendanceDto> queryAll(AttendanceQueryCriteria criteria){
        return attendanceMapper.toDto(attendanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
    @Override
    @Transactional
    public AttendanceDto findById(Long id) {
        Attendance attendance = attendanceRepository.findById(id).orElseGet(Attendance::new);
        ValidationUtil.isNull(attendance.getId(),"Attendance","id",id);
        return attendanceMapper.toDto(attendance);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceDto create(Attendance resources) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        // 查询用户
        User user = userRepository.findById(resources.getUserId()).orElseGet(User::new);
        resources.setRosteringLunchStartTime(Timestamp.valueOf(df.format(resources.getAttendanceDate()) + " " + dateTimeFormatter.format(user.getSysRostering().getLunchStartTime())));
        resources.setRosteringLunchEndTime(Timestamp.valueOf(df.format(resources.getAttendanceDate()) + " " + dateTimeFormatter.format(user.getSysRostering().getLunchEndTime())));
        return attendanceMapper.toDto(attendanceRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Attendance resources) {
        Attendance attendance = attendanceRepository.findById(resources.getId()).orElseGet(Attendance::new);
        ValidationUtil.isNull( attendance.getId(),"Attendance","id",resources.getId());
        attendance.copy(resources);
        //获取当前登入人信息
        User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
        attendanceRepository.save(attendance);
    }
    /**
     * 计算时间(小时)
     * @param userId
     * @return
     */
    @Override
    public Integer calculateTimes(Calculate calculate, Long userId) {
        User userInfo = userRepository.getOne(userId);
        SysRostering sysRostering = userInfo.getSysRostering();
        //计算天数
        Integer count = calculateDays(calculate);
        Calculate startCalculate = new Calculate();
        startCalculate.setStart(calculate.getStart());
        startCalculate.setEnd(calculate.getStart());
        Integer startDays = calculateDays(startCalculate);
        Calculate endCalculate = new Calculate();
        endCalculate.setStart(calculate.getEnd());
        endCalculate.setEnd(calculate.getEnd());
        Integer endDays = calculateDays(endCalculate);
        Integer time = 0;
        time = (count - startDays - endDays) * 8 * 3600;
        calculate.setStart(formateDateTime(calculate.getStart(), sysRostering));
        calculate.setEnd(formateDateTime(calculate.getEnd(), sysRostering));
        if (startDays > 0) {
            Duration startDuration = Duration.between(calculate.getStart(), calculate.getStart().toLocalDate().atTime(sysRostering.getWorkEndTime()));
            Long StartSeconds = startDuration.getSeconds();
            if (calculate.getStart().toLocalTime().isBefore(LocalTime.NOON)) {
                time += StartSeconds.intValue() - 3600;
            }else if(calculate.getStart().toLocalTime().compareTo(LocalTime.NOON) >= 0 && calculate.getStart().toLocalTime().compareTo(calculate.getStart().toLocalDate().atTime(sysRostering.getLunchEndTime()).toLocalTime()) < 0){
                //补充,请假开始时间大于等于中午基准休息时间小于休息结束时间
                time += StartSeconds.intValue() - 3600;
            } else {
                time += StartSeconds.intValue();
            }
        }
        if (endDays > 0) {
            Duration endDuration = Duration.between(calculate.getEnd().toLocalDate().atTime(sysRostering.getWorkStartTime()), calculate.getEnd());
            Long endSeconds = endDuration.getSeconds();
            if (calculate.getEnd().toLocalTime().isAfter(LocalTime.NOON)) {
                time += endSeconds.intValue() - 3600;
            } else {
                time += endSeconds.intValue();
            }
        }
        return time;
    }
    /**
     * 计算时间(天)
     * @param calculate
     * @return
     */
    @Override
    public Integer calculateDays(Calculate calculate) {
        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));
            }
        }
        Long chronoUnit =  ChronoUnit.DAYS.between(calculate.getStart().toLocalDate(), calculate.getEnd().toLocalDate());
        Integer count = 0;
        for (Integer i = 0; i <= chronoUnit; i++) {
            LocalDate date = calculate.getStart().toLocalDate().plusDays(i);
            Boolean isWeekend = date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY;
            if ((!isWeekend && !holiday.contains(date.toString())) || (isWeekend && isWork.contains(date.toString()))) {
                count++;
            }
        }
        return count;
    }
    public LocalDateTime formateDateTime(LocalDateTime localDateTime, SysRostering sysRostering) {
        if (localDateTime.toLocalTime().isBefore(sysRostering.getWorkStartTime())) {
            return localDateTime.toLocalDate().atTime(sysRostering.getWorkStartTime());
        } else if (localDateTime.toLocalTime().isAfter(sysRostering.getLunchStartTime()) && localDateTime.toLocalTime().isBefore(sysRostering.getLunchEndTime())) {
            return localDateTime.toLocalDate().atTime(sysRostering.getLunchEndTime());
        } else if (localDateTime.toLocalTime().isAfter(sysRostering.getWorkEndTime())) {
            return localDateTime.toLocalDate().atTime(sysRostering.getWorkEndTime());
        }
        return localDateTime;
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //获取当前登入人信息
            User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
            Role role = user.getRoles().iterator().next();
            //根据id查询记录
            Optional<Attendance> attendance = attendanceRepository.findById(id);
            //除超管、总经理只能删除自己信息
            if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
                if (!Long.valueOf(attendance.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            attendanceRepository.deleteById(id);
        }
    }
    /**
     * 补卡判断登录人
     */
    @Override
    public void getUserMakeUpCard(String userId) {
        //获取当前登入人信息
        User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user.getRoles().iterator().next();
        //除超管、总经理只能补自己的卡
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(userId).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能补自己的卡");
            }
        }
    }
    /**
     * 补充考勤信息
     * @param attendance
     */
    @Override
    public void addAttendanceInfo(Attendance attendance) throws Exception {
        // 获取今天日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String todayDate = sdf.format(new Date());
        if(attendance.getAttendanceDate().compareTo(Timestamp.valueOf(todayDate)) >= 0){
            throw new BadRequestException("只能更新小于等于今天的考勤信息");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String attendanceDate = df.format(attendance.getAttendanceDate());
        List<User> userList = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(attendance.getUserId())){
            User user = userRepository.findById(attendance.getUserId()).orElseGet(User::new);
            userList.add(user);
        }
        // 调用0时定时任务
        dingTalkService.getDingTalkAttendanceList(attendance.getAttendanceDate(), userList);
        // 选择日期和员工更新员工的考勤信息,未选择员工则更新所有人
        dingTalkService.getDingTalkAttendanceListOfNoonOrNight(attendanceDate ,userList);
    }
    @Override
    public void download(List<AttendanceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceDto attendance : all) {
            String startLocationResults = attendance.getStartLocationResults() != null ? dictDetailRepository.findByDictNameAndValue("location_results", attendance.getStartLocationResults()).getLabel() : "";
            String startClockResults = attendance.getStartClockResults() != null ? dictDetailRepository.findByDictNameAndValue("attendance_state", attendance.getStartClockResults()).getLabel() : "";
            String endLocationResults = attendance.getEndLocationResults() != null ? dictDetailRepository.findByDictNameAndValue("location_results", attendance.getEndLocationResults()).getLabel() : "";
            String endClockResults = attendance.getEndClockResults() != null ? dictDetailRepository.findByDictNameAndValue("attendance_state", attendance.getEndClockResults()).getLabel() : "";
            String dateType = attendance.getDateType() != null ? dictDetailRepository.findByDictNameAndValue("date_type", attendance.getDateType()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("员工", attendance.getUserName());
            map.put("考勤日期", attendance.getAttendanceDate());
            map.put("排班工作开始时间", attendance.getRosteringWorkStartTime());
            map.put("实际工作开始时间", attendance.getActualWorkStartTime());
            map.put("开始位置结果",startLocationResults);
            map.put("开始打卡结果",startClockResults);
            map.put("排班工作结束时间", attendance.getRosteringWorkEndTime());
            map.put("实际工作结束时间", attendance.getActualWorkEndTime());
            map.put("结束位置结果",endLocationResults);
            map.put("结束打卡结果",endClockResults);
            map.put("日期类型",dateType);
            map.put("备注", attendance.getRemarks());
            map.put("创建者", attendance.getCreateBy());
            map.put("创建时间", attendance.getCreateTime());
            map.put("更新者", attendance.getUpdateBy());
            map.put("更新时间", attendance.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public Double queryAttendanceHours(Long userId, String date) {
        Attendance attendanceDate = attendanceRepository.findAllByUserIdAndAttendanceDate(userId, date);
        List<Calculate> resultParts = new ArrayList<>();
        LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDateTime startOfDate = localDate.atTime(0, 0, 0);
        LocalDateTime endOfDate = localDate.atTime(23, 59, 59);
        LocalDateTime actualWorkStartTime = attendanceDate.getActualWorkStartTime() == null ? null : attendanceDate.getActualWorkStartTime().toLocalDateTime();
        LocalDateTime actualWorkEndTime = attendanceDate.getActualWorkEndTime() == null ? null : attendanceDate.getActualWorkEndTime().toLocalDateTime();
        LocalDateTime rosteringWorkStartTime = attendanceDate.getRosteringWorkStartTime() == null ? null : attendanceDate.getRosteringWorkStartTime().toLocalDateTime();
        LocalDateTime rosteringLunchStartTime = attendanceDate.getRosteringLunchStartTime() == null ? null : attendanceDate.getRosteringLunchStartTime().toLocalDateTime();
        LocalDateTime rosteringLunchEndTime = attendanceDate.getRosteringLunchEndTime() == null ? null : attendanceDate.getRosteringLunchEndTime().toLocalDateTime();
        LocalDateTime rosteringWorkEndTime = attendanceDate.getRosteringWorkEndTime() == null ? null : attendanceDate.getRosteringWorkEndTime().toLocalDateTime();
        // 出差信息(出差时无打卡信息,用出差信息补充)
        AttendanceBusinessTravel attendanceBusinessTravel = attendanceBusinessTravelRepository.findByUserAndDate(userId, startOfDate, endOfDate);
        if (attendanceBusinessTravel != null) {
            actualWorkStartTime = rosteringWorkStartTime;
            actualWorkEndTime = rosteringWorkEndTime;
        }
        if (actualWorkStartTime != null && actualWorkStartTime.isBefore(rosteringWorkStartTime)) {
            actualWorkStartTime = rosteringWorkStartTime;
        }
//        if (actualWorkEndTime != null && actualWorkEndTime.isAfter(rosteringWorkEndTime)) {
//            actualWorkEndTime = rosteringWorkEndTime;
//        }
        List<Calculate> attendanceParts = new ArrayList<>();
        // 当日打卡信息不全不算
        if (actualWorkStartTime != null && actualWorkEndTime != null) {
            attendanceParts.add(new Calculate(actualWorkStartTime, actualWorkEndTime));
        }
        // 休息时间管理
        List<Calculate> breakParts = new ArrayList<>();
        breakParts.add(new Calculate(rosteringLunchStartTime, rosteringLunchEndTime));
        // 外出信息
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(userId, startOfDate, endOfDate);
        attendanceParts.addAll(
                attendanceGoOutList.stream().map(attendanceGoOut ->
                        new Calculate(attendanceGoOut.getOutStartTime().toLocalDateTime(), attendanceGoOut.getOutEndTime().toLocalDateTime())
                ).collect(Collectors.toList())
        );
        // 周末加班
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findByUserIdAndDate(userId, startOfDate, endOfDate);
        attendanceParts.addAll(
                attendanceOvertimeList.stream().map(attendanceOvertime ->
                        new Calculate(attendanceOvertime.getOvertimeStartTime().toLocalDateTime(), attendanceOvertime.getOvertimeEndTime().toLocalDateTime())
                ).collect(Collectors.toList())
        );
        attendanceParts.stream().sorted().reduce(new Stack<Calculate>(), (result, current) -> {
            // 删除重复时间,合并相连的时间段
            if (result.empty()) {
                result.push(current);
                return result;
            }
            Calculate last = result.peek();
            if (last.getEnd().isBefore(current.getStart())) {
                result.push(current);
            } else if (last.getEnd().isBefore(current.getEnd())) {
                last.setEnd(current.getEnd());
            }
            return result;
        }, (o1, o2) -> null).forEach(calculate -> {
            // 去除休息时间:午休等
            for (Calculate breakPart : breakParts) {
                if ((calculate.getStart().isBefore(breakPart.getStart()) && calculate.getEnd().isAfter(breakPart.getStart()))
                        || (calculate.getStart().isBefore(breakPart.getEnd()) && calculate.getEnd().isAfter(breakPart.getEnd()))) {
                    Calculate calculate1 = new Calculate(calculate.getStart(), breakPart.getStart());
                    Calculate calculate2 = new Calculate(breakPart.getEnd(), calculate.getEnd());
                    if (calculate1.getStart().isBefore(calculate1.getEnd())) {
                        resultParts.add(calculate1);
                    }
                    if (calculate2.getStart().isBefore(calculate2.getEnd())) {
                        resultParts.add(calculate2);
                    }
                } else {
                    resultParts.add(calculate);
                }
            }
        });
        // 请假信息
        List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.findByUserIdAndDate(userId, startOfDate, endOfDate);
//        // 加班信息
//        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findByUserIdAndDate(userId, startOfDate, endOfDate);
        // 出勤时间累计
        BigDecimal result = resultParts.stream()
                .map(calculate -> ChronoUnit.SECONDS.between(calculate.getStart(), calculate.getEnd()))
                .reduce(new BigDecimal(0),
                        (total, current) -> total.add(BigDecimal.valueOf(current)),
                        (o1, o2) -> null).divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP
                );
        BigDecimal annualLeaveHours = attendanceLeaveList.stream()
                .filter(attendanceLeave -> Constant.LEAVE_TYPE_ANNUAL_LEAVE.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_MARRIAGE_HOLIDAY.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_BEREAVEMENT_LEAVE.equals(attendanceLeave.getLeaveType())
//                    || Constant.LEAVE_TYPE_REPLACE.equals(attendanceLeave.getLeaveType())
                ).map(attendanceLeave -> BigDecimal.valueOf(attendanceLeave.getLeaveDuration())).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        return result.add(annualLeaveHours).doubleValue();
    }
    @Override
    public Double queryAttendanceHours(AttendanceQueryCriteria criteria) {
        // 节日检索类
        SysConfigHolidayQueryCriteria sysConfigHolidayQueryCriteria = new SysConfigHolidayQueryCriteria();
        sysConfigHolidayQueryCriteria.setHolidayDateLike(criteria.getTargetYearMonth().substring(0,7));
        // 获取本月节日列表
        List<SysConfigHoliday> sysConfigHolidayMonthList = sysConfigHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,sysConfigHolidayQueryCriteria,criteriaBuilder));
        LocalDate startDate = LocalDate.parse(criteria.getTargetYearMonth(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate = startDate.plusMonths(1).minusDays(1);
        Long distance = ChronoUnit.DAYS.between(startDate, endDate);
        return Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).filter(localDate -> {
            for (SysConfigHoliday sysConfigHoliday : sysConfigHolidayMonthList) {
                if (sysConfigHoliday.getHolidayDate().toLocalDateTime().isEqual(localDate.atStartOfDay())) {
                    return Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHoliday.getDateType());
                }
            }
            return localDate.getDayOfWeek() != DayOfWeek.SATURDAY && localDate.getDayOfWeek() != DayOfWeek.SUNDAY;
        }).map(localDate -> {
            System.out.print("localDate : " + localDate);
            LocalDateTime startOfDate = localDate.atTime(0, 0, 0);
            LocalDateTime endOfDate = localDate.atTime(23, 59, 59);
            AttendanceBusinessTravel attendanceBusinessTravel = attendanceBusinessTravelRepository.findByUserAndDate(criteria.getUserId(), startOfDate, endOfDate);
            if (attendanceBusinessTravel != null) {
                System.out.println("\t hours1 : " + 8);
                return BigDecimal.valueOf(8.0);
            }
            Attendance attendanceDate = attendanceRepository.findAllByUserIdAndAttendanceDate(criteria.getUserId(), localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            if (attendanceDate == null) {
                System.out.println("\t hours2 : " + 0);
                return BigDecimal.valueOf(0.0);
            }
            LocalDateTime actualWorkStartTime = attendanceDate.getActualWorkStartTime() == null ? null : attendanceDate.getActualWorkStartTime().toLocalDateTime();
            LocalDateTime actualWorkEndTime = attendanceDate.getActualWorkEndTime() == null ? null : attendanceDate.getActualWorkEndTime().toLocalDateTime();
            LocalDateTime rosteringWorkStartTime = attendanceDate.getRosteringWorkStartTime() == null ? null : attendanceDate.getRosteringWorkStartTime().toLocalDateTime();
            LocalDateTime rosteringLunchStartTime = attendanceDate.getRosteringLunchStartTime() == null ? null : attendanceDate.getRosteringLunchStartTime().toLocalDateTime();
            LocalDateTime rosteringLunchEndTime = attendanceDate.getRosteringLunchEndTime() == null ? null : attendanceDate.getRosteringLunchEndTime().toLocalDateTime();
            LocalDateTime rosteringWorkEndTime = attendanceDate.getRosteringWorkEndTime() == null ? null : attendanceDate.getRosteringWorkEndTime().toLocalDateTime();
            if (actualWorkStartTime != null && actualWorkStartTime.isBefore(rosteringWorkStartTime)) {
                actualWorkStartTime = rosteringWorkStartTime;
            }
            if (actualWorkEndTime != null && actualWorkEndTime.isAfter(rosteringWorkEndTime)) {
                actualWorkEndTime = rosteringWorkEndTime;
            }
            List<Calculate> attendanceParts = new ArrayList<>();
            // 当日打卡信息不全不算
            if (actualWorkStartTime != null && actualWorkEndTime != null) {
                attendanceParts.add(new Calculate(actualWorkStartTime, actualWorkEndTime));
            }
            // 休息时间管理
            List<Calculate> breakParts = new ArrayList<>();
            breakParts.add(new Calculate(rosteringLunchStartTime, rosteringLunchEndTime));
            // 外出信息
            List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(criteria.getUserId(), startOfDate, endOfDate);
            attendanceParts.addAll(
                    attendanceGoOutList.stream().map(attendanceGoOut -> {
                        LocalDateTime attendanceGoOutStart = attendanceGoOut.getOutStartTime().toLocalDateTime();
                        LocalDateTime attendanceGoOutEnd = attendanceGoOut.getOutEndTime().toLocalDateTime();
                        if (attendanceGoOutStart.isBefore(rosteringWorkStartTime)) {
                            attendanceGoOutStart = rosteringWorkStartTime;
                        }
                        if (attendanceGoOutEnd.isAfter(rosteringWorkEndTime)) {
                            attendanceGoOutEnd = rosteringWorkEndTime;
                        }
                        return new Calculate(attendanceGoOutStart, attendanceGoOutEnd);
                    }).filter(calculate -> calculate.getStart().isBefore(calculate.getEnd())).collect(Collectors.toList())
            );
            List<Calculate> resultParts = new ArrayList<>();
            attendanceParts.stream().sorted().reduce(new Stack<Calculate>(), (result, current) -> {
                // 删除重复时间,合并相连的时间段
                if (result.empty()) {
                    result.push(current);
                    return result;
                }
                Calculate last = result.peek();
                if (last.getEnd().isBefore(current.getStart())) {
                    result.push(current);
                } else if (last.getEnd().isBefore(current.getEnd())) {
                    last.setEnd(current.getEnd());
                }
                return result;
            }, (o1, o2) -> null).forEach(calculate -> {
                // 去除休息时间:午休等
                for (Calculate breakPart : breakParts) {
                    if ((calculate.getStart().isBefore(breakPart.getStart()) && calculate.getEnd().isAfter(breakPart.getStart()))
                            || (calculate.getStart().isBefore(breakPart.getEnd()) && calculate.getEnd().isAfter(breakPart.getEnd()))) {
                        Calculate calculate1 = new Calculate(calculate.getStart(), breakPart.getStart());
                        Calculate calculate2 = new Calculate(breakPart.getEnd(), calculate.getEnd());
                        if (calculate1.getStart().isBefore(calculate1.getEnd())) {
                            resultParts.add(calculate1);
                        }
                        if (calculate2.getStart().isBefore(calculate2.getEnd())) {
                            resultParts.add(calculate2);
                        }
                    } else {
                        resultParts.add(calculate);
                    }
                }
            });
            // 出勤时间累计
            BigDecimal result = resultParts.stream()
                    .map(calculate -> ChronoUnit.SECONDS.between(calculate.getStart(), calculate.getEnd()))
                    .reduce(new BigDecimal(0),
                            (total, current) -> total.add(BigDecimal.valueOf(current)),
                            (o1, o2) -> null).divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP
                    );
            // 请假信息
            List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.findByUserIdAndDate(criteria.getUserId(), startOfDate, endOfDate);
            // 年假不扣工时
            BigDecimal annualLeaveHours = attendanceLeaveList.stream()
                    .filter(attendanceLeave -> Constant.LEAVE_TYPE_ANNUAL_LEAVE.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_MARRIAGE_HOLIDAY.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_BEREAVEMENT_LEAVE.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_REPLACE.equals(attendanceLeave.getLeaveType()))
                    .map(attendanceLeave -> {
                        if (Constant.LEAVE_TIME_TYPE_HOUR.equals(attendanceLeave.getLeaveDurationUnit())) {
                            return BigDecimal.valueOf(attendanceLeave.getLeaveDuration());
                        } else {
                            return BigDecimal.valueOf(attendanceLeave.getLeaveDuration()).multiply(BigDecimal.valueOf(8));
                        }
                    }).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            if (result.add(annualLeaveHours).compareTo(BigDecimal.valueOf(8.0)) > 0) {
                System.out.println("\t hours3 : " + 8);
                return BigDecimal.valueOf(8.0);
            }
            System.out.println("\t hours4 : " + result.add(annualLeaveHours));
            return result.add(annualLeaveHours);
        }).reduce(BigDecimal::add).get().doubleValue();
    }
    /**
     * 设置日历类
     * @return
     */
    private Calendar setUpCalendar(String targetYearMonth) {
        // 日历类
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, Integer.valueOf(targetYearMonth.substring(0,4)));
        // 设置月份
        cal.set(Calendar.MONTH, Integer.valueOf(targetYearMonth.substring(5,7)) - 1);
        // 日历类
        return cal;
    }
    /**
     * 获取有效时长
     * @param attendanceDay
     * @param startTime
     * @param endTime
     * @return
     */
    private Long getValidDuration(Attendance attendanceDay, Timestamp startTime, Timestamp endTime) {
        // 判断开始时间与结束时间
        if (endTime.getTime() < startTime.getTime()) {
            throw new BadRequestException("结束时间应大于开始时间!");
        }
        // 判断开始时间
        if (startTime.getTime() < attendanceDay.getRosteringWorkStartTime().getTime()) {
            // 判断结束时间
            if (endTime.getTime() < attendanceDay.getRosteringWorkStartTime().getTime()) {
                // 返回有效时长 = 0
                return 0L;
            } else if (endTime.getTime() < attendanceDay.getRosteringLunchStartTime().getTime()) {
                // 返回有效时长 = 结束时间 - 排班工作开始时间
                return endTime.getTime() - attendanceDay.getRosteringWorkStartTime().getTime();
            } else if (endTime.getTime() < attendanceDay.getRosteringLunchEndTime().getTime()) {
                // 返回有效时长 = 排班午休开始时间 - 排班工作开始时间
                return attendanceDay.getRosteringLunchStartTime().getTime() - attendanceDay.getRosteringWorkStartTime().getTime();
            } else if (endTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
                // 返回有效时长 = (排班午休开始时间 - 排班工作开始时间) + (结束时间 - 排班午休结束时间)
                return (attendanceDay.getRosteringLunchStartTime().getTime() - attendanceDay.getRosteringWorkStartTime().getTime()) + (endTime.getTime() - attendanceDay.getRosteringLunchEndTime().getTime());
            } else {
                // 返回有效时长 = (排班午休开始时间 - 排班工作开始时间) + (排班工作结束时间 - 排班午休结束时间)
                return (attendanceDay.getRosteringLunchStartTime().getTime() - attendanceDay.getRosteringWorkStartTime().getTime()) + (attendanceDay.getRosteringWorkEndTime().getTime() - attendanceDay.getRosteringLunchEndTime().getTime());
            }
        } else if (startTime.getTime() < attendanceDay.getRosteringLunchStartTime().getTime()) {
            // 判断结束时间
            if (endTime.getTime() < attendanceDay.getRosteringLunchStartTime().getTime()) {
                // 返回有效时长 = 结束时间 - 开始时间
                return endTime.getTime() - startTime.getTime();
            } else if (endTime.getTime() < attendanceDay.getRosteringLunchEndTime().getTime()) {
                // 返回有效时长 = 排班午休开始时间 - 开始时间
                return attendanceDay.getRosteringLunchStartTime().getTime() - startTime.getTime();
            } else if (endTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
                // 返回有效时长 = (排班午休开始时间 - 开始时间) + (结束时间 - 排班午休结束时间)
                return (attendanceDay.getRosteringLunchStartTime().getTime() - startTime.getTime()) + (endTime.getTime() - attendanceDay.getRosteringLunchEndTime().getTime());
            } else {
                // 返回有效时长 = (排班午休开始时间 - 开始时间) + (排班工作结束时间 - 排班午休结束时间)
                return (attendanceDay.getRosteringLunchStartTime().getTime() - startTime.getTime()) + (attendanceDay.getRosteringWorkEndTime().getTime() - attendanceDay.getRosteringLunchEndTime().getTime());
            }
        } else if (startTime.getTime() < attendanceDay.getRosteringLunchEndTime().getTime()) {
            // 判断结束时间
            if (endTime.getTime() < attendanceDay.getRosteringLunchEndTime().getTime()) {
                // 返回有效时长 = 0
                return 0L;
            } else if (endTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
                // 返回有效时长 = 结束时间 - 排班午休结束时间
                return endTime.getTime() - attendanceDay.getRosteringLunchEndTime().getTime();
            } else {
                // 返回有效时长 = 排班工作结束时间 - 排班午休结束时间
                return attendanceDay.getRosteringWorkEndTime().getTime() - attendanceDay.getRosteringLunchEndTime().getTime();
            }
        } else if (startTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
            // 判断结束时间
            if (endTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
                // 返回有效时长 = 结束时间 - 开始时间
                return endTime.getTime() - startTime.getTime();
            } else {
                // 返回有效时长 = 排班工作结束时间 - 开始时间
                return attendanceDay.getRosteringWorkEndTime().getTime() - startTime.getTime();
            }
        } else {
            // 返回有效时长 = 0
            return 0L;
        }
    }
/*
*  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 lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.*;
import me.zhengjie.modules.attendance.service.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.*;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.impl.DingTalkServiceImpl;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.SysRostering;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.dto.SysConfigHolidayQueryCriteria;
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.stereotype.Service;
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.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author wcd
* @date 2022-12-14
**/
@Service
@RequiredArgsConstructor
public class AttendanceServiceImpl implements AttendanceService {
    private final AttendanceRepository attendanceRepository;
    private final AttendanceMapper attendanceMapper;
    private final UserRepository userRepository;
    private final DictDetailRepository dictDetailRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceLeaveRepository attendanceLeaveRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    private final DingTalkServiceImpl dingTalkService;
    @Override
    public Map<String,Object> queryAll(AttendanceQueryCriteria criteria, Pageable pageable){
        Page<Attendance> page = attendanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //将实体转换为Dto(重写)
        Function<Attendance, AttendanceDto> func = new Function<Attendance, AttendanceDto>(){
            @Override
            public AttendanceDto apply(Attendance attendance) {
                // 将实体类转换成DTO
                AttendanceDto attendanceDto = attendanceMapper.toDto(attendance);
                //查询用户信息
                User user = userRepository.findById(attendanceDto.getUserId()).orElseGet(User::new);
                attendanceDto.setUserName(user.getNickName());
                return attendanceDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<AttendanceDto> queryAll(AttendanceQueryCriteria criteria){
        return attendanceMapper.toDto(attendanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
    @Override
    @Transactional
    public AttendanceDto findById(Long id) {
        Attendance attendance = attendanceRepository.findById(id).orElseGet(Attendance::new);
        ValidationUtil.isNull(attendance.getId(),"Attendance","id",id);
        return attendanceMapper.toDto(attendance);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttendanceDto create(Attendance resources) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        // 查询用户
        User user = userRepository.findById(resources.getUserId()).orElseGet(User::new);
        resources.setRosteringLunchStartTime(Timestamp.valueOf(df.format(resources.getAttendanceDate()) + " " + dateTimeFormatter.format(user.getSysRostering().getLunchStartTime())));
        resources.setRosteringLunchEndTime(Timestamp.valueOf(df.format(resources.getAttendanceDate()) + " " + dateTimeFormatter.format(user.getSysRostering().getLunchEndTime())));
        return attendanceMapper.toDto(attendanceRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Attendance resources) {
        Attendance attendance = attendanceRepository.findById(resources.getId()).orElseGet(Attendance::new);
        ValidationUtil.isNull( attendance.getId(),"Attendance","id",resources.getId());
        attendance.copy(resources);
        //获取当前登入人信息
        User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
        }
        attendanceRepository.save(attendance);
    }
    /**
     * 计算时间(小时)
     * @param userId
     * @return
     */
    @Override
    public Integer calculateTimes(Calculate calculate, Long userId) {
        User userInfo = userRepository.getOne(userId);
        SysRostering sysRostering = userInfo.getSysRostering();
        //计算天数
        Integer count = calculateDays(calculate);
        Calculate startCalculate = new Calculate();
        startCalculate.setStart(calculate.getStart());
        startCalculate.setEnd(calculate.getStart());
        Integer startDays = calculateDays(startCalculate);
        Calculate endCalculate = new Calculate();
        endCalculate.setStart(calculate.getEnd());
        endCalculate.setEnd(calculate.getEnd());
        Integer endDays = calculateDays(endCalculate);
        Integer time = 0;
        time = (count - startDays - endDays) * 8 * 3600;
        calculate.setStart(formateDateTime(calculate.getStart(), sysRostering));
        calculate.setEnd(formateDateTime(calculate.getEnd(), sysRostering));
        if (startDays > 0) {
            Duration startDuration = Duration.between(calculate.getStart(), calculate.getStart().toLocalDate().atTime(sysRostering.getWorkEndTime()));
            Long StartSeconds = startDuration.getSeconds();
            if (calculate.getStart().toLocalTime().isBefore(LocalTime.NOON)) {
                time += StartSeconds.intValue() - 3600;
            }else if(calculate.getStart().toLocalTime().compareTo(LocalTime.NOON) >= 0 && calculate.getStart().toLocalTime().compareTo(calculate.getStart().toLocalDate().atTime(sysRostering.getLunchEndTime()).toLocalTime()) < 0){
                //补充,请假开始时间大于等于中午基准休息时间小于休息结束时间
                time += StartSeconds.intValue() - 3600;
            } else {
                time += StartSeconds.intValue();
            }
        }
        if (endDays > 0) {
            Duration endDuration = Duration.between(calculate.getEnd().toLocalDate().atTime(sysRostering.getWorkStartTime()), calculate.getEnd());
            Long endSeconds = endDuration.getSeconds();
            if (calculate.getEnd().toLocalTime().isAfter(LocalTime.NOON)) {
                time += endSeconds.intValue() - 3600;
            } else {
                time += endSeconds.intValue();
            }
        }
        return time;
    }
    /**
     * 计算时间(天)
     * @param calculate
     * @return
     */
    @Override
    public Integer calculateDays(Calculate calculate) {
        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));
            }
        }
        Long chronoUnit =  ChronoUnit.DAYS.between(calculate.getStart().toLocalDate(), calculate.getEnd().toLocalDate());
        Integer count = 0;
        for (Integer i = 0; i <= chronoUnit; i++) {
            LocalDate date = calculate.getStart().toLocalDate().plusDays(i);
            Boolean isWeekend = date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY;
            if ((!isWeekend && !holiday.contains(date.toString())) || (isWeekend && isWork.contains(date.toString()))) {
                count++;
            }
        }
        return count;
    }
    public LocalDateTime formateDateTime(LocalDateTime localDateTime, SysRostering sysRostering) {
        if (localDateTime.toLocalTime().isBefore(sysRostering.getWorkStartTime())) {
            return localDateTime.toLocalDate().atTime(sysRostering.getWorkStartTime());
        } else if (localDateTime.toLocalTime().isAfter(sysRostering.getLunchStartTime()) && localDateTime.toLocalTime().isBefore(sysRostering.getLunchEndTime())) {
            return localDateTime.toLocalDate().atTime(sysRostering.getLunchEndTime());
        } else if (localDateTime.toLocalTime().isAfter(sysRostering.getWorkEndTime())) {
            return localDateTime.toLocalDate().atTime(sysRostering.getWorkEndTime());
        }
        return localDateTime;
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //获取当前登入人信息
            User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
            Role role = user.getRoles().iterator().next();
            //根据id查询记录
            Optional<Attendance> attendance = attendanceRepository.findById(id);
            //除超管、总经理只能删除自己信息
            if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
                if (!Long.valueOf(attendance.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
            }
            attendanceRepository.deleteById(id);
        }
    }
    /**
     * 补卡判断登录人
     */
    @Override
    public void getUserMakeUpCard(String userId) {
        //获取当前登入人信息
        User user = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user.getRoles().iterator().next();
        //除超管、总经理只能补自己的卡
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            if (!Long.valueOf(userId).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能补自己的卡");
            }
        }
    }
    /**
     * 补充考勤信息
     * @param attendance
     */
    @Override
    public void addAttendanceInfo(Attendance attendance) throws Exception {
        // 获取今天日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String todayDate = sdf.format(new Date());
        if(attendance.getAttendanceDate().compareTo(Timestamp.valueOf(todayDate)) >= 0){
            throw new BadRequestException("只能更新小于等于今天的考勤信息");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String attendanceDate = df.format(attendance.getAttendanceDate());
        List<User> userList = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(attendance.getUserId())){
            User user = userRepository.findById(attendance.getUserId()).orElseGet(User::new);
            userList.add(user);
        }
        // 调用0时定时任务
        dingTalkService.getDingTalkAttendanceList(attendance.getAttendanceDate(), userList);
        // 选择日期和员工更新员工的考勤信息,未选择员工则更新所有人
        dingTalkService.getDingTalkAttendanceListOfNoonOrNight(attendanceDate ,userList);
    }
    @Override
    public void download(List<AttendanceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AttendanceDto attendance : all) {
            String startLocationResults = attendance.getStartLocationResults() != null ? dictDetailRepository.findByDictNameAndValue("location_results", attendance.getStartLocationResults()).getLabel() : "";
            String startClockResults = attendance.getStartClockResults() != null ? dictDetailRepository.findByDictNameAndValue("attendance_state", attendance.getStartClockResults()).getLabel() : "";
            String endLocationResults = attendance.getEndLocationResults() != null ? dictDetailRepository.findByDictNameAndValue("location_results", attendance.getEndLocationResults()).getLabel() : "";
            String endClockResults = attendance.getEndClockResults() != null ? dictDetailRepository.findByDictNameAndValue("attendance_state", attendance.getEndClockResults()).getLabel() : "";
            String dateType = attendance.getDateType() != null ? dictDetailRepository.findByDictNameAndValue("date_type", attendance.getDateType()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("员工", attendance.getUserName());
            map.put("考勤日期", attendance.getAttendanceDate());
            map.put("排班工作开始时间", attendance.getRosteringWorkStartTime());
            map.put("实际工作开始时间", attendance.getActualWorkStartTime());
            map.put("开始位置结果",startLocationResults);
            map.put("开始打卡结果",startClockResults);
            map.put("排班工作结束时间", attendance.getRosteringWorkEndTime());
            map.put("实际工作结束时间", attendance.getActualWorkEndTime());
            map.put("结束位置结果",endLocationResults);
            map.put("结束打卡结果",endClockResults);
            map.put("日期类型",dateType);
            map.put("备注", attendance.getRemarks());
            map.put("创建者", attendance.getCreateBy());
            map.put("创建时间", attendance.getCreateTime());
            map.put("更新者", attendance.getUpdateBy());
            map.put("更新时间", attendance.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public Double queryAttendanceHours(Long userId, String date) {
        Attendance attendanceDate = attendanceRepository.findAllByUserIdAndAttendanceDate(userId, date);
        List<Calculate> resultParts = new ArrayList<>();
        LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDateTime startOfDate = localDate.atTime(0, 0, 0);
        LocalDateTime endOfDate = localDate.atTime(23, 59, 59);
        LocalDateTime actualWorkStartTime = attendanceDate.getActualWorkStartTime() == null ? null : attendanceDate.getActualWorkStartTime().toLocalDateTime();
        LocalDateTime actualWorkEndTime = attendanceDate.getActualWorkEndTime() == null ? null : attendanceDate.getActualWorkEndTime().toLocalDateTime();
        LocalDateTime rosteringWorkStartTime = attendanceDate.getRosteringWorkStartTime() == null ? null : attendanceDate.getRosteringWorkStartTime().toLocalDateTime();
        LocalDateTime rosteringLunchStartTime = attendanceDate.getRosteringLunchStartTime() == null ? null : attendanceDate.getRosteringLunchStartTime().toLocalDateTime();
        LocalDateTime rosteringLunchEndTime = attendanceDate.getRosteringLunchEndTime() == null ? null : attendanceDate.getRosteringLunchEndTime().toLocalDateTime();
        LocalDateTime rosteringWorkEndTime = attendanceDate.getRosteringWorkEndTime() == null ? null : attendanceDate.getRosteringWorkEndTime().toLocalDateTime();
        // 出差信息(出差时无打卡信息,用出差信息补充)
        AttendanceBusinessTravel attendanceBusinessTravel = attendanceBusinessTravelRepository.findByUserAndDate(userId, startOfDate, endOfDate);
        if (attendanceBusinessTravel != null) {
            actualWorkStartTime = rosteringWorkStartTime;
            actualWorkEndTime = rosteringWorkEndTime;
        }
        if (actualWorkStartTime != null && actualWorkStartTime.isBefore(rosteringWorkStartTime)) {
            actualWorkStartTime = rosteringWorkStartTime;
        }
//        if (actualWorkEndTime != null && actualWorkEndTime.isAfter(rosteringWorkEndTime)) {
//            actualWorkEndTime = rosteringWorkEndTime;
//        }
        List<Calculate> attendanceParts = new ArrayList<>();
        // 当日打卡信息不全不算
        if (actualWorkStartTime != null && actualWorkEndTime != null) {
            attendanceParts.add(new Calculate(actualWorkStartTime, actualWorkEndTime));
        }
        // 休息时间管理
        List<Calculate> breakParts = new ArrayList<>();
        breakParts.add(new Calculate(rosteringLunchStartTime, rosteringLunchEndTime));
        // 外出信息
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(userId, startOfDate, endOfDate);
        attendanceParts.addAll(
                attendanceGoOutList.stream().map(attendanceGoOut ->
                        new Calculate(attendanceGoOut.getOutStartTime().toLocalDateTime(), attendanceGoOut.getOutEndTime().toLocalDateTime())
                ).collect(Collectors.toList())
        );
        // 周末加班
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findByUserIdAndDate(userId, startOfDate, endOfDate);
        attendanceParts.addAll(
                attendanceOvertimeList.stream().map(attendanceOvertime ->
                        new Calculate(attendanceOvertime.getOvertimeStartTime().toLocalDateTime(), attendanceOvertime.getOvertimeEndTime().toLocalDateTime())
                ).collect(Collectors.toList())
        );
        attendanceParts.stream().sorted().reduce(new Stack<Calculate>(), (result, current) -> {
            // 删除重复时间,合并相连的时间段
            if (result.empty()) {
                result.push(current);
                return result;
            }
            Calculate last = result.peek();
            if (last.getEnd().isBefore(current.getStart())) {
                result.push(current);
            } else if (last.getEnd().isBefore(current.getEnd())) {
                last.setEnd(current.getEnd());
            }
            return result;
        }, (o1, o2) -> null).forEach(calculate -> {
            // 去除休息时间:午休等
            for (Calculate breakPart : breakParts) {
                if ((calculate.getStart().isBefore(breakPart.getStart()) && calculate.getEnd().isAfter(breakPart.getStart()))
                        || (calculate.getStart().isBefore(breakPart.getEnd()) && calculate.getEnd().isAfter(breakPart.getEnd()))) {
                    Calculate calculate1 = new Calculate(calculate.getStart(), breakPart.getStart());
                    Calculate calculate2 = new Calculate(breakPart.getEnd(), calculate.getEnd());
                    if (calculate1.getStart().isBefore(calculate1.getEnd())) {
                        resultParts.add(calculate1);
                    }
                    if (calculate2.getStart().isBefore(calculate2.getEnd())) {
                        resultParts.add(calculate2);
                    }
                } else {
                    resultParts.add(calculate);
                }
            }
        });
        // 请假信息
        List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.findByUserIdAndDate(userId, startOfDate, endOfDate);
//        // 加班信息
//        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findByUserIdAndDate(userId, startOfDate, endOfDate);
        // 出勤时间累计
        BigDecimal result = resultParts.stream()
                .map(calculate -> ChronoUnit.SECONDS.between(calculate.getStart(), calculate.getEnd()))
                .reduce(new BigDecimal(0),
                        (total, current) -> total.add(BigDecimal.valueOf(current)),
                        (o1, o2) -> null).divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP
                );
        BigDecimal annualLeaveHours = attendanceLeaveList.stream()
                .filter(attendanceLeave -> Constant.LEAVE_TYPE_ANNUAL_LEAVE.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_MARRIAGE_HOLIDAY.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_BEREAVEMENT_LEAVE.equals(attendanceLeave.getLeaveType())
//                    || Constant.LEAVE_TYPE_REPLACE.equals(attendanceLeave.getLeaveType())
                ).map(attendanceLeave -> BigDecimal.valueOf(attendanceLeave.getLeaveDuration())).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        return result.add(annualLeaveHours).doubleValue();
    }
    @Override
    public Double queryAttendanceHolidaysOverTimeHours(AttendanceQueryCriteria criteria) {
        LocalDate startDate = LocalDate.parse(criteria.getTargetYearMonth(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate = startDate.plusMonths(1).minusDays(1);
        // 节日检索类
        SysConfigHolidayQueryCriteria sysConfigHolidayQueryCriteria = new SysConfigHolidayQueryCriteria();
        sysConfigHolidayQueryCriteria.setHolidayDateLike(criteria.getTargetYearMonth().substring(0,7));
        // 获取本月节日列表
        List<SysConfigHoliday> sysConfigHolidayMonthList = sysConfigHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,sysConfigHolidayQueryCriteria,criteriaBuilder));
        if (sysConfigHolidayMonthList.isEmpty()) {
            return 0.0D;
        }
        // 加班信息
        List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeRepository.findByUserIdAndDate(criteria.getUserId(), startDate.atStartOfDay(), endDate.atStartOfDay());
        return sysConfigHolidayMonthList.stream()
                .filter(sysConfigHoliday -> Constant.DATE_TYPE_LEGAL_HOLIDAYS.equals(sysConfigHoliday.getDateType()))
                .mapToDouble(sysConfigHoliday -> {
                    for (AttendanceOvertime attendanceOvertime : attendanceOvertimeList) {
                        if (sysConfigHoliday.getHolidayDate().toLocalDateTime().isEqual(attendanceOvertime.getOvertimeStartTime().toLocalDateTime().truncatedTo(ChronoUnit.DAYS))) {
                            return attendanceOvertime.getOvertimeDuration();
                        }
                    }
                    return 0.0D;
                }).sum();
    }
    @Override
    public Double queryAttendanceOverTimeHours(AttendanceQueryCriteria criteria) {
        // 节日检索类
        SysConfigHolidayQueryCriteria sysConfigHolidayQueryCriteria = new SysConfigHolidayQueryCriteria();
        sysConfigHolidayQueryCriteria.setHolidayDateLike(criteria.getTargetYearMonth().substring(0,7));
        // 获取本月节日列表
        List<SysConfigHoliday> sysConfigHolidayMonthList = sysConfigHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,sysConfigHolidayQueryCriteria,criteriaBuilder));
        LocalDate startDate = LocalDate.parse(criteria.getTargetYearMonth(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate = startDate.plusMonths(1).minusDays(1);
        Long distance = ChronoUnit.DAYS.between(startDate, endDate);
        return Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).filter(localDate -> {
            for (SysConfigHoliday sysConfigHoliday : sysConfigHolidayMonthList) {
                if (sysConfigHoliday.getHolidayDate().toLocalDateTime().isEqual(localDate.atStartOfDay())) {
                    return Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHoliday.getDateType());
                }
            }
            return localDate.getDayOfWeek() != DayOfWeek.SATURDAY && localDate.getDayOfWeek() != DayOfWeek.SUNDAY;
        }).map(localDate -> {
            LocalDateTime startOfDate = localDate.atTime(0, 0, 0);
            LocalDateTime endOfDate = localDate.atTime(23, 59, 59);
            Attendance attendanceDate = attendanceRepository.findAllByUserIdAndAttendanceDate(criteria.getUserId(), localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            if (attendanceDate == null) {
                return BigDecimal.valueOf(0.0);
            }
           LocalDateTime actualWorkStartTime = attendanceDate.getActualWorkStartTime() == null ? null : attendanceDate.getActualWorkStartTime().toLocalDateTime();
            LocalDateTime actualWorkEndTime = attendanceDate.getActualWorkEndTime() == null ? null : attendanceDate.getActualWorkEndTime().toLocalDateTime();
            LocalDateTime rosteringWorkStartTime = attendanceDate.getRosteringWorkStartTime() == null ? null : attendanceDate.getRosteringWorkStartTime().toLocalDateTime();
            LocalDateTime rosteringWorkEndTime = attendanceDate.getRosteringWorkEndTime() == null ? null : attendanceDate.getRosteringWorkEndTime().toLocalDateTime();
            if (actualWorkStartTime != null && actualWorkStartTime.isBefore(rosteringWorkStartTime)) {
                actualWorkStartTime = rosteringWorkStartTime;
            }
            List<Calculate> attendanceParts = new ArrayList<>();
            // 当日打卡信息不全不算
            if (actualWorkStartTime != null && actualWorkEndTime != null) {
                attendanceParts.add(new Calculate(actualWorkStartTime, actualWorkEndTime));
            }
            // 正常时间管理
            List<Calculate> breakParts = new ArrayList<>();
            breakParts.add(new Calculate(rosteringWorkStartTime, rosteringWorkEndTime.plusMinutes(30)));
            // 外出信息
            List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(criteria.getUserId(), startOfDate, endOfDate);
            attendanceParts.addAll(
                    attendanceGoOutList.stream().map(attendanceGoOut -> {
                        LocalDateTime attendanceGoOutStart = attendanceGoOut.getOutStartTime().toLocalDateTime();
                        LocalDateTime attendanceGoOutEnd = attendanceGoOut.getOutEndTime().toLocalDateTime();
                        if (attendanceGoOutStart.isBefore(rosteringWorkStartTime)) {
                            attendanceGoOutStart = rosteringWorkStartTime;
                        }
                        return new Calculate(attendanceGoOutStart, attendanceGoOutEnd);
                    }).filter(calculate -> calculate.getStart().isBefore(calculate.getEnd())).collect(Collectors.toList())
            );
            List<Calculate> resultParts = new ArrayList<>();
            attendanceParts.stream().sorted().reduce(new Stack<Calculate>(), (result, current) -> {
                // 删除重复时间,合并相连的时间段
                if (result.empty()) {
                    result.push(current);
                    return result;
                }
                Calculate last = result.peek();
                if (last.getEnd().isBefore(current.getStart())) {
                    result.push(current);
                } else if (last.getEnd().isBefore(current.getEnd())) {
                    last.setEnd(current.getEnd());
                }
                return result;
            }, (o1, o2) -> null).forEach(calculate -> {
                // 去除休息时间:午休等
                for (Calculate breakPart : breakParts) {
                    if ((!calculate.getStart().isAfter(breakPart.getStart()) && !calculate.getEnd().isBefore(breakPart.getStart()))
                            || (!calculate.getStart().isAfter(breakPart.getEnd()) && !calculate.getEnd().isBefore(breakPart.getEnd()))) {
                        Calculate calculate1 = new Calculate(calculate.getStart(), breakPart.getStart());
                        Calculate calculate2 = new Calculate(breakPart.getEnd(), calculate.getEnd());
                        if (calculate1.getStart().isBefore(calculate1.getEnd())) {
                            resultParts.add(calculate1);
                        }
                        if (calculate2.getStart().isBefore(calculate2.getEnd())) {
                            resultParts.add(calculate2);
                        }
                    } else if (calculate.getEnd().isBefore(breakPart.getStart()) || calculate.getStart().isAfter(breakPart.getEnd())) {
                        resultParts.add(calculate);
                    }
                }
            });
            // 出勤时间累计
            Long result = resultParts.stream()
                    .mapToLong(calculate -> ChronoUnit.MINUTES.between(calculate.getStart(), calculate.getEnd()))
                    .sum();
//            .reduce(new BigDecimal(0),
//                    (total, current) -> total.add(BigDecimal.valueOf(current)),
//                    (o1, o2) -> null).divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP
//            )
//            result = result.setScale(1, RoundingMode.FLOOR);
//            if (result < 30) {
//                System.out.println("localDate : " + localDate + " hours : " + 0);
//                return BigDecimal.valueOf(0.0);
//            } else {
//                result = result - 30;
//            }
            System.out.println("localDate : " + localDate + " hours : " + result);
            return BigDecimal.valueOf(result).divide(BigDecimal.valueOf(60), 1, RoundingMode.HALF_DOWN);
        }).reduce(BigDecimal::add).get().doubleValue();
    }
    @Override
    public Double queryAttendanceHours(AttendanceQueryCriteria criteria) {
        // 节日检索类
        SysConfigHolidayQueryCriteria sysConfigHolidayQueryCriteria = new SysConfigHolidayQueryCriteria();
        sysConfigHolidayQueryCriteria.setHolidayDateLike(criteria.getTargetYearMonth().substring(0,7));
        // 获取本月节日列表
        List<SysConfigHoliday> sysConfigHolidayMonthList = sysConfigHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,sysConfigHolidayQueryCriteria,criteriaBuilder));
        LocalDate startDate = LocalDate.parse(criteria.getTargetYearMonth(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate = startDate.plusMonths(1).minusDays(1);
        Long distance = ChronoUnit.DAYS.between(startDate, endDate);
        return Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).filter(localDate -> {
            for (SysConfigHoliday sysConfigHoliday : sysConfigHolidayMonthList) {
                if (sysConfigHoliday.getHolidayDate().toLocalDateTime().isEqual(localDate.atStartOfDay())) {
                    return Constant.DATE_TYPE_WEEKDAY.equals(sysConfigHoliday.getDateType());
                }
            }
            return localDate.getDayOfWeek() != DayOfWeek.SATURDAY && localDate.getDayOfWeek() != DayOfWeek.SUNDAY;
        }).map(localDate -> {
            System.out.print("localDate : " + localDate);
            LocalDateTime startOfDate = localDate.atTime(0, 0, 0);
            LocalDateTime endOfDate = localDate.atTime(23, 59, 59);
            AttendanceBusinessTravel attendanceBusinessTravel = attendanceBusinessTravelRepository.findByUserAndDate(criteria.getUserId(), startOfDate, endOfDate);
            if (attendanceBusinessTravel != null) {
                System.out.println("\t hours1 : " + 8);
                return BigDecimal.valueOf(8.0);
            }
            Attendance attendanceDate = attendanceRepository.findAllByUserIdAndAttendanceDate(criteria.getUserId(), localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            if (attendanceDate == null) {
                System.out.println("\t hours2 : " + 0);
                return BigDecimal.valueOf(0.0);
            }
            LocalDateTime actualWorkStartTime = attendanceDate.getActualWorkStartTime() == null ? null : attendanceDate.getActualWorkStartTime().toLocalDateTime();
            LocalDateTime actualWorkEndTime = attendanceDate.getActualWorkEndTime() == null ? null : attendanceDate.getActualWorkEndTime().toLocalDateTime();
            LocalDateTime rosteringWorkStartTime = attendanceDate.getRosteringWorkStartTime() == null ? null : attendanceDate.getRosteringWorkStartTime().toLocalDateTime();
            LocalDateTime rosteringLunchStartTime = attendanceDate.getRosteringLunchStartTime() == null ? null : attendanceDate.getRosteringLunchStartTime().toLocalDateTime();
            LocalDateTime rosteringLunchEndTime = attendanceDate.getRosteringLunchEndTime() == null ? null : attendanceDate.getRosteringLunchEndTime().toLocalDateTime();
            LocalDateTime rosteringWorkEndTime = attendanceDate.getRosteringWorkEndTime() == null ? null : attendanceDate.getRosteringWorkEndTime().toLocalDateTime();
            if (actualWorkStartTime != null && actualWorkStartTime.isBefore(rosteringWorkStartTime)) {
                actualWorkStartTime = rosteringWorkStartTime;
            }
            if (actualWorkEndTime != null && actualWorkEndTime.isAfter(rosteringWorkEndTime)) {
                actualWorkEndTime = rosteringWorkEndTime;
            }
            List<Calculate> attendanceParts = new ArrayList<>();
            // 当日打卡信息不全不算
            if (actualWorkStartTime != null && actualWorkEndTime != null) {
                attendanceParts.add(new Calculate(actualWorkStartTime, actualWorkEndTime));
            }
            // 休息时间管理
            List<Calculate> breakParts = new ArrayList<>();
            breakParts.add(new Calculate(rosteringLunchStartTime, rosteringLunchEndTime));
            // 外出信息
            List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(criteria.getUserId(), startOfDate, endOfDate);
            attendanceParts.addAll(
                    attendanceGoOutList.stream().map(attendanceGoOut -> {
                        LocalDateTime attendanceGoOutStart = attendanceGoOut.getOutStartTime().toLocalDateTime();
                        LocalDateTime attendanceGoOutEnd = attendanceGoOut.getOutEndTime().toLocalDateTime();
                        if (attendanceGoOutStart.isBefore(rosteringWorkStartTime)) {
                            attendanceGoOutStart = rosteringWorkStartTime;
                        }
                        if (attendanceGoOutEnd.isAfter(rosteringWorkEndTime)) {
                            attendanceGoOutEnd = rosteringWorkEndTime;
                        }
                        return new Calculate(attendanceGoOutStart, attendanceGoOutEnd);
                    }).filter(calculate -> calculate.getStart().isBefore(calculate.getEnd())).collect(Collectors.toList())
            );
            List<Calculate> resultParts = new ArrayList<>();
            attendanceParts.stream().sorted().reduce(new Stack<Calculate>(), (result, current) -> {
                // 删除重复时间,合并相连的时间段
                if (result.empty()) {
                    result.push(current);
                    return result;
                }
                Calculate last = result.peek();
                if (last.getEnd().isBefore(current.getStart())) {
                    result.push(current);
                } else if (last.getEnd().isBefore(current.getEnd())) {
                    last.setEnd(current.getEnd());
                }
                return result;
            }, (o1, o2) -> null).forEach(calculate -> {
                // 去除休息时间:午休等
                for (Calculate breakPart : breakParts) {
                    if ((calculate.getStart().isBefore(breakPart.getStart()) && calculate.getEnd().isAfter(breakPart.getStart()))
                            || (calculate.getStart().isBefore(breakPart.getEnd()) && calculate.getEnd().isAfter(breakPart.getEnd()))) {
                        Calculate calculate1 = new Calculate(calculate.getStart(), breakPart.getStart());
                        Calculate calculate2 = new Calculate(breakPart.getEnd(), calculate.getEnd());
                        if (calculate1.getStart().isBefore(calculate1.getEnd())) {
                            resultParts.add(calculate1);
                        }
                        if (calculate2.getStart().isBefore(calculate2.getEnd())) {
                            resultParts.add(calculate2);
                        }
                    } else {
                        resultParts.add(calculate);
                    }
                }
            });
            // 出勤时间累计
            BigDecimal result = resultParts.stream()
                    .map(calculate -> ChronoUnit.SECONDS.between(calculate.getStart(), calculate.getEnd()))
                    .reduce(new BigDecimal(0),
                            (total, current) -> total.add(BigDecimal.valueOf(current)),
                            (o1, o2) -> null).divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP
                    );
            // 请假信息
            List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.findByUserIdAndDate(criteria.getUserId(), startOfDate, endOfDate);
            // 年假不扣工时
            BigDecimal annualLeaveHours = attendanceLeaveList.stream()
                    .filter(attendanceLeave -> Constant.LEAVE_TYPE_ANNUAL_LEAVE.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_MARRIAGE_HOLIDAY.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_BEREAVEMENT_LEAVE.equals(attendanceLeave.getLeaveType())
                    || Constant.LEAVE_TYPE_REPLACE.equals(attendanceLeave.getLeaveType()))
                    .map(attendanceLeave -> {
                        if (Constant.LEAVE_TIME_TYPE_HOUR.equals(attendanceLeave.getLeaveDurationUnit())) {
                            return BigDecimal.valueOf(attendanceLeave.getLeaveDuration());
                        } else {
                            return BigDecimal.valueOf(attendanceLeave.getLeaveDuration()).multiply(BigDecimal.valueOf(8));
                        }
                    }).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            if (result.add(annualLeaveHours).compareTo(BigDecimal.valueOf(8.0)) > 0) {
                System.out.println("\t hours3 : " + 8);
                return BigDecimal.valueOf(8.0);
            }
            System.out.println("\t hours4 : " + result.add(annualLeaveHours));
            return result.add(annualLeaveHours);
        }).reduce(BigDecimal::add).get().doubleValue();
    }
    /**
     * 设置日历类
     * @return
     */
    private Calendar setUpCalendar(String targetYearMonth) {
        // 日历类
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, Integer.valueOf(targetYearMonth.substring(0,4)));
        // 设置月份
        cal.set(Calendar.MONTH, Integer.valueOf(targetYearMonth.substring(5,7)) - 1);
        // 日历类
        return cal;
    }
    /**
     * 获取有效时长
     * @param attendanceDay
     * @param startTime
     * @param endTime
     * @return
     */
    private Long getValidDuration(Attendance attendanceDay, Timestamp startTime, Timestamp endTime) {
        // 判断开始时间与结束时间
        if (endTime.getTime() < startTime.getTime()) {
            throw new BadRequestException("结束时间应大于开始时间!");
        }
        // 判断开始时间
        if (startTime.getTime() < attendanceDay.getRosteringWorkStartTime().getTime()) {
            // 判断结束时间
            if (endTime.getTime() < attendanceDay.getRosteringWorkStartTime().getTime()) {
                // 返回有效时长 = 0
                return 0L;
            } else if (endTime.getTime() < attendanceDay.getRosteringLunchStartTime().getTime()) {
                // 返回有效时长 = 结束时间 - 排班工作开始时间
                return endTime.getTime() - attendanceDay.getRosteringWorkStartTime().getTime();
            } else if (endTime.getTime() < attendanceDay.getRosteringLunchEndTime().getTime()) {
                // 返回有效时长 = 排班午休开始时间 - 排班工作开始时间
                return attendanceDay.getRosteringLunchStartTime().getTime() - attendanceDay.getRosteringWorkStartTime().getTime();
            } else if (endTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
                // 返回有效时长 = (排班午休开始时间 - 排班工作开始时间) + (结束时间 - 排班午休结束时间)
                return (attendanceDay.getRosteringLunchStartTime().getTime() - attendanceDay.getRosteringWorkStartTime().getTime()) + (endTime.getTime() - attendanceDay.getRosteringLunchEndTime().getTime());
            } else {
                // 返回有效时长 = (排班午休开始时间 - 排班工作开始时间) + (排班工作结束时间 - 排班午休结束时间)
                return (attendanceDay.getRosteringLunchStartTime().getTime() - attendanceDay.getRosteringWorkStartTime().getTime()) + (attendanceDay.getRosteringWorkEndTime().getTime() - attendanceDay.getRosteringLunchEndTime().getTime());
            }
        } else if (startTime.getTime() < attendanceDay.getRosteringLunchStartTime().getTime()) {
            // 判断结束时间
            if (endTime.getTime() < attendanceDay.getRosteringLunchStartTime().getTime()) {
                // 返回有效时长 = 结束时间 - 开始时间
                return endTime.getTime() - startTime.getTime();
            } else if (endTime.getTime() < attendanceDay.getRosteringLunchEndTime().getTime()) {
                // 返回有效时长 = 排班午休开始时间 - 开始时间
                return attendanceDay.getRosteringLunchStartTime().getTime() - startTime.getTime();
            } else if (endTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
                // 返回有效时长 = (排班午休开始时间 - 开始时间) + (结束时间 - 排班午休结束时间)
                return (attendanceDay.getRosteringLunchStartTime().getTime() - startTime.getTime()) + (endTime.getTime() - attendanceDay.getRosteringLunchEndTime().getTime());
            } else {
                // 返回有效时长 = (排班午休开始时间 - 开始时间) + (排班工作结束时间 - 排班午休结束时间)
                return (attendanceDay.getRosteringLunchStartTime().getTime() - startTime.getTime()) + (attendanceDay.getRosteringWorkEndTime().getTime() - attendanceDay.getRosteringLunchEndTime().getTime());
            }
        } else if (startTime.getTime() < attendanceDay.getRosteringLunchEndTime().getTime()) {
            // 判断结束时间
            if (endTime.getTime() < attendanceDay.getRosteringLunchEndTime().getTime()) {
                // 返回有效时长 = 0
                return 0L;
            } else if (endTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
                // 返回有效时长 = 结束时间 - 排班午休结束时间
                return endTime.getTime() - attendanceDay.getRosteringLunchEndTime().getTime();
            } else {
                // 返回有效时长 = 排班工作结束时间 - 排班午休结束时间
                return attendanceDay.getRosteringWorkEndTime().getTime() - attendanceDay.getRosteringLunchEndTime().getTime();
            }
        } else if (startTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
            // 判断结束时间
            if (endTime.getTime() < attendanceDay.getRosteringWorkEndTime().getTime()) {
                // 返回有效时长 = 结束时间 - 开始时间
                return endTime.getTime() - startTime.getTime();
            } else {
                // 返回有效时长 = 排班工作结束时间 - 开始时间
                return attendanceDay.getRosteringWorkEndTime().getTime() - startTime.getTime();
            }
        } else {
            // 返回有效时长 = 0
            return 0L;
        }
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/domain/ProjectProgress.java
@@ -1,126 +1,130 @@
/*
*  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.project.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import me.zhengjie.base.BaseEntity;
/**
* @website https://eladmin.vip
* @description /
* @author HuaZhe
* @date 2022-12-23
**/
@Entity
@Data
@Table(name="project_progress")
public class ProjectProgress extends BaseEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "`id`")
    @ApiModelProperty(value = "ID")
    private Long id;
    @Column(name = "`belong_year`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "年度")
    private Integer belongYear;
    @Column(name = "`belong_week`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "周度")
    private Integer belongWeek;
    @Column(name = "`belong_date`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "生成日")
    private Timestamp belongDate;
    @ManyToOne
    @JoinColumn(name = "`project_id`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "项目ID")
    private Project project;
    @Column(name = "`estimated_progress`")
    @ApiModelProperty(value = "预计进度")
    private Double estimatedProgress;
    @Column(name = "`project_progress`")
    @ApiModelProperty(value = "项目进度")
    private Double projectProgress;
    @Column(name = "`approve_status`",nullable = false)
    @NotBlank
    @ApiModelProperty(value = "批准状态")
    private String approveStatus;
    @Column(name = "`remarks`")
    @ApiModelProperty(value = "备注")
    private String remarks;
    @Column(name = "`time_total_init`")
    @ApiModelProperty(value = "总绩效工时")
    private Double timeTotalInit;
    @Column(name = "`time_total_cost`")
    @ApiModelProperty(value = "总消耗绩效工时")
    private Double timeTotalCost;
    @Column(name = "`real_last_cost`")
    @ApiModelProperty(value = "实际消化工时")
    private Double realLastCost;
    @Column(name = "`work_total_init`")
    @ApiModelProperty(value = "总工作量")
    private Double workTotalInit;
    @Column(name = "`work_total_cost`")
    @ApiModelProperty(value = "总消耗工作量")
    private Double workTotalCost;
    @Column(name = "`money_total_init`")
    @ApiModelProperty(value = "计划总成本")
    private BigDecimal moneyTotalInit;
    @Column(name = "`money_total_cost`")
    @ApiModelProperty(value = "总消耗成本")
    private BigDecimal moneyTotalCost;
    public void copy(ProjectProgress source) {
        BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
    }
}
/*
*  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.project.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import me.zhengjie.base.BaseEntity;
/**
* @website https://eladmin.vip
* @description /
* @author HuaZhe
* @date 2022-12-23
**/
@Entity
@Data
@Table(name="project_progress")
public class ProjectProgress extends BaseEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "`id`")
    @ApiModelProperty(value = "ID")
    private Long id;
    @Column(name = "`belong_year`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "年度")
    private Integer belongYear;
    @Column(name = "`belong_week`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "周度")
    private Integer belongWeek;
    @Column(name = "`belong_date`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "生成日")
    private Timestamp belongDate;
    @ManyToOne
    @JoinColumn(name = "`project_id`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "项目ID")
    private Project project;
    @Column(name = "`estimated_progress`")
    @ApiModelProperty(value = "预计进度")
    private Double estimatedProgress;
    @Column(name = "`project_progress`")
    @ApiModelProperty(value = "项目进度")
    private Double projectProgress;
    @Column(name = "`approve_status`",nullable = false)
    @NotBlank
    @ApiModelProperty(value = "批准状态")
    private String approveStatus;
    @Column(name = "`remarks`")
    @ApiModelProperty(value = "备注")
    private String remarks;
    @Column(name = "`time_total_init`")
    @ApiModelProperty(value = "总绩效工时")
    private Double timeTotalInit;
    @Column(name = "`time_total_cost`")
    @ApiModelProperty(value = "总消耗绩效工时")
    private Double timeTotalCost;
    @Column(name = "`real_last_cost`")
    @ApiModelProperty(value = "实际消化工时")
    private Double realLastCost;
    @Column(name = "`work_total_init`")
    @ApiModelProperty(value = "总工作量")
    private Double workTotalInit;
    @Column(name = "`work_total_cost`")
    @ApiModelProperty(value = "总消耗工作量")
    private Double workTotalCost;
    @Column(name = "`money_total_init`")
    @ApiModelProperty(value = "计划总成本")
    private BigDecimal moneyTotalInit;
    @Column(name = "`money_total_cost`")
    @ApiModelProperty(value = "总消耗成本")
    private BigDecimal moneyTotalCost;
    @Column(name = "`money_real_cost`")
    @ApiModelProperty(value = "总消耗成本")
    private BigDecimal moneyRealCost;
    public void copy(ProjectProgress source) {
        BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/domain/ProjectProgressDetail.java
New file
@@ -0,0 +1,96 @@
/*
*  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.project.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import me.zhengjie.base.BaseEntity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
/**
* @website https://eladmin.vip
* @description /
* @author HuaZhe
* @date 2022-12-23
**/
@Entity
@Data
@Table(name="project_progress_detail")
public class ProjectProgressDetail extends BaseEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "`id`")
    @ApiModelProperty(value = "ID")
    private Long id;
    @Column(name = "`belong_year`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "年度")
    private Integer belongYear;
    @Column(name = "`belong_week`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "周度")
    private Integer belongWeek;
    @Column(name = "`belong_date`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "生成日")
    private Timestamp belongDate;
    @ManyToOne
    @JoinColumn(name = "`project_id`",nullable = false)
    @NotNull
    @ApiModelProperty(value = "项目ID")
    private Project project;
    @Column(name = "`user_id`")
    @ApiModelProperty(value = "用户ID")
    private Long userId;
    @Column(name = "`time_init_cost`")
    @ApiModelProperty(value = "总分配绩效工时")
    private Double timeInitCost;
    @Column(name = "`time_total_cost`")
    @ApiModelProperty(value = "实际消化总工时")
    private Double timeTotalCost;
//    @Column(name = "`time_last_cost`")
//    @ApiModelProperty(value = "当周消化工时")
//    private Double timeLastCost;
    @Column(name = "`money_total_cost`")
    @ApiModelProperty(value = "实际消耗总成本")
    private BigDecimal moneyTotalCost;
//    @Column(name = "`money_last_cost`")
//    @ApiModelProperty(value = "当周消耗成本")
//    private Double moneyLastCost;
    public void copy(ProjectProgressDetail source) {
        BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/ProjectCostService.java
@@ -1,95 +1,97 @@
/*
*  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.project.service;
import me.zhengjie.modules.project.domain.ProjectCost;
import me.zhengjie.modules.project.service.dto.ProjectCostDto;
import me.zhengjie.modules.project.service.dto.ProjectCostQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.text.ParseException;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @description 服务接口
* @author HuaZhe
* @date 2022-12-27
**/
public interface ProjectCostService {
    /**
    * 查询数据分页
    * @param criteria 条件
    * @param pageable 分页参数
    * @return Map<String,Object>
    */
    Map<String,Object> queryAll(ProjectCostQueryCriteria criteria, Pageable pageable);
    /**
    * 查询所有数据不分页
    * @param criteria 条件参数
    * @return List<ProjectCostDto>
    */
    List<ProjectCostDto> queryAll(ProjectCostQueryCriteria criteria);
    /**
     * 根据ID查询
     * @param id ID
     * @return ProjectCostDto
     */
    ProjectCostDto findById(Long id);
    /**
    * 创建
    * @param resources /
    * @return ProjectCostDto
    */
    ProjectCostDto create(ProjectCost resources);
    /**
    * 编辑
    * @param resources /
    */
    void update(ProjectCost resources);
    /**
    * 多选删除
    * @param ids /
    */
    void deleteAll(Long[] ids);
    ProjectCost getCost(ProjectCostQueryCriteria criteria) throws ParseException;
    Double getHours(ProjectCostQueryCriteria criteria) throws ParseException;
    /**
    * 导出数据
    * @param all 待导出的数据
    * @param response /
    * @throws IOException /
    */
    void download(List<ProjectCostDto> all, HttpServletResponse response) throws IOException;
    BigDecimal calcUserCostByDate(Long userId, Timestamp enterProjectTime, Timestamp exitProjectTime, Map<String, Double> costHoursMap);
/*
*  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.project.service;
import me.zhengjie.modules.project.domain.ProjectCost;
import me.zhengjie.modules.project.service.dto.ProjectCostDto;
import me.zhengjie.modules.project.service.dto.ProjectCostQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.text.ParseException;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @description 服务接口
* @author HuaZhe
* @date 2022-12-27
**/
public interface ProjectCostService {
    /**
    * 查询数据分页
    * @param criteria 条件
    * @param pageable 分页参数
    * @return Map<String,Object>
    */
    Map<String,Object> queryAll(ProjectCostQueryCriteria criteria, Pageable pageable);
    /**
    * 查询所有数据不分页
    * @param criteria 条件参数
    * @return List<ProjectCostDto>
    */
    List<ProjectCostDto> queryAll(ProjectCostQueryCriteria criteria);
    /**
     * 根据ID查询
     * @param id ID
     * @return ProjectCostDto
     */
    ProjectCostDto findById(Long id);
    /**
    * 创建
    * @param resources /
    * @return ProjectCostDto
    */
    ProjectCostDto create(ProjectCost resources);
    /**
    * 编辑
    * @param resources /
    */
    void update(ProjectCost resources);
    /**
    * 多选删除
    * @param ids /
    */
    void deleteAll(Long[] ids);
    ProjectCost getCost(ProjectCostQueryCriteria criteria) throws ParseException;
    Double getHours(ProjectCostQueryCriteria criteria) throws ParseException;
    /**
    * 导出数据
    * @param all 待导出的数据
    * @param response /
    * @throws IOException /
    */
    void download(List<ProjectCostDto> all, HttpServletResponse response) throws IOException;
//    BigDecimal calcUserCostByDate(Long userId, Timestamp enterProjectTime, Timestamp exitProjectTime, Map<String, Double> costHoursMap);
    BigDecimal calcUserCostByHours(Long userId, Double timeTotalCost);
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/dto/ProjectProgressDetailDto.java
New file
@@ -0,0 +1,57 @@
/*
*  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.project.service.dto;
import lombok.Data;
import me.zhengjie.base.BaseDTO;
import me.zhengjie.modules.project.domain.ProjectProgress;
import java.io.Serializable;
/**
* @website https://eladmin.vip
* @description /
* @author HuaZhe
* @date 2022-12-23
**/
@Data
public class ProjectProgressDetailDto extends BaseDTO implements Serializable {
    /** ID */
    private Long id;
    /** 用户ID */
    private Long userId;
    /** 总分配绩效工时 */
    private Double timeInitCost;
    /** 实际消化总工时 */
    private Double timeTotalCost;
    /** 当周消化工时 */
    private Double timeLastCost;
    /** 实际消耗总成本 */
    private Double moneyTotalCost;
    /** 当周消耗成本 */
    private Double moneyLastCost;
    /** 上周进度 */
    private ProjectProgress lastProjectProcess;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/dto/ProjectProgressDto.java
@@ -1,82 +1,85 @@
/*
*  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.project.service.dto;
import java.io.Serializable;
import java.math.BigDecimal;
import lombok.Data;
import me.zhengjie.base.BaseDTO;
import me.zhengjie.modules.project.domain.ProjectProgress;
/**
* @website https://eladmin.vip
* @description /
* @author HuaZhe
* @date 2022-12-23
**/
@Data
public class ProjectProgressDto extends BaseDTO implements Serializable {
    /** ID */
    private Long id;
    /** 年度 */
    private Integer belongYear;
    /** 周度 */
    private Integer belongWeek;
    /** 项目 */
    private ProjectDto project;
    /** 预计进度 */
    private Double estimatedProgress;
    /** 项目进度 */
    private Double projectProgress;
    /** 批准状态 */
    private String approveStatus;
    /** 备注 */
    private String remarks;
    /** 总绩效工时 */
    private Double timeTotalInit;
    /** 总消耗绩效工时 */
    private Double timeTotalCost;
    /** 实际消化工时 */
    private Double realLastCost;
    /** 总工作量 */
    private Double workTotalInit;
    /** 总消耗工作量 */
    private Double workTotalCost;
    /** 计划总成本 */
    private BigDecimal moneyTotalInit;
    /** 总消耗成本 */
    private BigDecimal moneyTotalCost;
    /** 上周进度 */
    private ProjectProgress lastProjectProcess;
/*
*  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.project.service.dto;
import lombok.Data;
import me.zhengjie.base.BaseDTO;
import me.zhengjie.modules.project.domain.ProjectProgress;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* @website https://eladmin.vip
* @description /
* @author HuaZhe
* @date 2022-12-23
**/
@Data
public class ProjectProgressDto extends BaseDTO implements Serializable {
    /** ID */
    private Long id;
    /** 年度 */
    private Integer belongYear;
    /** 周度 */
    private Integer belongWeek;
    /** 项目 */
    private ProjectDto project;
    /** 预计进度 */
    private Double estimatedProgress;
    /** 项目进度 */
    private Double projectProgress;
    /** 批准状态 */
    private String approveStatus;
    /** 备注 */
    private String remarks;
    /** 总绩效工时 */
    private Double timeTotalInit;
    /** 总消耗绩效工时 */
    private Double timeTotalCost;
    /** 实际消化工时 */
    private Double realLastCost;
    /** 总工作量 */
    private Double workTotalInit;
    /** 总消耗工作量 */
    private Double workTotalCost;
    /** 计划总成本 */
    private BigDecimal moneyTotalInit;
    /** 总消耗成本 */
    private BigDecimal moneyTotalCost;
    /** 总消耗成本 */
    private BigDecimal moneyRealCost;
    /** 上周进度 */
    private ProjectProgress lastProjectProcess;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/impl/ProjectCostServiceImpl.java
@@ -1,470 +1,498 @@
/*
*  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.project.service.impl;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.domain.Project;
import me.zhengjie.modules.project.domain.ProjectCost;
import me.zhengjie.modules.project.repository.ProjectCostRepository;
import me.zhengjie.modules.project.repository.ProjectRepository;
import me.zhengjie.modules.project.service.ProjectCostService;
import me.zhengjie.modules.project.service.dto.ProjectCostDto;
import me.zhengjie.modules.project.service.dto.ProjectCostQueryCriteria;
import me.zhengjie.modules.project.service.mapstruct.ProjectCostMapper;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.SysLevel;
import me.zhengjie.modules.system.domain.SysUserLevelInsurance;
import me.zhengjie.modules.system.domain.SysUserLevelWage;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.SysLevelRepository;
import me.zhengjie.modules.system.repository.SysUserLevelInsuranceRepository;
import me.zhengjie.modules.system.repository.SysUserLevelWageRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.SysRosteringDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.enums.DataScopeEnum;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author HuaZhe
* @date 2022-12-27
**/
@Service
@RequiredArgsConstructor
public class ProjectCostServiceImpl implements ProjectCostService {
    private final ProjectCostRepository projectCostRepository;
    private final ProjectCostMapper projectCostMapper;
    private final ProjectRepository projectRepository;
    private final UserRepository userRepository;
    private final SysUserLevelWageRepository sysUserLevelWageRepository;
    private final SysUserLevelInsuranceRepository sysUserLevelInsuranceRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final UserService userService;
    private final RoleService roleService;
    private final SysLevelRepository sysLevelRepository;
    @Override
    public Map<String,Object> queryAll(ProjectCostQueryCriteria criteria, Pageable pageable) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUserId();
        // 查询用户角色
        List<RoleSmallDto> roleSet = roleService.findByUsersId(userId);
        if (roleSet.stream().anyMatch(role -> DataScopeEnum.find(role.getDataScope()) == DataScopeEnum.THIS_LEVEL)) {
            // 根据用户ID查询负责的项目ID
            List<Long> projectIdList = projectRepository.findIdByLiableUserId(userId);
            // 根据用户ID查询参与的项目ID
            List<Long> taskUserProjectIdList = projectCostRepository.findProjectIdByUserId(userId);
            // 检索条件
            List<Long> totalProjectIdList = Stream.of(taskUserProjectIdList, projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
            if (totalProjectIdList.size() == 0) {
                return PageUtil.toPage(Collections.emptyList(), 0);
            }
            criteria.setProjectIdList(totalProjectIdList);
        }
        Page<ProjectCost> page = projectCostRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        // 将实体类转换为DTO(重写)
        Function<ProjectCost, ProjectCostDto> func = new Function<ProjectCost, ProjectCostDto>() {
            @Override
            public ProjectCostDto apply(ProjectCost projectCost) {
                // 将实体类转换成DTO
                ProjectCostDto projectCostDto = projectCostMapper.toDto(projectCost);
                // 根据项目ID查询项目信息
                Project project = projectRepository.findById(projectCostDto.getProjectId()).orElseGet(Project::new);
                ValidationUtil.isNull(projectCostDto.getId(),"Project","id",projectCostDto.getProjectId());
                // 项目名称
                projectCostDto.setProjectName(project.getName());
                User user = userRepository.findById(projectCostDto.getUserId()).orElseGet(User::new);
                ValidationUtil.isNull(projectCostDto.getId(),"User","id",projectCostDto.getUserId());
                projectCostDto.setUserName(user.getNickName());
                return projectCostDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<ProjectCostDto> queryAll(ProjectCostQueryCriteria criteria){
        return projectCostMapper.toDto(projectCostRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
    @Override
    @Transactional
    public ProjectCostDto findById(Long id) {
        ProjectCost projectCost = projectCostRepository.findById(id).orElseGet(ProjectCost::new);
        ValidationUtil.isNull(projectCost.getId(),"ProjectCost","id",id);
        return projectCostMapper.toDto(projectCost);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectCostDto create(ProjectCost resources) {
        Project project = projectRepository.findByIdUpdate(resources.getProjectId());
        if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_ACKNOWLEDGED)){
            throw new BadRequestException("项目已承认无法新增项目成本");
        }
        return projectCostMapper.toDto(projectCostRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProjectCost resources) {
        Project project = projectRepository.findByIdUpdate(resources.getProjectId());
        if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_ACKNOWLEDGED)){
            throw new BadRequestException("项目已承认无法修改项目成本");
        }
        ProjectCost projectCost = projectCostRepository.findById(resources.getId()).orElseGet(ProjectCost::new);
        ValidationUtil.isNull( projectCost.getId(),"ProjectCost","id",resources.getId());
        projectCost.copy(resources);
        projectCostRepository.save(projectCost);
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            ProjectCost projectCost = projectCostRepository.findById(id).orElseGet(ProjectCost::new);
            Project project = projectRepository.findByIdUpdate(projectCost.getProjectId());
            if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_ACKNOWLEDGED)){
                throw new BadRequestException("项目已承认无法删除项目成本");
            }
            projectCostRepository.deleteById(id);
        }
    }
    @Override
    public BigDecimal calcUserCostByDate(Long userId, Timestamp enterProjectTime, Timestamp exitProjectTime, Map<String, Double> costHoursMap) {
        // 工资
        BigDecimal wageCost = BigDecimal.valueOf(0);
        // 工作天数
        LocalDateTime enterProject = enterProjectTime.toLocalDateTime();
        LocalDateTime exitProject = exitProjectTime.toLocalDateTime();
        // 通过id获取用户级别工资
        List<SysUserLevelWage> sysUserLevelWages = sysUserLevelWageRepository.findByUserId(userId)
                .stream().filter(sysUserLevelWage -> !((sysUserLevelWage.getEndDate() != null && sysUserLevelWage.getEndDate().before(enterProjectTime)) || sysUserLevelWage.getStartDate().after(exitProjectTime)))
                .collect(Collectors.toList());
        // 通过id获取用户级别保险
        List<SysUserLevelInsurance> sysUserLevelInsurances = sysUserLevelInsuranceRepository.findByUserId(userId)
                .stream().filter(sysUserLevelInsurance -> !((sysUserLevelInsurance.getEndDate() != null && sysUserLevelInsurance.getEndDate().before(enterProjectTime)) || sysUserLevelInsurance.getStartDate().after(exitProjectTime)))
                .collect(Collectors.toList());
//        // 判断是否有用户级别工资
//        if(sysUserLevelWages.size() <= 0){
//            throw new BadRequestException("此用户暂无级别工资");
//        }
//        // 判断是否有用户级别保险
//        if(sysUserLevelInsurances.size() <= 0){
//            throw new BadRequestException("此用户暂无级别保险");
//        }
        Map<Long, Double> sysUserLevelWageHoursMap = new HashMap<Long, Double>();
        for (SysUserLevelWage sysUserLevelWage : sysUserLevelWages) {
            sysUserLevelWageHoursMap.put(sysUserLevelWage.getId(), 0.0);
        }
        Map<Long, Double> sysUserLevelInsuranceHoursMap = new HashMap<Long, Double>();
        for (SysUserLevelInsurance sysUserLevelInsurance : sysUserLevelInsurances) {
            sysUserLevelInsuranceHoursMap.put(sysUserLevelInsurance.getId(), 0.0);
        }
        for (LocalDate currentLocalDate = enterProject.toLocalDate();
                currentLocalDate.isBefore(exitProject.toLocalDate()) || currentLocalDate.isEqual(exitProject.toLocalDate());
                currentLocalDate = currentLocalDate.plusDays(1)) {
            String dateStr = currentLocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (!costHoursMap.containsKey(dateStr)) {
                continue;
            }
            Date currentDate = Date.from(currentLocalDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
            Double costHours = costHoursMap.get(dateStr);
            for (SysUserLevelWage sysUserLevelWage : sysUserLevelWages) {
                if (sysUserLevelWage.getEndDate() == null || sysUserLevelWage.getEndDate().after(currentDate) || sysUserLevelWage.getEndDate().equals(currentDate)) {
                    sysUserLevelWageHoursMap.put(sysUserLevelWage.getId(), costHours + sysUserLevelWageHoursMap.get(sysUserLevelWage.getId()));
                    break;
                }
            }
            for (SysUserLevelInsurance sysUserLevelInsurance : sysUserLevelInsurances) {
                if (sysUserLevelInsurance.getEndDate() == null || sysUserLevelInsurance.getEndDate().after(currentDate) || sysUserLevelInsurance.getEndDate().equals(currentDate)) {
                    sysUserLevelInsuranceHoursMap.put(sysUserLevelInsurance.getId(), costHours + sysUserLevelInsuranceHoursMap.get(sysUserLevelInsurance.getId()));
                    break;
                }
            }
        }
        for (Entry<Long, Double> entry : sysUserLevelWageHoursMap.entrySet()) {
            SysUserLevelWage sysLevel = sysUserLevelWageRepository.findById(entry.getKey()).orElseGet(SysUserLevelWage::new);
            wageCost = wageCost.add(sysLevel.getLevelWage().multiply(BigDecimal.valueOf(entry.getValue())).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
        }
        for (Entry<Long, Double> entry : sysUserLevelInsuranceHoursMap.entrySet()) {
            SysUserLevelInsurance sysLevel = sysUserLevelInsuranceRepository.findById(entry.getKey()).orElseGet(SysUserLevelInsurance::new);
            BigDecimal accumulationRadix = sysLevel.getAccumulationRadix().multiply(BigDecimal.valueOf(sysLevel.getAccumulationCompanyProportion() / 100));
            BigDecimal pensionRadix = sysLevel.getPensionRadix().multiply(BigDecimal.valueOf(sysLevel.getPensionCompanyProportion() / 100));
            BigDecimal medicalRadix = sysLevel.getMedicalRadix().multiply(BigDecimal.valueOf(sysLevel.getMedicalCompanyProportion() / 100));
            BigDecimal unemploymentRadix = sysLevel.getUnemploymentRadix().multiply(BigDecimal.valueOf(sysLevel.getUnemploymentCompanyProportion() / 100));
            BigDecimal maternityRadix = sysLevel.getMaternityRadix().multiply(BigDecimal.valueOf(sysLevel.getMaternityCompanyProportion() / 100));
            BigDecimal industrialInjuryRadix = sysLevel.getIndustrialInjuryRadix().multiply(BigDecimal.valueOf(sysLevel.getIndustrialInjuryCompanyProportion() / 100));
            wageCost = wageCost.add(accumulationRadix.add(pensionRadix).add(medicalRadix).add(unemploymentRadix).add(maternityRadix).add(industrialInjuryRadix).multiply(BigDecimal.valueOf(entry.getValue())).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
        }
        return wageCost;
    }
    @Override
    public Double getHours(ProjectCostQueryCriteria criteria) throws ParseException {
        // 工时
        Double costHours = 0.0;
        // 工作天数
        LocalDateTime enterProject = criteria.getEnterProjectTime().toLocalDateTime();
        LocalDateTime exitProject = criteria.getExitProjectTime().toLocalDateTime();
        // 通过id获取用户信息
        UserDto user = userService.findById(criteria.getUserId());
        List<SysConfigHoliday> sysConfigHolidayList = sysConfigHolidayRepository.findByHolidayDateBetween(criteria.getEnterProjectTime(), criteria.getExitProjectTime());
        for (LocalDate currentLocalDate = enterProject.toLocalDate();
                currentLocalDate.isBefore(exitProject.toLocalDate()) || currentLocalDate.isEqual(exitProject.toLocalDate());
                currentLocalDate = currentLocalDate.plusDays(1)) {
            String dateType = "";
            for (SysConfigHoliday sysConfigHoliday : sysConfigHolidayList) {
                if (currentLocalDate.isEqual(sysConfigHoliday.getHolidayDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())) {
                    dateType = sysConfigHoliday.getDateType();
                    break;
                }
            }
            if ("".equals(dateType)) {
                dateType = currentLocalDate.getDayOfWeek() == DayOfWeek.SATURDAY || currentLocalDate.getDayOfWeek() == DayOfWeek.SUNDAY ? Constant.DATE_TYPE_WEEKEND : Constant.DATE_TYPE_WEEKDAY;
            }
            if (Constant.DATE_TYPE_WEEKEND.equals(dateType) || Constant.DATE_TYPE_LEGAL_HOLIDAYS.equals(dateType)) {
                continue;
            }
            SysRosteringDto sysRostering = user.getSysRostering();
            if (currentLocalDate.isEqual(exitProject.toLocalDate())) {
                if (exitProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) > 0 && exitProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) <= 0) {
                    if (exitProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) > 0) {
                        exitProject = exitProject.with(sysRostering.getLunchStartTime());
                    }
                    costHours = costHours + sysRostering.getWorkStartTime().until(exitProject.toLocalTime(), ChronoUnit.HOURS);
                } else if (exitProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) > 0 && exitProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) < 0) {
                    costHours = costHours + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS) + sysRostering.getLunchEndTime().until(exitProject.toLocalTime(), ChronoUnit.HOURS);
                } else if (exitProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) >= 0) {
                    costHours = costHours + sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS);
                }
            } else if (currentLocalDate.isEqual(enterProject.toLocalDate())) {
                if (enterProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) <= 0) {
                    costHours = costHours + sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS);
                } else if (enterProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) > 0 && enterProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) <= 0) {
                    costHours = costHours + sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS) + enterProject.toLocalTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS);
                } else if (enterProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) > 0 && enterProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) < 0) {
                    if (enterProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) < 0) {
                        enterProject = enterProject.with(sysRostering.getLunchEndTime());
                    }
                    costHours = costHours + enterProject.toLocalTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS);
                }
            } else {
                costHours = costHours + sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS);
            }
        }
        return costHours;
    }
    @Override
    public ProjectCost getCost(ProjectCostQueryCriteria criteria) throws ParseException {
        ProjectCost projectCost = new ProjectCost();
        // 工资
        BigDecimal wageCost = BigDecimal.valueOf(0);
        // 工时
        Double costHours = 0.0;
        // 工作天数
        LocalDateTime enterProject = criteria.getEnterProjectTime().toLocalDateTime();
        LocalDateTime exitProject = criteria.getExitProjectTime().toLocalDateTime();
        Date startDate = criteria.getEnterProjectTime();
        Date endDate = criteria.getExitProjectTime();
        // 通过id获取用户信息
        UserDto user = userService.findById(criteria.getUserId());
        // 通过id获取用户级别工资
        Optional<SysUserLevelWage> sysUserLevelWageOpl = sysUserLevelWageRepository.findByUserId(criteria.getUserId())
                .stream().filter(sysUserLevelWage -> !((sysUserLevelWage.getEndDate() != null && sysUserLevelWage.getEndDate().before(startDate)) || sysUserLevelWage.getStartDate().after(endDate)))
                .max((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
        // 通过id获取用户级别保险
        Optional<SysUserLevelInsurance> sysUserLevelInsuranceOpl = sysUserLevelInsuranceRepository.findByUserId(criteria.getUserId())
                .stream().filter(sysUserLevelInsurance -> !((sysUserLevelInsurance.getEndDate() != null && sysUserLevelInsurance.getEndDate().before(startDate)) || sysUserLevelInsurance.getStartDate().after(endDate)))
                .max((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
        // 判断是否有用户级别工资
        if (!sysUserLevelWageOpl.isPresent()) {
            throw new BadRequestException("此用户暂无级别工资");
        }
        // 判断是否有用户级别保险
        if (!sysUserLevelInsuranceOpl.isPresent()) {
            throw new BadRequestException("此用户暂无级别保险");
        }
        if (criteria.getInvolvementHours() == null) {
            // 获取假期数据
            List<SysConfigHoliday> sysConfigHolidayList = sysConfigHolidayRepository.findByHolidayDateBetween(criteria.getEnterProjectTime(), criteria.getExitProjectTime());
            for (LocalDate currentLocalDate = enterProject.toLocalDate();
                    currentLocalDate.isBefore(exitProject.toLocalDate()) || currentLocalDate.isEqual(exitProject.toLocalDate());
                    currentLocalDate = currentLocalDate.plusDays(1)) {
                String dateType = "";
                for (SysConfigHoliday sysConfigHoliday : sysConfigHolidayList) {
                    if (currentLocalDate.isEqual(sysConfigHoliday.getHolidayDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())) {
                        dateType = sysConfigHoliday.getDateType();
                        break;
                    }
                }
                if ("".equals(dateType)) {
                    dateType = currentLocalDate.getDayOfWeek() == DayOfWeek.SATURDAY || currentLocalDate.getDayOfWeek() == DayOfWeek.SUNDAY ? Constant.DATE_TYPE_WEEKEND : Constant.DATE_TYPE_WEEKDAY;
                }
                if (Constant.DATE_TYPE_WEEKEND.equals(dateType) || Constant.DATE_TYPE_LEGAL_HOLIDAYS.equals(dateType)) {
                    continue;
                }
                SysRosteringDto sysRostering = user.getSysRostering();
                if (currentLocalDate.isEqual(exitProject.toLocalDate())) {
                    if (exitProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) > 0 && exitProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) <= 0) {
                        if (exitProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) > 0) {
                            exitProject = exitProject.with(sysRostering.getLunchStartTime());
                        }
                        costHours = costHours + sysRostering.getWorkStartTime().until(exitProject.toLocalTime(), ChronoUnit.HOURS);
                    } else if (exitProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) > 0 && exitProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) < 0) {
                        costHours = costHours + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS) + sysRostering.getLunchEndTime().until(exitProject.toLocalTime(), ChronoUnit.HOURS);
                    } else if (exitProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) >= 0) {
                        costHours = costHours + sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS);
                    }
                } else if (currentLocalDate.isEqual(enterProject.toLocalDate())) {
                    if (enterProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) <= 0) {
                        costHours = costHours + sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS);
                    } else if (enterProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) > 0 && enterProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) <= 0) {
                        costHours = costHours + sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS) + enterProject.toLocalTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS);
                    } else if (enterProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) > 0 && enterProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) < 0) {
                        if (enterProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) < 0) {
                            enterProject = enterProject.with(sysRostering.getLunchEndTime());
                        }
                        costHours = costHours + enterProject.toLocalTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS);
                    }
                } else {
                    costHours = costHours + sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.HOURS) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.HOURS);
                }
            }
        } else {
            costHours = criteria.getInvolvementHours();
        }
        // 参与工时
        projectCost.setInvolvementHours(BigDecimal.valueOf(costHours));
        // 用户级别工资成本
        SysLevel sysLevelWage = sysLevelRepository.findById(sysUserLevelWageOpl.get().getLevelId()).orElseGet(SysLevel::new);
        wageCost = wageCost.add(sysLevelWage.getLevelWage().multiply(BigDecimal.valueOf(costHours)).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
        // 用户级别保险成本
        SysLevel sysLevelInsurance = sysLevelRepository.findById(sysUserLevelInsuranceOpl.get().getLevelId()).orElseGet(SysLevel::new);
        BigDecimal accumulationRadix = sysLevelInsurance.getAccumulationRadix().multiply(BigDecimal.valueOf(sysLevelInsurance.getAccumulationCompanyProportion() / 100));
        BigDecimal pensionRadix = sysLevelInsurance.getPensionRadix().multiply(BigDecimal.valueOf(sysLevelInsurance.getPensionCompanyProportion() / 100));
        BigDecimal medicalRadix = sysLevelInsurance.getMedicalRadix().multiply(BigDecimal.valueOf(sysLevelInsurance.getMedicalCompanyProportion() / 100));
        BigDecimal unemploymentRadix = sysLevelInsurance.getUnemploymentRadix().multiply(BigDecimal.valueOf(sysLevelInsurance.getUnemploymentCompanyProportion() / 100));
        BigDecimal maternityRadix = sysLevelInsurance.getMaternityRadix().multiply(BigDecimal.valueOf(sysLevelInsurance.getMaternityCompanyProportion() / 100));
        BigDecimal industrialInjuryRadix = sysLevelInsurance.getIndustrialInjuryRadix().multiply(BigDecimal.valueOf(sysLevelInsurance.getIndustrialInjuryCompanyProportion() / 100));
        wageCost = wageCost.add(accumulationRadix.add(pensionRadix).add(medicalRadix).add(unemploymentRadix).add(maternityRadix).add(industrialInjuryRadix).multiply(BigDecimal.valueOf(costHours)).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
        projectCost.setProjectCost(wageCost);
        return projectCost;
    }
    @Override
    public void download(List<ProjectCostDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectCostDto projectCost : all) {
            String projectName = projectCost.getProjectId() != null ? projectRepository.findById(projectCost.getProjectId()).orElseGet(Project::new).getName() : "";
            String user = projectCost.getUserId() != null ? userRepository.findById(projectCost.getUserId()).orElseGet(User::new).getNickName() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("项目", projectName);
            map.put("用户", user);
            map.put("进入项目时间", projectCost.getEnterProjectTime());
            map.put("退出项目时间", projectCost.getExitProjectTime());
            map.put("参与时间", projectCost.getInvolvementHours());
            map.put("项目成本", projectCost.getProjectCost());
            map.put("备注", projectCost.getRemarks());
            map.put("创建者", projectCost.getCreateBy());
            map.put("创建时间", projectCost.getCreateTime());
            map.put("更新者", projectCost.getUpdateBy());
            map.put("更新时间", projectCost.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
/*
*  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.project.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.domain.Project;
import me.zhengjie.modules.project.domain.ProjectCost;
import me.zhengjie.modules.project.repository.ProjectCostRepository;
import me.zhengjie.modules.project.repository.ProjectRepository;
import me.zhengjie.modules.project.service.ProjectCostService;
import me.zhengjie.modules.project.service.dto.ProjectCostDto;
import me.zhengjie.modules.project.service.dto.ProjectCostQueryCriteria;
import me.zhengjie.modules.project.service.mapstruct.ProjectCostMapper;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.SysLevelRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.SysRosteringDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.treatment.domain.UserInsurance;
import me.zhengjie.modules.treatment.domain.UserLevelWage;
import me.zhengjie.modules.treatment.repository.UserInsuranceRepository;
import me.zhengjie.modules.treatment.repository.UserLevelWageRepository;
import me.zhengjie.utils.*;
import me.zhengjie.utils.enums.DataScopeEnum;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author HuaZhe
* @date 2022-12-27
**/
@Service
@RequiredArgsConstructor
public class ProjectCostServiceImpl implements ProjectCostService {
    private final ProjectCostRepository projectCostRepository;
    private final ProjectCostMapper projectCostMapper;
    private final ProjectRepository projectRepository;
    private final UserRepository userRepository;
    private final UserLevelWageRepository sysUserLevelWageRepository;
    private final UserInsuranceRepository sysUserLevelInsuranceRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final UserService userService;
    private final RoleService roleService;
    private final SysLevelRepository sysLevelRepository;
    @Override
    public Map<String,Object> queryAll(ProjectCostQueryCriteria criteria, Pageable pageable) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUserId();
        // 查询用户角色
        List<RoleSmallDto> roleSet = roleService.findByUsersId(userId);
        if (roleSet.stream().anyMatch(role -> DataScopeEnum.find(role.getDataScope()) == DataScopeEnum.THIS_LEVEL)) {
            // 根据用户ID查询负责的项目ID
            List<Long> projectIdList = projectRepository.findIdByLiableUserId(userId);
            // 根据用户ID查询参与的项目ID
            List<Long> taskUserProjectIdList = projectCostRepository.findProjectIdByUserId(userId);
            // 检索条件
            List<Long> totalProjectIdList = Stream.of(taskUserProjectIdList, projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
            if (totalProjectIdList.size() == 0) {
                return PageUtil.toPage(Collections.emptyList(), 0);
            }
            criteria.setProjectIdList(totalProjectIdList);
        }
        Page<ProjectCost> page = projectCostRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        // 将实体类转换为DTO(重写)
        Function<ProjectCost, ProjectCostDto> func = new Function<ProjectCost, ProjectCostDto>() {
            @Override
            public ProjectCostDto apply(ProjectCost projectCost) {
                // 将实体类转换成DTO
                ProjectCostDto projectCostDto = projectCostMapper.toDto(projectCost);
                // 根据项目ID查询项目信息
                Project project = projectRepository.findById(projectCostDto.getProjectId()).orElseGet(Project::new);
                ValidationUtil.isNull(projectCostDto.getId(),"Project","id",projectCostDto.getProjectId());
                // 项目名称
                projectCostDto.setProjectName(project.getName());
                User user = userRepository.findById(projectCostDto.getUserId()).orElseGet(User::new);
                ValidationUtil.isNull(projectCostDto.getId(),"User","id",projectCostDto.getUserId());
                projectCostDto.setUserName(user.getNickName());
                return projectCostDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<ProjectCostDto> queryAll(ProjectCostQueryCriteria criteria){
        return projectCostMapper.toDto(projectCostRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
    @Override
    @Transactional
    public ProjectCostDto findById(Long id) {
        ProjectCost projectCost = projectCostRepository.findById(id).orElseGet(ProjectCost::new);
        ValidationUtil.isNull(projectCost.getId(),"ProjectCost","id",id);
        return projectCostMapper.toDto(projectCost);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectCostDto create(ProjectCost resources) {
        Project project = projectRepository.findByIdUpdate(resources.getProjectId());
        if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_ACKNOWLEDGED)){
            throw new BadRequestException("项目已承认无法新增项目成本");
        }
        return projectCostMapper.toDto(projectCostRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProjectCost resources) {
        Project project = projectRepository.findByIdUpdate(resources.getProjectId());
        if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_ACKNOWLEDGED)){
            throw new BadRequestException("项目已承认无法修改项目成本");
        }
        ProjectCost projectCost = projectCostRepository.findById(resources.getId()).orElseGet(ProjectCost::new);
        ValidationUtil.isNull( projectCost.getId(),"ProjectCost","id",resources.getId());
        projectCost.copy(resources);
        projectCostRepository.save(projectCost);
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            ProjectCost projectCost = projectCostRepository.findById(id).orElseGet(ProjectCost::new);
            Project project = projectRepository.findByIdUpdate(projectCost.getProjectId());
            if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_ACKNOWLEDGED)){
                throw new BadRequestException("项目已承认无法删除项目成本");
            }
            projectCostRepository.deleteById(id);
        }
    }
//    @Override
//    public BigDecimal calcUserCostByDate(Long userId, Timestamp enterProjectTime, Timestamp exitProjectTime, Map<String, Double> costHoursMap) {
//        // 工资
//        BigDecimal wageCost = BigDecimal.valueOf(0);
//        // 工作天数
//        LocalDateTime enterProject = enterProjectTime.toLocalDateTime();
//        LocalDateTime exitProject = exitProjectTime.toLocalDateTime();
//
////        // 通过id获取用户级别工资
////        List<UserLevelWage> sysUserLevelWages = sysUserLevelWageRepository.findUserLevelWageByUserId(userId)
////                .stream().filter(sysUserLevelWage -> !((sysUserLevelWage.getYearMonth().getEndDate() != null && sysUserLevelWage.getEndDate().before(enterProjectTime)) || sysUserLevelWage.getStartDate().after(exitProjectTime)))
////                .collect(Collectors.toList());
////        // 通过id获取用户级别保险
////        List<SysUserLevelInsurance> sysUserLevelInsurances = sysUserLevelInsuranceRepository.findByUserId(userId)
////                .stream().filter(sysUserLevelInsurance -> !((sysUserLevelInsurance.getEndDate() != null && sysUserLevelInsurance.getEndDate().before(enterProjectTime)) || sysUserLevelInsurance.getStartDate().after(exitProjectTime)))
////                .collect(Collectors.toList());
//
//        List<UserLevelWage> userLevelWages = sysUserLevelWageRepository.findUserLevelWageByUserId(userId);
//        UserInsurance userInsurance = sysUserLevelInsuranceRepository.findbyUserIdAndDate(userId, enterProject.format(DateTimeFormatter.ofPattern("yyyy-MM")));
//
//        // 判断是否有用户级别工资
//        if(userLevelWages.size() == 0){
//            throw new BadRequestException("此用户暂无级别工资");
//        }
//        UserLevelWage userLevelWage = userLevelWages.get(0);
//        // 判断是否有用户级别保险
//        if(userInsurance == null){
//            throw new BadRequestException("此用户暂无级别保险");
//        }
//
////        Map<Long, Double> sysUserLevelWageHoursMap = new HashMap<Long, Double>();
////        for (SysUserLevelWage sysUserLevelWage : sysUserLevelWages) {
////            sysUserLevelWageHoursMap.put(sysUserLevelWage.getId(), 0.0);
////        }
////
////        Map<Long, Double> sysUserLevelInsuranceHoursMap = new HashMap<Long, Double>();
////        for (SysUserLevelInsurance sysUserLevelInsurance : sysUserLevelInsurances) {
////            sysUserLevelInsuranceHoursMap.put(sysUserLevelInsurance.getId(), 0.0);
////        }
//
////        for (LocalDate currentLocalDate = enterProject.toLocalDate();
////                currentLocalDate.isBefore(exitProject.toLocalDate()) || currentLocalDate.isEqual(exitProject.toLocalDate());
////                currentLocalDate = currentLocalDate.plusDays(1)) {
////
////            String dateStr = currentLocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
////            if (!costHoursMap.containsKey(dateStr)) {
////                continue;
////            }
////
////            Date currentDate = Date.from(currentLocalDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
////
////            Double costHours = costHoursMap.get(dateStr);
////
////            for (SysUserLevelWage sysUserLevelWage : sysUserLevelWages) {
////                if (sysUserLevelWage.getEndDate() == null || sysUserLevelWage.getEndDate().after(currentDate) || sysUserLevelWage.getEndDate().equals(currentDate)) {
////                    sysUserLevelWageHoursMap.put(sysUserLevelWage.getId(), costHours + sysUserLevelWageHoursMap.get(sysUserLevelWage.getId()));
////                    break;
////                }
////            }
////
////            for (SysUserLevelInsurance sysUserLevelInsurance : sysUserLevelInsurances) {
////                if (sysUserLevelInsurance.getEndDate() == null || sysUserLevelInsurance.getEndDate().after(currentDate) || sysUserLevelInsurance.getEndDate().equals(currentDate)) {
////                    sysUserLevelInsuranceHoursMap.put(sysUserLevelInsurance.getId(), costHours + sysUserLevelInsuranceHoursMap.get(sysUserLevelInsurance.getId()));
////                    break;
////                }
////            }
////        }
//
//        for (Entry<Long, Double> entry : sysUserLevelWageHoursMap.entrySet()) {
//            SysUserLevelWage sysLevel = sysUserLevelWageRepository.findById(entry.getKey()).orElseGet(SysUserLevelWage::new);
//            wageCost = wageCost.add(sysLevel.getLevelWage().multiply(BigDecimal.valueOf(entry.getValue())).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
//        }
//
//        for (Entry<Long, Double> entry : sysUserLevelInsuranceHoursMap.entrySet()) {
//            SysUserLevelInsurance sysLevel = sysUserLevelInsuranceRepository.findById(entry.getKey()).orElseGet(SysUserLevelInsurance::new);
//
//            BigDecimal accumulationRadix = sysLevel.getAccumulationRadix().multiply(BigDecimal.valueOf(sysLevel.getAccumulationCompanyProportion() / 100));
//            BigDecimal pensionRadix = sysLevel.getPensionRadix().multiply(BigDecimal.valueOf(sysLevel.getPensionCompanyProportion() / 100));
//            BigDecimal medicalRadix = sysLevel.getMedicalRadix().multiply(BigDecimal.valueOf(sysLevel.getMedicalCompanyProportion() / 100));
//            BigDecimal unemploymentRadix = sysLevel.getUnemploymentRadix().multiply(BigDecimal.valueOf(sysLevel.getUnemploymentCompanyProportion() / 100));
//            BigDecimal maternityRadix = sysLevel.getMaternityRadix().multiply(BigDecimal.valueOf(sysLevel.getMaternityCompanyProportion() / 100));
//            BigDecimal industrialInjuryRadix = sysLevel.getIndustrialInjuryRadix().multiply(BigDecimal.valueOf(sysLevel.getIndustrialInjuryCompanyProportion() / 100));
//
//            wageCost = wageCost.add(accumulationRadix.add(pensionRadix).add(medicalRadix).add(unemploymentRadix).add(maternityRadix).add(industrialInjuryRadix).multiply(BigDecimal.valueOf(entry.getValue())).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
//        }
//
//        return wageCost;
//    }
    @Override
    public BigDecimal calcUserCostByHours(Long userId, Double timeTotalCost) {
        // 工资
        BigDecimal wageCost = BigDecimal.valueOf(0);
        // 通过id获取用户级别工资
        List<UserLevelWage> sysUserLevelWages = sysUserLevelWageRepository.findUserLevelWageByUserId(userId);
        if (sysUserLevelWages.size() == 0) {
            return BigDecimal.ZERO;
        }
        // 通过id获取用户级别保险
        List<UserInsurance> sysUserLevelInsurances = sysUserLevelInsuranceRepository.findByUserId(userId);
        if (sysUserLevelInsurances.size() == 0) {
            return BigDecimal.ZERO;
        }
        // 工资
        UserLevelWage sysUserLevelWage = sysUserLevelWages.get(sysUserLevelWages.size() - 1);
        wageCost = wageCost.add(sysUserLevelWage.getBasicWage().add(sysUserLevelWage.getRankWage()).add(sysUserLevelWage.getPerformanceWage()).multiply(BigDecimal.valueOf(timeTotalCost)).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
        // 五险一金
        UserInsurance sysUserLevelInsurance = sysUserLevelInsurances.get(sysUserLevelInsurances.size() - 1);
        BigDecimal accumulationRadix = sysUserLevelInsurance.getAccumulationFund().multiply(BigDecimal.valueOf(sysUserLevelInsurance.getAccumulationFundCompany() / 100));
        BigDecimal pensionRadix = sysUserLevelInsurance.getRetirementInsurance().multiply(BigDecimal.valueOf(sysUserLevelInsurance.getRetirementInsuranceCompany() / 100));
        BigDecimal medicalRadix = sysUserLevelInsurance.getMedicalInsurance().multiply(BigDecimal.valueOf(sysUserLevelInsurance.getMedicalInsuranceCompany() / 100));
        BigDecimal unemploymentRadix = sysUserLevelInsurance.getUnemploymentInsurance().multiply(BigDecimal.valueOf(sysUserLevelInsurance.getUnemploymentInsuranceCompany() / 100));
        BigDecimal maternityRadix = sysUserLevelInsurance.getBirthInsurance().multiply(BigDecimal.valueOf(sysUserLevelInsurance.getBirthInsuranceCompany() / 100));
        BigDecimal industrialInjuryRadix = sysUserLevelInsurance.getEmploymentInsurance().multiply(BigDecimal.valueOf(sysUserLevelInsurance.getEmploymentInsuranceCompany() / 100));
        wageCost = wageCost.add(accumulationRadix.add(pensionRadix).add(medicalRadix).add(unemploymentRadix).add(maternityRadix).add(industrialInjuryRadix).multiply(BigDecimal.valueOf(timeTotalCost)).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
        return wageCost;
    }
    @Override
    public Double getHours(ProjectCostQueryCriteria criteria) throws ParseException {
        // 工时
        Double costHours = 0.0;
        // 工作天数
        LocalDateTime enterProject = criteria.getEnterProjectTime().toLocalDateTime();
        LocalDateTime exitProject = criteria.getExitProjectTime().toLocalDateTime();
        // 通过id获取用户信息
        UserDto user = userService.findById(criteria.getUserId());
        List<SysConfigHoliday> sysConfigHolidayList = sysConfigHolidayRepository.findByHolidayDateBetween(criteria.getEnterProjectTime(), criteria.getExitProjectTime());
        for (LocalDate currentLocalDate = enterProject.toLocalDate();
                currentLocalDate.isBefore(exitProject.toLocalDate()) || currentLocalDate.isEqual(exitProject.toLocalDate());
                currentLocalDate = currentLocalDate.plusDays(1)) {
            String dateType = "";
            for (SysConfigHoliday sysConfigHoliday : sysConfigHolidayList) {
                if (currentLocalDate.isEqual(sysConfigHoliday.getHolidayDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())) {
                    dateType = sysConfigHoliday.getDateType();
                    break;
                }
            }
            if ("".equals(dateType)) {
                dateType = currentLocalDate.getDayOfWeek() == DayOfWeek.SATURDAY || currentLocalDate.getDayOfWeek() == DayOfWeek.SUNDAY ? Constant.DATE_TYPE_WEEKEND : Constant.DATE_TYPE_WEEKDAY;
            }
            if (Constant.DATE_TYPE_WEEKEND.equals(dateType) || Constant.DATE_TYPE_LEGAL_HOLIDAYS.equals(dateType) || Constant.DATE_TYPE_HOLIDAYS.equals(dateType)) {
                continue;
            }
            SysRosteringDto sysRostering = user.getSysRostering();
            if (currentLocalDate.isEqual(exitProject.toLocalDate())) {
                if (exitProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) > 0 && exitProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) <= 0) {
                    if (exitProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) > 0) {
                        exitProject = exitProject.with(sysRostering.getLunchStartTime());
                    }
                    costHours = costHours + BigDecimal.valueOf(sysRostering.getWorkStartTime().until(exitProject.toLocalTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                } else if (exitProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) > 0 && exitProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) < 0) {
                    costHours = costHours + BigDecimal.valueOf(sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES) + sysRostering.getLunchEndTime().until(exitProject.toLocalTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                } else if (exitProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) >= 0) {
                    costHours = costHours + BigDecimal.valueOf(sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                }
            } else if (currentLocalDate.isEqual(enterProject.toLocalDate())) {
                if (enterProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) <= 0) {
                    costHours = costHours + BigDecimal.valueOf(sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                } else if (enterProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) > 0 && enterProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) <= 0) {
                    costHours = costHours + BigDecimal.valueOf(sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES) + enterProject.toLocalTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                } else if (enterProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) > 0 && enterProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) < 0) {
                    if (enterProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) < 0) {
                        enterProject = enterProject.with(sysRostering.getLunchEndTime());
                    }
                    costHours = costHours + BigDecimal.valueOf(enterProject.toLocalTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                }
            } else {
                costHours = costHours + BigDecimal.valueOf(sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
            }
        }
        return costHours;
    }
    @Override
    public ProjectCost getCost(ProjectCostQueryCriteria criteria) throws ParseException {
        ProjectCost projectCost = new ProjectCost();
        // 工资
        BigDecimal wageCost = BigDecimal.valueOf(0);
        // 工时
        Double costHours = 0.0;
        // 工作天数
        LocalDateTime enterProject = criteria.getEnterProjectTime().toLocalDateTime();
        LocalDateTime exitProject = criteria.getExitProjectTime().toLocalDateTime();
        Date startDate = criteria.getEnterProjectTime();
        Date endDate = criteria.getExitProjectTime();
        // 通过id获取用户信息
        UserDto user = userService.findById(criteria.getUserId());
//        // 通过id获取用户级别工资
//        Optional<SysUserLevelWage> sysUserLevelWageOpl = sysUserLevelWageRepository.findByUserId(criteria.getUserId())
//                .stream().filter(sysUserLevelWage -> !((sysUserLevelWage.getEndDate() != null && sysUserLevelWage.getEndDate().before(startDate)) || sysUserLevelWage.getStartDate().after(endDate)))
//                .max((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
//        // 通过id获取用户级别保险
//        Optional<SysUserLevelInsurance> sysUserLevelInsuranceOpl = sysUserLevelInsuranceRepository.findByUserId(criteria.getUserId())
//                .stream().filter(sysUserLevelInsurance -> !((sysUserLevelInsurance.getEndDate() != null && sysUserLevelInsurance.getEndDate().before(startDate)) || sysUserLevelInsurance.getStartDate().after(endDate)))
//                .max((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
        List<UserLevelWage> userLevelWageList = sysUserLevelWageRepository.findUserLevelWageByUserId(criteria.getUserId());
        List<UserInsurance> userInsurances = sysUserLevelInsuranceRepository.findByUserId(criteria.getUserId());
        // 判断是否有用户级别工资
        if (userLevelWageList.size() == 0) {
            throw new BadRequestException("此用户暂无级别工资");
        }
        // 判断是否有用户级别保险
        if (userInsurances.size() == 0) {
            throw new BadRequestException("此用户暂无级别保险");
        }
        if (criteria.getInvolvementHours() == null) {
            // 获取假期数据
            List<SysConfigHoliday> sysConfigHolidayList = sysConfigHolidayRepository.findByHolidayDateBetween(criteria.getEnterProjectTime(), criteria.getExitProjectTime());
            for (LocalDate currentLocalDate = enterProject.toLocalDate();
                    currentLocalDate.isBefore(exitProject.toLocalDate()) || currentLocalDate.isEqual(exitProject.toLocalDate());
                    currentLocalDate = currentLocalDate.plusDays(1)) {
                String dateType = "";
                for (SysConfigHoliday sysConfigHoliday : sysConfigHolidayList) {
                    if (currentLocalDate.isEqual(sysConfigHoliday.getHolidayDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())) {
                        dateType = sysConfigHoliday.getDateType();
                        break;
                    }
                }
                if ("".equals(dateType)) {
                    dateType = currentLocalDate.getDayOfWeek() == DayOfWeek.SATURDAY || currentLocalDate.getDayOfWeek() == DayOfWeek.SUNDAY ? Constant.DATE_TYPE_WEEKEND : Constant.DATE_TYPE_WEEKDAY;
                }
                if (Constant.DATE_TYPE_WEEKEND.equals(dateType) || Constant.DATE_TYPE_LEGAL_HOLIDAYS.equals(dateType) || Constant.DATE_TYPE_HOLIDAYS.equals(dateType)) {
                    continue;
                }
                SysRosteringDto sysRostering = user.getSysRostering();
                if (currentLocalDate.isEqual(exitProject.toLocalDate())) {
                    if (exitProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) > 0 && exitProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) <= 0) {
                        if (exitProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) > 0) {
                            exitProject = exitProject.with(sysRostering.getLunchStartTime());
                        }
                        costHours = costHours + BigDecimal.valueOf(sysRostering.getWorkStartTime().until(exitProject.toLocalTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                    } else if (exitProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) > 0 && exitProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) < 0) {
                        costHours = costHours + BigDecimal.valueOf(sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES) + sysRostering.getLunchEndTime().until(exitProject.toLocalTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                    } else if (exitProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) >= 0) {
                        costHours = costHours + BigDecimal.valueOf(sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                    }
                } else if (currentLocalDate.isEqual(enterProject.toLocalDate())) {
                    if (enterProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) <= 0) {
                        costHours = costHours + BigDecimal.valueOf(sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                    } else if (enterProject.toLocalTime().compareTo(sysRostering.getWorkStartTime()) > 0 && enterProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) <= 0) {
                        costHours = costHours + BigDecimal.valueOf(sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES) + enterProject.toLocalTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                    } else if (enterProject.toLocalTime().compareTo(sysRostering.getLunchStartTime()) > 0 && enterProject.toLocalTime().compareTo(sysRostering.getWorkEndTime()) < 0) {
                        if (enterProject.toLocalTime().compareTo(sysRostering.getLunchEndTime()) < 0) {
                            enterProject = enterProject.with(sysRostering.getLunchEndTime());
                        }
                        costHours = costHours + BigDecimal.valueOf(enterProject.toLocalTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                    }
                } else {
                    costHours = costHours + BigDecimal.valueOf(sysRostering.getLunchEndTime().until(sysRostering.getWorkEndTime(), ChronoUnit.MINUTES) + sysRostering.getWorkStartTime().until(sysRostering.getLunchStartTime(), ChronoUnit.MINUTES)).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_CEILING).doubleValue();
                }
            }
        } else {
            costHours = criteria.getInvolvementHours();
        }
        // 参与工时
        projectCost.setInvolvementHours(BigDecimal.valueOf(costHours));
        // 用户级别工资成本
        wageCost = wageCost.add(userLevelWageList.get(0).getBasicWage())
                .add(userLevelWageList.get(0).getRankWage())
                .add(userLevelWageList.get(0).getPerformanceWage())
                .multiply(BigDecimal.valueOf(costHours))
                .divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING);
        // 用户级别保险成本
        UserInsurance sysLevelInsurance = userInsurances.stream().max(Comparator.comparing(UserInsurance::getYearMonth)).orElseGet(UserInsurance::new);
        BigDecimal accumulationRadix = sysLevelInsurance.getAccumulationFund().multiply(BigDecimal.valueOf(sysLevelInsurance.getAccumulationFundCompany() / 100));
        BigDecimal pensionRadix = sysLevelInsurance.getRetirementInsurance().multiply(BigDecimal.valueOf(sysLevelInsurance.getRetirementInsuranceCompany() / 100));
        BigDecimal medicalRadix = sysLevelInsurance.getMedicalInsurance().multiply(BigDecimal.valueOf(sysLevelInsurance.getMedicalInsuranceCompany() / 100));
        BigDecimal unemploymentRadix = sysLevelInsurance.getUnemploymentInsurance().multiply(BigDecimal.valueOf(sysLevelInsurance.getUnemploymentInsuranceCompany() / 100));
        BigDecimal maternityRadix = sysLevelInsurance.getBirthInsurance().multiply(BigDecimal.valueOf(sysLevelInsurance.getBirthInsuranceCompany() / 100));
        BigDecimal industrialInjuryRadix = sysLevelInsurance.getEmploymentInsurance().multiply(BigDecimal.valueOf(sysLevelInsurance.getEmploymentInsuranceCompany() / 100));
        wageCost = wageCost.add(accumulationRadix.add(pensionRadix).add(medicalRadix).add(unemploymentRadix).add(maternityRadix).add(industrialInjuryRadix).multiply(BigDecimal.valueOf(costHours)).divide(BigDecimal.valueOf(160), 2, BigDecimal.ROUND_CEILING));
        projectCost.setProjectCost(wageCost);
        return projectCost;
    }
    @Override
    public void download(List<ProjectCostDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectCostDto projectCost : all) {
            String projectName = projectCost.getProjectId() != null ? projectRepository.findById(projectCost.getProjectId()).orElseGet(Project::new).getName() : "";
            String user = projectCost.getUserId() != null ? userRepository.findById(projectCost.getUserId()).orElseGet(User::new).getNickName() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("项目", projectName);
            map.put("用户", user);
            map.put("进入项目时间", projectCost.getEnterProjectTime());
            map.put("退出项目时间", projectCost.getExitProjectTime());
            map.put("参与时间", projectCost.getInvolvementHours());
            map.put("项目成本", projectCost.getProjectCost());
            map.put("备注", projectCost.getRemarks());
            map.put("创建者", projectCost.getCreateBy());
            map.put("创建时间", projectCost.getCreateTime());
            map.put("更新者", projectCost.getUpdateBy());
            map.put("更新时间", projectCost.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/impl/ProjectProgressServiceImpl.java
@@ -1,337 +1,313 @@
/*
*  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.project.service.impl;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.domain.Project;
import me.zhengjie.modules.project.domain.ProjectProgress;
import me.zhengjie.modules.project.repository.ProjectProgressRepository;
import me.zhengjie.modules.project.repository.ProjectRepository;
import me.zhengjie.modules.project.service.ProjectCostService;
import me.zhengjie.modules.project.service.ProjectProgressService;
import me.zhengjie.modules.project.service.dto.ProjectProgressDto;
import me.zhengjie.modules.project.service.dto.ProjectProgressQueryCriteria;
import me.zhengjie.modules.project.service.mapstruct.ProjectProgressMapper;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.task.domain.Task;
import me.zhengjie.modules.task.domain.TaskDailyInterface;
import me.zhengjie.modules.task.domain.TaskDaliy;
import me.zhengjie.modules.task.domain.TaskInterface;
import me.zhengjie.modules.task.repository.TaskDaliyRepository;
import me.zhengjie.modules.task.repository.TaskRepository;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author HuaZhe
* @date 2022-12-23
**/
@Service
@RequiredArgsConstructor
public class ProjectProgressServiceImpl implements ProjectProgressService {
    private final ProjectProgressRepository projectProgressRepository;
    private final ProjectProgressMapper projectProgressMapper;
    private final ProjectRepository projectRepository;
    private final DictDetailRepository dictDetailRepository;
    private final TaskRepository taskRepository;
    private final TaskDaliyRepository taskDaliyRepository;
    private final ProjectCostService projectCostService;
    @Override
    public Map<String,Object> queryAll(ProjectProgressQueryCriteria criteria, Pageable pageable){
        Page<ProjectProgress> page = projectProgressRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder), pageable);
        // 当年第一周需满足四天。(例:2022年的第一周是从1月3号开始的,1号和2号并入到2021年度的最后一周里)
        WeekFields wfs = WeekFields.of(DayOfWeek.MONDAY, 4);
        // 将实体类转换为DTO(重写)
        Function<ProjectProgress, ProjectProgressDto> func = new Function<ProjectProgress, ProjectProgressDto>() {
            @Override
            public ProjectProgressDto apply(ProjectProgress projectProgress) {
                // 将实体类转换成DTO
                ProjectProgressDto projectProgressDto = projectProgressMapper.toDto(projectProgress);
                // 获取前一周的周五
                LocalDate localDate = LocalDate.now()
                                        .with(wfs.weekBasedYear(), projectProgress.getBelongYear())
                                        .with(wfs.weekOfWeekBasedYear(), projectProgress.getBelongWeek())
                                        .with(wfs.dayOfWeek(), 5L)
                                        .minusDays(7);
                // 获取前一周的项目进度信息
                Optional<ProjectProgress> projectProgressOpl = projectProgressRepository.findByBelongYearAndBelongWeekAndProjectId(localDate.get(wfs.weekBasedYear()), localDate.get(wfs.weekOfWeekBasedYear()), projectProgressDto.getProject().getId());
                projectProgressDto.setLastProjectProcess(projectProgressOpl.orElseGet(ProjectProgress::new));
                if (projectProgressDto.getProjectProgress() == null) {
                    projectProgressDto.setProjectProgress(0.0);
                }
                if (projectProgressDto.getEstimatedProgress() == null) {
                    projectProgressDto.setEstimatedProgress(0.0);
                }
                return projectProgressDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<ProjectProgressDto> queryAll(ProjectProgressQueryCriteria criteria){
        return projectProgressMapper.toDto(projectProgressRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
    @Override
    @Transactional
    public ProjectProgressDto findById(Long id) {
        ProjectProgress projectProgress = projectProgressRepository.findById(id).orElseGet(ProjectProgress::new);
        ValidationUtil.isNull(projectProgress.getId(),"ProjectProgress","id",id);
        return projectProgressMapper.toDto(projectProgress);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectProgressDto create(ProjectProgress resources) {
        // 项目进度 check
        checkProjectProgress(resources);
        // 项目是否已承认
        Project project = projectRepository.findByIdUpdate(resources.getProject().getId());
        if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_UNRECOGNIZED)){
            throw new BadRequestException("项目未承认无法创建周报");
        }
        resources.setProject(project);
        // 当年第一周需满足四天。(例:2022年的第一周是从1月3号开始的,1号和2号并入到2021年度的最后一周里)
        WeekFields wfs = WeekFields.of(DayOfWeek.MONDAY, 4);
        // 所属日未设定的场合,取对应周的周五
        if (resources.getBelongDate() == null) {
            LocalDate localDate = LocalDate.now()
                    .with(wfs.weekBasedYear(), resources.getBelongYear())
                    .with(wfs.weekOfWeekBasedYear(), resources.getBelongWeek())
                    .plusWeeks(1)
                    .with(wfs.dayOfWeek(), 1L);
            resources.setBelongDate(Timestamp.valueOf(localDate.atStartOfDay()));
        }
        return generalProjectProgress(resources);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProjectProgress resources) {
        ProjectProgress projectProgress = projectProgressRepository.findById(resources.getId()).orElseGet(ProjectProgress::new);
        ValidationUtil.isNull( projectProgress.getId(),"ProjectProgress","id",resources.getId());
        // 项目是否已承认
        Project project = projectRepository.findByIdUpdate(resources.getProject().getId());
        if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_UNRECOGNIZED)){
            throw new BadRequestException("项目未承认无法创建周报");
        }
        resources.setProject(project);
        // 周报是否已承认
        if(projectProgress.getApproveStatus().equals(Constant.APPROVE_STATUS_ACKNOWLEDGED)){
            throw new BadRequestException("周报已承认无法修改");
        }
        // 当年第一周需满足四天。(例:2022年的第一周是从1月3号开始的,1号和2号并入到2021年度的最后一周里)
        WeekFields wfs = WeekFields.of(DayOfWeek.MONDAY, 4);
        // 所属日未设定的场合,取对应周的周五
        if (resources.getBelongDate() == null) {
            LocalDate localDate = LocalDate.now()
                    .with(wfs.weekBasedYear(), resources.getBelongYear())
                    .with(wfs.weekOfWeekBasedYear(), resources.getBelongWeek())
                    .with(wfs.dayOfWeek(), 5L);
            resources.setBelongDate(Timestamp.valueOf(localDate.atStartOfDay()));
        }
        projectProgress.copy(resources);
        generalProjectProgress(resources);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoGenerateProjectProcess(LocalDate localDate, Integer year, Integer weeks) {
        // 获取所有的【进行中】的项目
        List<Project> projectList = projectRepository.findByProjectStatus(Constant.PROJECT_STATUS_UNDER_WAY);
        projectList.forEach(project -> {
            // 存在则更新,不存在则插入
            ProjectProgress projectProgress = projectProgressRepository.findByBelongYearAndBelongWeekAndProjectId(year, weeks, project.getId()).orElseGet(ProjectProgress::new);
            // 初始主键
            if (projectProgress.getId() == null) {
                projectProgress.setBelongYear(year);
                projectProgress.setBelongWeek(weeks);
                projectProgress.setBelongDate(Timestamp.valueOf(localDate.atStartOfDay()));
                projectProgress.setProject(project);
                projectProgress.setApproveStatus(Constant.APPROVE_STATUS_UNRECOGNIZED);
            }
            // 如果已经承认则不需要更新
            if (Constant.APPROVE_STATUS_ACKNOWLEDGED.equals(projectProgress.getApproveStatus())) {
                return;
            }
            generalProjectProgress(projectProgress);
        });
    }
    private ProjectProgressDto generalProjectProgress(ProjectProgress resources) {
        // 总消化工时
//        Double timeTotalCost = 0.0;
        // 总消耗工作量
        Double workTotalCost = 0.0;
        // 真实时长
        Double realLastCost = 0.0;
        List<TaskDailyInterface> taskDaliyWithTaskList = taskDaliyRepository.collectByProjectIdAndFillDateLessThanGroupByTaskIdJoinTask(resources.getProject().getId(), resources.getBelongDate()); // TODO error
        for (TaskDailyInterface taskDaily : taskDaliyWithTaskList) {
            // 总消化工时
//            timeTotalCost += BigDecimal.valueOf(taskDaily.getPlanHours()).multiply(BigDecimal.valueOf(taskDaily.getTaskProgress())).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_CEILING).doubleValue();
            // 总消耗工作量
            workTotalCost += taskDaily.getConsumedWorkload();
            // 真实时长
            realLastCost += taskDaily.getConsumedHours();
        }
        // 总消化工时
//        resources.setTimeTotalCost(timeTotalCost);
        // 总消耗工作量
        resources.setWorkTotalCost(workTotalCost);
        // 真实时长
        resources.setRealLastCost(realLastCost);
        if (resources.getId() == null) {
            // 根据项目ID取得任务信息
            TaskInterface taskTotal = taskRepository.collectByProjectId(resources.getProject().getId());
            // 总工时
            resources.setTimeTotalInit(taskTotal.getPlanHours());
            // 总工作量
            resources.setWorkTotalInit(taskTotal.getPlanWorkload());
            // 计划总成本
            resources.setMoneyTotalInit(resources.getProject().getPerformancePrice().multiply(BigDecimal.valueOf(taskTotal.getPlanHours())).divide(BigDecimal.valueOf(160)));
        }
        // 根据日期和项目ID取得日报信息
        List<TaskDailyInterface> taskDaliyList = taskDaliyRepository.collectByProjectIdAndFillDateLessThanGroupByUserIdAndFillDate(resources.getProject().getId(), resources.getBelongDate());
        Map<Long, List<TaskDailyInterface>> collectMap = taskDaliyList.stream().collect(Collectors.groupingBy(TaskDailyInterface::getUserId));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 总消耗成本
        BigDecimal totalCost = BigDecimal.valueOf(0.0);
        for (Entry<Long, List<TaskDailyInterface>> entry : collectMap.entrySet()) {
            List<TaskDailyInterface> taskDaliyListSub = entry.getValue();
            // 最小日期
            TaskDailyInterface taskDaliyFirst = taskDaliyListSub.stream().min(Comparator.comparing(taskDaliy -> taskDaliy.getFillDate())).get();
            // 最大日期
            TaskDailyInterface taskDaliyLast = taskDaliyListSub.stream().max(Comparator.comparing(taskDaliy -> taskDaliy.getFillDate())).get();
            Map<String, Double> costHourMap = new HashMap<String, Double>();
            taskDaliyListSub.forEach(taskDaliy -> {
                costHourMap.put(sdf.format(taskDaliy.getFillDate()), taskDaliy.getConsumedHours());
            });
            // 根据员工成本单金算出当前工作的成本
            totalCost = totalCost.add(projectCostService.calcUserCostByDate(entry.getKey(), new Timestamp(taskDaliyFirst.getFillDate().getTime()), new Timestamp(taskDaliyLast.getFillDate().getTime()), costHourMap));
        }
        // 总消耗成本
        resources.setMoneyTotalCost(totalCost);
        return projectProgressMapper.toDto(projectProgressRepository.save(resources));
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            projectProgressRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<ProjectProgressDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectProgressDto projectProgress : all) {
            String projectName = projectProgress.getProject().getId() != null ? projectRepository.findById(projectProgress.getProject().getId()).orElseGet(Project::new).getName() : "";
            String approveStatus= projectProgress.getApproveStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.APPROVAL_STATUS, projectProgress.getApproveStatus()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("项目", projectName);
            map.put("项目进度", projectProgress.getProjectProgress());
            map.put("批准状态", approveStatus);
            map.put("备注", projectProgress.getRemarks());
            map.put("总绩效工时", projectProgress.getTimeTotalInit());
            map.put("总消耗绩效工时", projectProgress.getTimeTotalCost());
            map.put("实际消化工时", projectProgress.getRealLastCost());
            map.put("总工作量", projectProgress.getWorkTotalInit());
            map.put("总消耗工作量", projectProgress.getWorkTotalCost());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    public void checkProjectProgress(ProjectProgress resources) {
        // 获取前次月报的最大进度。
        List<ProjectProgress> list = projectProgressRepository.findByProjectId(resources.getProject().getId(), resources.getBelongDate());
        if (list.size() > 0 && list.get(0).getProjectProgress() != null) {
            if (resources.getProjectProgress() <= list.get(0).getProjectProgress()) {
                throw new BadRequestException("项目进度必须大于上一次的项目进度");
            }
        }
    }
    @Override
    public List<Integer> queryYearSelection() {
        return projectProgressRepository.findAllBelongYear();
    }
    @Override
    public List<Integer> queryWeeksSelection(Integer year) {
        return projectProgressRepository.findAllBelongWeekByBelongYear(year);
    }
/*
*  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.project.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.domain.Project;
import me.zhengjie.modules.project.domain.ProjectProgress;
import me.zhengjie.modules.project.domain.ProjectProgressDetail;
import me.zhengjie.modules.project.repository.ProjectProgressRepository;
import me.zhengjie.modules.project.repository.ProjectRepository;
import me.zhengjie.modules.project.service.ProjectCostService;
import me.zhengjie.modules.project.service.ProjectProgressService;
import me.zhengjie.modules.project.service.dto.ProjectProgressDto;
import me.zhengjie.modules.project.service.dto.ProjectProgressQueryCriteria;
import me.zhengjie.modules.project.service.mapstruct.ProjectProgressMapper;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.task.domain.TaskMongo;
import me.zhengjie.modules.task.domain.TaskUserMongo;
import me.zhengjie.modules.task.repository.TaskDaliyRepository;
import me.zhengjie.modules.task.repository.TaskRepository;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
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.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @website https://eladmin.vip
* @description 服务实现
* @author HuaZhe
* @date 2022-12-23
**/
@Service
@RequiredArgsConstructor
public class ProjectProgressServiceImpl implements ProjectProgressService {
    private final ProjectProgressRepository projectProgressRepository;
    private final ProjectProgressMapper projectProgressMapper;
    private final ProjectRepository projectRepository;
    private final DictDetailRepository dictDetailRepository;
    private final TaskRepository taskRepository;
    private final TaskDaliyRepository taskDaliyRepository;
    private final ProjectCostService projectCostService;
    private final MongoTemplate mongoTemplate;
    @Override
    public Map<String,Object> queryAll(ProjectProgressQueryCriteria criteria, Pageable pageable){
        Page<ProjectProgress> page = projectProgressRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder), pageable);
        // 当年第一周需满足四天。(例:2022年的第一周是从1月3号开始的,1号和2号并入到2021年度的最后一周里)
        WeekFields wfs = WeekFields.of(DayOfWeek.MONDAY, 4);
        // 将实体类转换为DTO(重写)
        Function<ProjectProgress, ProjectProgressDto> func = new Function<ProjectProgress, ProjectProgressDto>() {
            @Override
            public ProjectProgressDto apply(ProjectProgress projectProgress) {
                // 将实体类转换成DTO
                ProjectProgressDto projectProgressDto = projectProgressMapper.toDto(projectProgress);
                // 获取前一周的周五
                LocalDate localDate = LocalDate.now()
                                        .with(wfs.weekBasedYear(), projectProgress.getBelongYear())
                                        .with(wfs.weekOfWeekBasedYear(), projectProgress.getBelongWeek())
                                        .with(wfs.dayOfWeek(), 5L)
                                        .minusDays(7);
                // 获取前一周的项目进度信息
                Optional<ProjectProgress> projectProgressOpl = projectProgressRepository.findByBelongYearAndBelongWeekAndProjectId(localDate.get(wfs.weekBasedYear()), localDate.get(wfs.weekOfWeekBasedYear()), projectProgressDto.getProject().getId());
                projectProgressDto.setLastProjectProcess(projectProgressOpl.orElseGet(ProjectProgress::new));
                if (projectProgressDto.getProjectProgress() == null) {
                    projectProgressDto.setProjectProgress(0.0);
                }
                if (projectProgressDto.getEstimatedProgress() == null) {
                    projectProgressDto.setEstimatedProgress(0.0);
                }
                return projectProgressDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<ProjectProgressDto> queryAll(ProjectProgressQueryCriteria criteria){
        return projectProgressMapper.toDto(projectProgressRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
    @Override
    @Transactional
    public ProjectProgressDto findById(Long id) {
        ProjectProgress projectProgress = projectProgressRepository.findById(id).orElseGet(ProjectProgress::new);
        ValidationUtil.isNull(projectProgress.getId(),"ProjectProgress","id",id);
        return projectProgressMapper.toDto(projectProgress);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectProgressDto create(ProjectProgress resources) {
        // 项目进度 check
        checkProjectProgress(resources);
        // 项目是否已承认
        Project project = projectRepository.findByIdUpdate(resources.getProject().getId());
        if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_UNRECOGNIZED)){
            throw new BadRequestException("项目未承认无法创建周报");
        }
        resources.setProject(project);
        // 当年第一周需满足四天。(例:2022年的第一周是从1月3号开始的,1号和2号并入到2021年度的最后一周里)
        WeekFields wfs = WeekFields.of(DayOfWeek.MONDAY, 4);
        // 所属日未设定的场合,取对应周的周五
        if (resources.getBelongDate() == null) {
            LocalDate localDate = LocalDate.now()
                    .with(wfs.weekBasedYear(), resources.getBelongYear())
                    .with(wfs.weekOfWeekBasedYear(), resources.getBelongWeek())
                    .plusWeeks(1)
                    .with(wfs.dayOfWeek(), 1L);
            resources.setBelongDate(Timestamp.valueOf(localDate.atStartOfDay()));
        }
        return generalProjectProgress(resources);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProjectProgress resources) {
        ProjectProgress projectProgress = projectProgressRepository.findById(resources.getId()).orElseGet(ProjectProgress::new);
        ValidationUtil.isNull( projectProgress.getId(),"ProjectProgress","id",resources.getId());
        // 项目是否已承认
        Project project = projectRepository.findByIdUpdate(resources.getProject().getId());
        if(project.getApproveStatus().equals(Constant.APPROVE_STATUS_UNRECOGNIZED)){
            throw new BadRequestException("项目未承认无法创建周报");
        }
        resources.setProject(project);
        // 周报是否已承认
        if(projectProgress.getApproveStatus().equals(Constant.APPROVE_STATUS_ACKNOWLEDGED)){
            throw new BadRequestException("周报已承认无法修改");
        }
        // 当年第一周需满足四天。(例:2022年的第一周是从1月3号开始的,1号和2号并入到2021年度的最后一周里)
        WeekFields wfs = WeekFields.of(DayOfWeek.MONDAY, 4);
        // 所属日未设定的场合,取对应周的周五
        if (resources.getBelongDate() == null) {
            LocalDate localDate = LocalDate.now()
                    .with(wfs.weekBasedYear(), resources.getBelongYear())
                    .with(wfs.weekOfWeekBasedYear(), resources.getBelongWeek())
                    .with(wfs.dayOfWeek(), 5L);
            resources.setBelongDate(Timestamp.valueOf(localDate.atStartOfDay()));
        }
        projectProgress.copy(resources);
        generalProjectProgress(resources);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoGenerateProjectProcess(LocalDate localDate, Integer year, Integer weeks) {
        // 获取所有的【进行中】的项目
        List<Project> projectList = projectRepository.findByProjectStatus(Constant.PROJECT_STATUS_UNDER_WAY);
        projectList.forEach(project -> {
            // 存在则更新,不存在则插入
            ProjectProgress projectProgress = projectProgressRepository.findByBelongYearAndBelongWeekAndProjectId(year, weeks, project.getId()).orElseGet(ProjectProgress::new);
            // 初始主键
            if (projectProgress.getId() == null) {
                projectProgress.setBelongYear(year);
                projectProgress.setBelongWeek(weeks);
                projectProgress.setBelongDate(Timestamp.valueOf(localDate.atStartOfDay()));
                projectProgress.setProject(project);
                projectProgress.setApproveStatus(Constant.APPROVE_STATUS_UNRECOGNIZED);
            }
            // 如果已经承认则不需要更新
            if (Constant.APPROVE_STATUS_ACKNOWLEDGED.equals(projectProgress.getApproveStatus())) {
                return;
            }
            generalProjectProgress(projectProgress);
        });
    }
    private ProjectProgressDto generalProjectProgress(ProjectProgress resources) {
        Query query = new Query(Criteria.where("projectId").is(resources.getProject().getId()));
        List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
        Aggregation customerAgg = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("task").in(taskMongoList)),
                Aggregation.project("userId", "taskHours", "costHours"),
                Aggregation.group("userId").sum("taskHours").as("taskHours").sum("costHours").as("costHours")
        );
        AggregationResults<Map> aggregate = mongoTemplate.aggregate(customerAgg, TaskUserMongo.class, Map.class);
        List<ProjectProgressDetail> projectProgressDetailList = aggregate.getMappedResults().stream().filter(data -> data.get("_id") != null).map(data -> {
            ProjectProgressDetail projectProgressDetail = new ProjectProgressDetail();
            projectProgressDetail.setUserId(Long.parseLong(String.valueOf(data.get("_id"))));
            BigDecimal taskHours = new BigDecimal(String.valueOf(data.get("taskHours")));
            projectProgressDetail.setTimeInitCost(taskHours.setScale(2, RoundingMode.HALF_UP).doubleValue());
            BigDecimal costHours = new BigDecimal(String.valueOf(data.get("costHours")));
            projectProgressDetail.setTimeTotalCost(costHours.setScale(2, RoundingMode.HALF_UP).doubleValue());
            BigDecimal moneyTotalCost = projectCostService.calcUserCostByHours(projectProgressDetail.getUserId(), projectProgressDetail.getTimeTotalCost());
            projectProgressDetail.setMoneyTotalCost(moneyTotalCost);
            return projectProgressDetail;
        }).collect(Collectors.toList());
        // 任务总时间
        resources.setTimeTotalInit(projectProgressDetailList.stream().mapToDouble(ProjectProgressDetail::getTimeInitCost).sum());
        // 消耗总时间
        resources.setTimeTotalCost(projectProgressDetailList.stream().mapToDouble(ProjectProgressDetail::getTimeTotalCost).sum());
        // 计划总成本
        resources.setMoneyTotalInit(resources.getProject().getProjectPrice().multiply(BigDecimal.valueOf(10000)));
        // 已分配总成本
        resources.setMoneyTotalCost(BigDecimal.valueOf(resources.getTimeTotalCost()).multiply(BigDecimal.valueOf(11250)).divide(BigDecimal.valueOf(160), 2, RoundingMode.HALF_UP));
        // 总消耗成本
        resources.setMoneyRealCost(projectProgressDetailList.stream().map(ProjectProgressDetail::getMoneyTotalCost).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP));
        ProjectProgressDto projectProgressDto = projectProgressMapper.toDto(projectProgressRepository.save(resources));
        return projectProgressDto;
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            projectProgressRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<ProjectProgressDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectProgressDto projectProgress : all) {
            String projectName = projectProgress.getProject().getId() != null ? projectRepository.findById(projectProgress.getProject().getId()).orElseGet(Project::new).getName() : "";
            String approveStatus= projectProgress.getApproveStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.APPROVAL_STATUS, projectProgress.getApproveStatus()).getLabel() : "";
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("项目", projectName);
            map.put("项目进度", projectProgress.getProjectProgress());
            map.put("批准状态", approveStatus);
            map.put("备注", projectProgress.getRemarks());
            map.put("总绩效工时", projectProgress.getTimeTotalInit());
            map.put("总消耗绩效工时", projectProgress.getTimeTotalCost());
            map.put("实际消化工时", projectProgress.getRealLastCost());
            map.put("总工作量", projectProgress.getWorkTotalInit());
            map.put("总消耗工作量", projectProgress.getWorkTotalCost());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    public void checkProjectProgress(ProjectProgress resources) {
        // 获取前次月报的最大进度。
        List<ProjectProgress> list = projectProgressRepository.findByProjectId(resources.getProject().getId(), resources.getBelongDate());
        if (list.size() > 0 && list.get(0).getProjectProgress() != null) {
            if (resources.getProjectProgress() <= list.get(0).getProjectProgress()) {
                throw new BadRequestException("项目进度必须大于上一次的项目进度");
            }
        }
    }
    @Override
    public List<Integer> queryYearSelection() {
        return projectProgressRepository.findAllBelongYear();
    }
    @Override
    public List<Integer> queryWeeksSelection(Integer year) {
        return projectProgressRepository.findAllBelongWeekByBelongYear(year);
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/project/service/impl/ProjectServiceImpl.java
@@ -1,813 +1,810 @@
/*
 *  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.project.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.contract.repository.ContractProjectRepository;
import me.zhengjie.modules.cost.repository.CostRepository;
import me.zhengjie.modules.project.domain.*;
import me.zhengjie.modules.project.repository.*;
import me.zhengjie.modules.project.service.ProjectCostService;
import me.zhengjie.modules.project.service.ProjectService;
import me.zhengjie.modules.project.service.dto.ProjectDto;
import me.zhengjie.modules.project.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.project.service.dto.ProjectTypeQueryCriteria;
import me.zhengjie.modules.project.service.mapstruct.ProjectMapper;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.SysExchangeRateService;
import me.zhengjie.modules.system.service.SysGoalSettingService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.task.domain.*;
import me.zhengjie.modules.task.repository.TaskDaliyRepository;
import me.zhengjie.modules.task.repository.TaskRepository;
import me.zhengjie.modules.task.repository.TaskUserRepository;
import me.zhengjie.modules.task.service.TaskService;
import me.zhengjie.modules.task.service.dto.TaskDto;
import me.zhengjie.modules.task.service.dto.TaskUserTotalDetailMongoDto;
import me.zhengjie.modules.task.service.mapstruct.TaskMapper;
import me.zhengjie.utils.*;
import me.zhengjie.utils.enums.DataScopeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
 * @author HuaZhe
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-12-15
 **/
@Service
@RequiredArgsConstructor
public class ProjectServiceImpl implements ProjectService { // TODO redis化
    private final ProjectRepository projectRepository;
    private final ProjectMapper projectMapper;
    private final ProjectTypeRepository projectTypeRepository;
    private final UserRepository userRepository;
    private final DictDetailRepository dictDetailRepository;
    private final ProjectTaskRepository projectTaskRepository;
    private final RoleService roleService;
    private final TaskUserRepository taskUserRepository;
    private final ProjectCostRepository projectCostRepository;
    private final ProjectCostOtherRepository projectCostOtherRepository;
    private final TaskRepository taskRepository;
    private final TaskDaliyRepository taskDaliyRepository;
    private final ProjectCostService projectCostService;
    private final ProjectProgressRepository projectProgressRepository;
    private final ProjectPerformanceRepository projectPerformanceRepository;
    private final ProjectPerformanceDetailRepository projectPerformanceDetailRepository;
    private final CostRepository costRepository;
    private final ContractProjectRepository contractProjectRepository;
    private final SysGoalSettingService sysGoalSettingService;
    @Autowired
    private TaskService taskService;
    private final TaskMapper taskMapper;
    private final SysExchangeRateService sysExchangeRateService;
    private final MongoTemplate mongoTemplate;
    @Override
    public Map<String, Object> queryAll(ProjectQueryCriteria criteria, Pageable pageable) {
        if (criteria.getLiableUserId() == null) {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            // 查询用户角色
            List<RoleSmallDto> roleSet = roleService.findByUsersId(userId);
            if (roleSet.stream().anyMatch(role -> DataScopeEnum.find(role.getDataScope()) == DataScopeEnum.THIS_LEVEL)) {
                // 根据用户ID查询负责的项目ID
                List<Long> projectIdList = projectRepository.findIdByLiableUserId(userId);
                // 根据用户ID查询参与的项目ID
                List<Long> taskUserProjectIdList = projectCostRepository.findProjectIdByUserId(userId);
                // 检索条件
                List<Long> totalProjectIdList = Stream.of(taskUserProjectIdList, projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
                if (totalProjectIdList.size() == 0) {
                    return PageUtil.toPage(Collections.emptyList(), 0);
                }
                criteria.setLiableUserId("-" + userId + "-");
            }
        }
        Page<Project> page = projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        // 将实体类转换为DTO(重写)
        Function<Project, ProjectDto> func = new Function<Project, ProjectDto>() {
            @Override
            public ProjectDto apply(Project project) {
                // 将实体类转换成DTO
                ProjectDto projectDto = projectMapper.toDto(project);
                // 根据项目类型ID查询项目类型信息
                ProjectType projectType = projectTypeRepository.findById(projectDto.getProjectTypeId()).orElseGet(ProjectType::new);
                ValidationUtil.isNull(project.getId(), "ProjectType", "id", projectDto.getProjectTypeId());
                // 项目类型名称
                projectDto.setProjectTypeName(projectType.getName());
                // 判断是否有负责人
                if (projectDto.getLiableUserId() != null) {
                    // 负责人名称
                    String liableUserName = null;
                    // 负责人ID列表
                    List<Long> liableUserIdList = new ArrayList<>();
                    // 负责人ID
                    String handleLiableUserId = projectDto.getLiableUserId().replace("-", "");
                    // 负责人ID列表
                    String[] handleLiableUserIdList = handleLiableUserId.split(",");
                    // 循环负责人ID列表
                    for (String liableUserId : handleLiableUserIdList) {
                        // 负责人ID列表
                        liableUserIdList.add(Long.valueOf(liableUserId));
                        // 根据负责人ID查询用户信息
                        User user = userRepository.findById(Long.valueOf(liableUserId)).orElseGet(User::new);
                        ValidationUtil.isNull(project.getId(), "User", "id", projectDto.getLiableUserId());
                        // 判断负责人名称
                        liableUserName = liableUserName == null ? user.getNickName() : liableUserName + "," + user.getNickName();
                    }
                    // 负责人ID列表
                    projectDto.setLiableUserIdList(liableUserIdList);
                    // 负责人名称
                    projectDto.setLiableUserName(liableUserName);
                }
                ProjectTaskSummary projectTaskSummary = projectTaskRepository.findSummaryByProjectId(project.getId());
                projectDto.setTaskStartDate(projectTaskSummary.getTaskStartDate());
                projectDto.setTaskEndDate(projectTaskSummary.getTaskEndDate());
                projectDto.setTotalTaskTime(projectTaskSummary.getTotalTaskTime());
                ProjectCostSummary projectCostSummary = projectCostRepository.findSummaryByProjectId(project.getId());
                projectDto.setTotalLaborCost(projectCostSummary.getTotalLaborCost());
                // 其他项目成本
                List<ProjectCostOther> projectCostOtherList = projectCostOtherRepository.findByProjectId(project.getId());
                projectDto.setTotalOtherCost(projectCostOtherList.stream().map(ProjectCostOther::getProjectCost).reduce(BigDecimal.ZERO, BigDecimal::add));
                // 查询项目的任务数据
                TaskInterface taskInterface = taskRepository.collectByProjectId(project.getId());
                projectDto.setActualTaskTime(taskInterface.getPlanHours());
                // 根据日期和项目ID取得日报信息
                List<TaskDailyInterface> taskDailyInterfaceList = taskDaliyRepository.collectByProjectIdGroupByUserIdAndFillDate(project.getId());
                Map<Long, List<TaskDailyInterface>> collectMap = taskDailyInterfaceList.stream().collect(Collectors.groupingBy(TaskDailyInterface::getUserId));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                // 实际消耗成本
                BigDecimal actualCost = BigDecimal.valueOf(0.0);
                for (Entry<Long, List<TaskDailyInterface>> entry : collectMap.entrySet()) {
                    List<TaskDailyInterface> taskDaliyListSub = entry.getValue();
                    // 最小日期
                    TaskDailyInterface taskDaliyFirst = taskDaliyListSub.stream().min(Comparator.comparing(taskDaliy -> taskDaliy.getFillDate())).get();
                    // 最大日期
                    TaskDailyInterface taskDaliyLast = taskDaliyListSub.stream().max(Comparator.comparing(taskDaliy -> taskDaliy.getFillDate())).get();
                    Map<String, Double> costHourMap = new HashMap<String, Double>();
                    taskDaliyListSub.forEach(taskDaliy -> {
                        costHourMap.put(sdf.format(taskDaliy.getFillDate()), taskDaliy.getConsumedHours());
                    });
                    // 根据员工成本单金算出当前工作的成本
                    actualCost = actualCost.add(projectCostService.calcUserCostByDate(entry.getKey(), new Timestamp(taskDaliyFirst.getFillDate().getTime()), new Timestamp(taskDaliyLast.getFillDate().getTime()), costHourMap));
                }
                // 实际消耗成本
                projectDto.setActualLaborCost(actualCost);
                // 项目二次处理
                projectDto = customHandle(projectDto);
                // 返回处理好的Dto
                return projectDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<ProjectDto> queryAll2(ProjectQueryCriteria criteria) {
        return projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    private ProjectDto customHandle(ProjectDto projectDto) {
        // 任务合计(已分配)
        Double divideTaskTime = 0D;
        // 任务合计(已完成)
        Double completedTaskTime = 0D;
        // 根据项目ID查询任务列表
        Criteria criteria = new Criteria();
        criteria.and("projectId").is(projectDto.getId());
        Query query = new Query(criteria);
        List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
        Criteria criteriaAggr = Criteria.where("task").in(taskMongoList);
        Aggregation customerAgg = Aggregation.newAggregation(
                Aggregation.match(criteriaAggr),
                Aggregation.project("taskStatus", "taskHours"),
                Aggregation.group("taskStatus").count().as("taskStatusCnt").sum("taskHours").as("taskHours")
        );
        AggregationResults<TaskUserTotalDetailMongoDto> taskUserMongoList = mongoTemplate.aggregate(customerAgg, TaskUserMongo.class, TaskUserTotalDetailMongoDto.class);
        for (TaskUserTotalDetailMongoDto taskUserTotalDetailMongoDto : taskUserMongoList.getMappedResults()) {
            if (Constant.TASK_STATUS_COMPLETED.equals(taskUserTotalDetailMongoDto.get_id())) {
                completedTaskTime += taskUserTotalDetailMongoDto.getTaskHours();
            }
            divideTaskTime += taskUserTotalDetailMongoDto.getTaskHours();
        }
        // 任务合计(已分配)
        projectDto.setDivideTaskTime(DoubleUtil.maximumDigitLimit(divideTaskTime, 2));
        // 任务合计(已完成)
        projectDto.setCompletedTaskTime(DoubleUtil.maximumDigitLimit(completedTaskTime, 2));
        // 任务合计(未完成)
        projectDto.setIncompleteTaskTime(DoubleUtil.maximumDigitLimit(divideTaskTime - completedTaskTime, 2));
        return projectDto;
    }
    @Override
    public List<ProjectDto> queryAll(ProjectQueryCriteria criteria) {
        if (criteria.getLiableUserId() == null) {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            // 查询用户角色
            List<RoleSmallDto> roleSet = roleService.findByUsersId(userId);
            if (roleSet.stream().anyMatch(role -> DataScopeEnum.find(role.getDataScope()) == DataScopeEnum.THIS_LEVEL)) {
                criteria.setLiableUserId("-" + userId + "-");
            }
        }
        return projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    @Override
    public List<ProjectDto> queryRelevant(ProjectQueryCriteria criteria) {
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        List<Long> projectIdList = new ArrayList<>();
        // 判断角色等级
        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
            // 根据用户ID查询参与的项目ID
            //List<Long> taskUserProjectIdList = taskDaliyRepository.findProjectIdByUserId(SecurityUtils.getCurrentUserId());
            //如果当前用户属于一个任务,那么他也可以看见当前这个任务的项目
            Query query = Query.query(Criteria.where("containUserList").is(SecurityUtils.getCurrentUserId()));
            List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
            ArrayList<Long> projectList = new ArrayList<>();
            for (TaskMongo taskMongo : taskMongoList) {
                projectList.add(taskMongo.getProjectId());
            }
            // 根据用户ID查询负责的项目ID
            projectIdList = projectRepository.findIdByLiableUserId(SecurityUtils.getCurrentUserId());
            // 检索条件
            List<Long> totalProjectIdList = Stream.of(projectList, projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
            if (totalProjectIdList.size() == 0) {
                return Collections.emptyList();
            }
            criteria.setIdInList(totalProjectIdList);
        }
        // 项目列表
        List<ProjectDto> projectDtoList = projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        // 循环项目列表
        for (int i = 0; i < projectDtoList.size(); i++) {
            // 项目
            ProjectDto projectDto = projectDtoList.get(i);
            if (projectDto.getLiableUserId() != null && !"".equals(projectDto.getLiableUserId())) {
                // 负责人ID列表
                List<Long> liableUserIdList = new ArrayList<>();
                // 负责人ID
                String handleLiableUserId = projectDto.getLiableUserId().replace("-", "");
                // 负责人ID列表
                String[] handleLiableUserIdList = handleLiableUserId.split(",");
                // 循环负责人ID列表
                for (String liableUserId : handleLiableUserIdList) {
                    // 负责人ID列表
                    liableUserIdList.add(Long.valueOf(liableUserId));
                }
                // 负责人ID列表
                projectDto.setLiableUserIdList(liableUserIdList);
            }
        }
        if (!(min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY)){
            for (ProjectDto projectDto : projectDtoList) {
                projectDto.setFlag(true);
            }
            return projectDtoList;
        }
        for (ProjectDto projectDto : projectDtoList) {
            for (Long project : projectIdList) {
                //当前用户所负责的项目ID
                //如果当前用户负责的项目ID在这个集合中,就给那个项目打一个标识
                if (projectDto.getId().equals(project)) {
                    projectDto.setFlag(true);
                    break;
                } else {
                    projectDto.setFlag(false);
                }
            }
        }
        return projectDtoList;
    }
    @Override
    @Transactional
    public ProjectDto findById(Long id) {
        Project project = projectRepository.findById(id).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", id);
        return projectMapper.toDto(project);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectDto create(Project resources) {
        return projectMapper.toDto(projectRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Project resources) {
        Project project = projectRepository.findById(resources.getId()).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", resources.getId());
        project.copy(resources);
        projectRepository.save(project);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            // 根据项目ID查询任务日报
            List<TaskDaliy> taskDaliyList = taskDaliyRepository.findByProjectId(id);
            // 判断任务日报数量
            if (taskDaliyList.size() == 0) {
                projectRepository.deleteById(id);
                projectTaskRepository.deleteByProjectId(id);
                projectCostRepository.deleteByProjectId(id);
                projectProgressRepository.deleteByProjectId(id);
                projectPerformanceRepository.deleteByProjectId(id);
                projectPerformanceDetailRepository.deleteByProjectId(id);
                costRepository.deleteByProjectId(id);
                taskRepository.deleteByProjectId(id);
                taskUserRepository.deleteByProjectId(id);
                taskDaliyRepository.deleteByProjectId(id);
                contractProjectRepository.deleteByProjectId(id);
            } else {
                throw new BadRequestException("存在任务日报的项目无法删除!");
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProjectAdmit(Long[] ids) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUserId();
        // 查询用户角色
        List<RoleSmallDto> roleSet = roleService.findByUsersId(userId);
        Long min = roleSet.stream().mapToLong(RoleSmallDto::getLevel).min().getAsLong();
        for (Long id : ids) {
            // 查询项目
            Project project = projectRepository.findByIdUpdate(id);
            if (min == Constant.ROLE_LEVEL_SUPER) {
                project.setApproveStatus(Constant.APPROVE_STATUS_ACKNOWLEDGED);
            } else if (min == Constant.ROLE_LEVEL_GENERAL) {
                project.setApproveStatus(Constant.APPROVE_STATUS_MASTER_ACKNOWLEDGED);
            } else if (min == Constant.ROLE_LEVEL_MANAGER) {
                project.setApproveStatus(Constant.APPROVE_STATUS_LEADER_ACKNOWLEDGED);
            }
            // 更新项目
            update(project);
            // 已承认的项目,生成任务
            if (Constant.APPROVE_STATUS_ACKNOWLEDGED.equals(project.getProjectStatus())) {
                // 查询项目任务
                List<ProjectTask> projectTaskList = projectTaskRepository.findByProjectId(id);
                List<TaskMongo> taskMongoList = mongoTemplate.find(Query.query(new Criteria("projectId").is(id)), TaskMongo.class);
                if (taskMongoList.size() == 0) {
                    // 从项目任务拷贝到任务中
                    for (int i = 0; i < projectTaskList.size(); i++) {
                        TaskMongo taskMongo = new TaskMongo();
                        taskMongo.setProjectId(projectTaskList.get(i).getProjectId());
                        taskMongo.setName(projectTaskList.get(i).getName());
//                        // TODO
//                        taskMongo.setTagList(Arrays.asList(projectTaskList.get(i).getTaskClassification()));
                        if (projectTaskList.get(i).getDescription() != null) {
                            taskMongo.setDescription(projectTaskList.get(i).getDescription());
                        }
                        taskMongo.setPlanHours(projectTaskList.get(i).getPlanHours());
                        if (projectTaskList.get(i).getPlanWorkload() != null) {
                            taskMongo.setPlanWorkload(projectTaskList.get(i).getPlanWorkload());
                        }
                        if (projectTaskList.get(i).getPlanWorkloadUnit() != null) {
                            taskMongo.setPlanWorkloadUnit(projectTaskList.get(i).getPlanWorkloadUnit());
                        }
                        if (projectTaskList.get(i).getRemarks() != null) {
                            taskMongo.setDescription(projectTaskList.get(i).getRemarks());
                        }
//                    task.setPriority(Constant.PRIORITY_LOW);
                        // 绩效区分
                        taskMongo.setPerformanceType(projectTaskList.get(i).getPerformanceType());
                        // 未开始
                        taskMongo.setTaskStatus(Constant.TASK_STATUS_NOT_STARTED);
                        taskMongo.setPlanStartTime(projectTaskList.get(i).getPlanStartTime());
                        taskMongo.setPlanEndTime(projectTaskList.get(i).getPlanEndTime());
                        mongoTemplate.insert(taskMongo);
                    }
                }
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProjectDisavow(Long[] ids) {
        for (Long id : ids) {
            // 查询项目
            Project project = projectRepository.findByIdUpdate(id);
            project.setApproveStatus(Constant.APPROVE_STATUS_UNRECOGNIZED);
            // 更新项目
            update(project);
        }
    }
    @Override
    public void download(List<ProjectDto> all, HttpServletResponse response) throws IOException { // TODO
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectDto project : all) {
            String projectTypeName = project.getProjectTypeId() != null ? projectTypeRepository.findById(project.getProjectTypeId()).orElseGet(ProjectType::new).getName() : "";
            String projectDistinguish = project.getProjectDistinguish() != null ? dictDetailRepository.findByDictNameAndValue(Constant.PROJECT_DISTINGUISH, project.getProjectDistinguish()).getLabel() : "";
            String projectStatus = project.getProjectStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.PROJECT_STATUS, project.getProjectStatus()).getLabel() : "";
            String approveStatus = project.getApproveStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.APPROVE_STATUS, project.getApproveStatus()).getLabel() : "";
            String unitCurrency = project.getUnitCurrency() != null ? dictDetailRepository.findByDictNameAndValue(Constant.STANDARD_UNIT_CURRENCY, project.getUnitCurrency()).getLabel() : "";
            // 负责人名称
            String liableUserName = null;
            if (project.getLiableUserId() != null && !"".equals(project.getLiableUserId())) {
                // 处理后负责人ID
                String handleLiableUserId = project.getLiableUserId().replace("-", "");
                // 处理后负责人ID列表
                String[] handleLiableUserIdList = handleLiableUserId.split(",");
                // 循环处理后负责人ID列表
                for (String liableUserId : handleLiableUserIdList) {
                    // 根据负责人ID查询用户信息
                    User user = userRepository.findById(Long.valueOf(liableUserId)).orElseGet(User::new);
                    // 判断负责人名称
                    liableUserName = liableUserName == null ? user.getNickName() : liableUserName + "," + user.getNickName();
                }
            }
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", project.getName());
            map.put("项目类型", projectTypeName);
            map.put("项目区分:", projectDistinguish);
            map.put("需求说明", project.getRequirement());
            map.put("单价币种", unitCurrency);
            // TODO
//            map.put("单价金额", project.getUnitPrice());
//            map.put("报价金额", project.getTotalPrice());
            map.put("责任人", liableUserName);
            map.put("计划开始日期", project.getPlanStartDate());
            map.put("计划结束日期", project.getPlanEndDate());
            map.put("项目状态", projectStatus);
            map.put("批准状态", approveStatus);
            map.put("备注", project.getRemarks());
            map.put("创建者", project.getCreateBy());
            map.put("创建时间", project.getCreateTime());
            map.put("更新者", project.getUpdateBy());
            map.put("更新时间", project.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public List<ProjectDto> queryPartakeAll(ProjectQueryCriteria criteria) {
        // 根据用户ID查询项目ID
        List<Long> partakeProjectIds = taskUserRepository.findProjectIdByUserId(criteria.getTaskUserId());
        // 判断长度
        if (partakeProjectIds.size() == 0) {
            return new ArrayList<>();
        }
        // 项目检索条件
        criteria.setIdInList(partakeProjectIds);
        criteria.setProjectStatusNotEqual(Constant.PROJECT_STATUS_COMPLETED);
        return projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    @Override
    public List<Map<String, Object>> queryProjectCost(ProjectQueryCriteria criteria) throws ParseException {
        // 判断入参完整性
        if (criteria.getTargetYear() == null || "".equals(criteria.getTargetYear())) {
            return null;
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        Sort sort = Sort.by(Sort.Order.desc("createTime"));
        ProjectQueryCriteria criteria1 = new ProjectQueryCriteria();
//        criteria1.setProjectDistinguish("project_distinguish_product"); // TODO
        criteria1.setProjectStatusNotEqual(Constant.PROJECT_STATUS_COMPLETED);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Project> projectList = projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria1, criteriaBuilder), sort);
        for (Project project : projectList) {
            Query query = new Query(
                    Criteria.where("projectId").is(project.getId())
                            .and("planStartTime").gte(sdf.parse(criteria.getTargetYear() + "-01-01"))
            );
            List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
            Map<String, Object> result = new HashMap<>();
            result.put("projectName", project.getName());
            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(new Query(Criteria.where("task").in(taskMongoList)), TaskUserMongo.class);
            result.put("taskHours", taskUserMongoList.stream().mapToDouble(TaskUserMongo::getTaskHours).sum());
            result.put("consumedHours", taskUserMongoList.stream().mapToDouble(TaskUserMongo::getCostHours).sum());
            if (!result.get("consumedHours").equals(0.0D)) {
                resultList.add(result);
            }
        }
        return resultList;
    }
    @Override
    public List<Map<String, Object>> querySubgroupTurnover(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getTargetYear() == null || "".equals(criteria.getTargetYear())) {
            return null;
        }
        // 根据字典名称查询
        List<DictDetail> dictDetailList = dictDetailRepository.findByDictName(Constant.PROJECT_DISTINGUISH);
        // 查询汇率列表
        List<SysExchangeRateDto> sysExchangeRateDtoList = sysExchangeRateService.queryAll(new SysExchangeRateQueryCriteria());
        // 根据目标年份查询分组营业额
        List<ProjectSummary> projectSummaryList = projectRepository.findSubgroupTurnoverByTargetYear(criteria.getTargetYear());
        // 根据目标年份查询分组目标金额
        SysGoalSettingQueryCriteria sysGoalSettingQueryCriteria = new SysGoalSettingQueryCriteria();
        sysGoalSettingQueryCriteria.setTargetYear(criteria.getTargetYear());
        List<SysGoalSettingDto> sysGoalSettingDtoList = sysGoalSettingService.queryAll(sysGoalSettingQueryCriteria);
        // 返回列表
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 循环项目区分
        for (int i = 0; i < dictDetailList.size(); i++) {
            // 返回集合
            Map<String, Object> returnMap = new HashMap<>();
            // 当前项目区分
            DictDetail dictDetail = dictDetailList.get(i);
            // 返回集合
            returnMap.put("projectDistinguish", dictDetail.getLabel());
            // 营业额
            BigDecimal contractPrice = new BigDecimal(0);
            // 循环分组营业额
            for (int j = 0; j < projectSummaryList.size(); j++) {
                // 当前项目区分
                ProjectSummary projectSummary = projectSummaryList.get(j);
                // 判断与项目区分是否一致
                if (dictDetail.getValue().equals(projectSummary.getProjectDistinguish())) {
                    // 当前汇率列表
                    List<SysExchangeRateDto> currentSysExchangeRateDtoList = sysExchangeRateDtoList.stream().filter(item -> item.getUnitCurrency().equals(projectSummary.getUnitCurrency())).collect(Collectors.toList());
                    // 判断当前汇率列表长度
                    if (currentSysExchangeRateDtoList.size() == 1) {
                        // 营业额
                        contractPrice = contractPrice.add(projectSummary.getContractPrice().multiply(currentSysExchangeRateDtoList.get(0).getExchangeRate()));
                    }
                }
                // 判断循环是否结束
                if (j == projectSummaryList.size() - 1) {
                    // 返回集合
                    returnMap.put("contractPrice", contractPrice);
                }
            }
            // 循环分组目标金额
            for (int j = 0; j < sysGoalSettingDtoList.size(); j++) {
                // 判断与项目区分是否一致
                if (dictDetail.getValue().equals(sysGoalSettingDtoList.get(j).getProjectDistinguish())) {
                    // 返回集合
                    returnMap.put("targetAmount", sysGoalSettingDtoList.get(j).getTargetAmount());
                    break;
                }
                // 判断循环是否结束
                if (j == sysGoalSettingDtoList.size() - 1) {
                    // 返回集合
                    returnMap.put("targetAmount", new BigDecimal(0));
                }
            }
            // 返回列表
            returnList.add(returnMap);
        }
        return returnList;
    }
    @Override
    public List<Map<String, Object>> querySubgroupWorkingHours(ProjectQueryCriteria criteria) {
        // 根据字典名称查询
        List<DictDetail> dictDetailList = dictDetailRepository.findByDictName(Constant.PROJECT_DISTINGUISH);
        // 查询项目列表
        List<Project> projectList = projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<Long> projectIdList = projectList.stream().map(Project::getId).collect(Collectors.toList());
        // 查询任务列表
        List<TaskInterface> taskInterfaceList = taskRepository.findSubgroupWorkingHoursByProjectId(projectIdList);
        // 返回列表
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 循环项目区分
        for (int i = 0; i < dictDetailList.size(); i++) {
            // 已分配工时
            Double divideHours = 0D;
            // 未完成工时
            Double incompleteHours = 0D;
            // 返回集合
            Map<String, Object> returnMap = new HashMap<>();
            // 当前项目区分
            DictDetail dictDetail = dictDetailList.get(i);
            // 返回集合
            returnMap.put("projectDistinguish", dictDetail.getLabel());
            // 当前任务列表
            List<TaskInterface> currentTaskInterfaceList = taskInterfaceList.stream().filter(item -> item.getProjectDistinguish().equals(dictDetail.getValue())).collect(Collectors.toList());
            // 循环当前任务列表
            for (int j = 0; j < currentTaskInterfaceList.size(); j++) {
                // 当前任务
                TaskInterface currentTaskInterface = currentTaskInterfaceList.get(j);
                Task task = taskRepository.findById(currentTaskInterface.getTaskId()).orElseGet(Task::new);
                // 当前任务二次处理
                TaskDto taskDto = taskMapper.toDto(task);
                taskDto = taskService.customHandleMini(taskDto);
                // 已分配工时
                divideHours += taskDto.getDivideHours();
                // 未完成工时
                incompleteHours += (taskDto.getDivideHours() - taskDto.getCompletedHours());
            }
            // 返回集合
            returnMap.put("divideHours", DoubleUtil.maximumDigitLimit(divideHours, 2));
            returnMap.put("incompleteHours", DoubleUtil.maximumDigitLimit(incompleteHours, 2));
            // 返回列表
            returnList.add(returnMap);
        }
        return returnList;
    }
    @Override
    public Map<String, Object> queryProjectWorkingHours(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getId() == null) {
            return null;
        }
        // 根据项目ID查询项目
        ProjectDto projectDto = projectMapper.toDto(projectRepository.findById(criteria.getId()).orElseGet(Project::new));
        // 项目二次处理
        projectDto = customHandle(projectDto);
        // 返回集合
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("divideHours", projectDto.getDivideTaskTime());
        returnMap.put("incompleteHours", projectDto.getIncompleteTaskTime());
        return returnMap;
    }
    @Override
    public List<Map<String, Object>> queryTypeContractPrice(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getProjectDistinguish() == null || "".equals(criteria.getProjectDistinguish()) || criteria.getTargetYear() == null || "".equals(criteria.getTargetYear())) {
            return null;
        }
        // 查询汇率列表
        List<SysExchangeRateDto> sysExchangeRateDtoList = sysExchangeRateService.queryAll(new SysExchangeRateQueryCriteria());
        // 根据项目区分、目标年份查询类型营业额
        List<ProjectSummary> projectSummaryList = projectRepository.findTypeContractPriceByProjectDistinguishAndTargetYear(criteria.getProjectDistinguish(), criteria.getTargetYear());
        // 项目类型列表
        List<String> projectTypeNameList = projectSummaryList.stream().map(ProjectSummary::getProjectTypeName).distinct().collect(Collectors.toList());
        // 返回列表
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 循环项目类型列表
        for (int i = 0; i < projectTypeNameList.size(); i++) {
            // 项目类型
            String projectTypeName = projectTypeNameList.get(i);
            // 返回集合
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("name", projectTypeName);
            // 当前项目类型营业额列表
            List<ProjectSummary> currentProjectSummaryList = projectSummaryList.stream().filter(item -> item.getProjectTypeName().equals(projectTypeName)).collect(Collectors.toList());
            // 营业额
            BigDecimal contractPrice = new BigDecimal(0);
            // 循环当前项目类型营业额列表
            for (int j = 0; j < currentProjectSummaryList.size(); j++) {
                // 当前项目类型营业额
                ProjectSummary currentProjectSummary = currentProjectSummaryList.get(j);
                // 当前汇率列表
                List<SysExchangeRateDto> currentSysExchangeRateDtoList = sysExchangeRateDtoList.stream().filter(item -> item.getUnitCurrency().equals(currentProjectSummary.getUnitCurrency())).collect(Collectors.toList());
                // 判断当前汇率列表长度
                if (currentSysExchangeRateDtoList.size() == 1) {
                    // 营业额
                    contractPrice = contractPrice.add(currentProjectSummary.getContractPrice().multiply(currentSysExchangeRateDtoList.get(0).getExchangeRate()));
                }
            }
            returnMap.put("value", contractPrice);
            // 返回列表
            returnList.add(returnMap);
        }
        return returnList;
    }
    @Override
    public List<Map<String, Object>> queryTypeWorkingHours(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getProjectDistinguish() == null || "".equals(criteria.getProjectDistinguish()) || criteria.getTargetYear() == null || "".equals(criteria.getTargetYear())) {
            return null;
        }
        // 根据项目区分、目标年份查询项目
        List<Project> projectList = projectRepository.findProjectByProjectDistinguishAndTargetYear(criteria.getProjectDistinguish(), criteria.getTargetYear());
        // 查询项目类型列表
        ProjectTypeQueryCriteria projectTypeQueryCriteria = new ProjectTypeQueryCriteria();
        List<ProjectType> projectTypeList = projectTypeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, projectTypeQueryCriteria, criteriaBuilder));
        // 返回列表
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 循环项目类型列表
        for (int i = 0; i < projectTypeList.size(); i++) {
            // 项目类型
            ProjectType projectType = projectTypeList.get(i);
            // 处理后项目列表
            List<Project> handleProjectList = projectList.stream().filter(item -> item.getProjectTypeId() == projectType.getId()).collect(Collectors.toList());
            // 判断处理后项目列表长度
            if (handleProjectList.size() != 0) {
                // 处理后项目ID列表
                List<Long> handleProjectIdList = handleProjectList.stream().map(Project::getId).collect(Collectors.toList());
                // 根据项目ID查询总工时
                Double sumWorkingHours = taskRepository.sumWorkingHoursByProjectId(handleProjectIdList);
                // 返回集合
                Map<String, Object> returnMap = new HashMap<>();
                returnMap.put("name", projectType.getName());
                returnMap.put("value", sumWorkingHours);
                // 返回列表
                returnList.add(returnMap);
            }
        }
        return returnList;
    }
    @Override
    public List<ProjectDto> querySubgroupTopHours(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getProjectDistinguish() == null || "".equals(criteria.getProjectDistinguish())) {
            return null;
        }
        // 查询项目列表
        List<ProjectDto> projectDtoList = projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        // 循环项目列表
        for (int i = 0; i < projectDtoList.size(); i++) {
            // 当前项目
            ProjectDto projectDto = projectDtoList.get(i);
            // 项目二次处理
            projectDto = customHandle(projectDto);
        }
        // 按照任务合计(未完成)进行降序排列
        projectDtoList = projectDtoList.stream().sorted(Comparator.comparing(ProjectDto::getIncompleteTaskTime).reversed()).collect(Collectors.toList());
        return projectDtoList;
    }
    @Override
    //@Cacheable(cacheNames = "project",key = "{#p0}")
    public List<ProjectDto> queryRelevantOfDaily(Long userId) {
        List<TaskUserMongo> taskUserMongos = mongoTemplate.find(Query.query(new Criteria("userId").is(userId)
                .and("taskStatus").in(Constant.TASK_STATUS_NOT_STARTED, Constant.TASK_STATUS_IN_HAND, Constant.TASK_STATUS_TEST, Constant.TASK_STATUS_UNRECOGNIZED)), TaskUserMongo.class);
        List<Long> projectIds = taskUserMongos.stream().map(taskUserMongo -> taskUserMongo.getTask().getProjectId()).distinct().collect(Collectors.toList());
        List<Project> projectList = projectRepository.findByProjectStatusInAndIdIn(Arrays.asList(Constant.PROJECT_STATUS_NOT_STARTED, Constant.PROJECT_STATUS_UNDER_WAY), projectIds);
        return projectList.stream().map(project -> {
            ProjectDto projectDto = new ProjectDto();
            projectDto.setId(project.getId());
            projectDto.setName(project.getName());
            return projectDto;
        }).collect(Collectors.toList());
    }
/*
 *  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.project.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.contract.repository.ContractProjectRepository;
import me.zhengjie.modules.cost.repository.CostRepository;
import me.zhengjie.modules.project.domain.*;
import me.zhengjie.modules.project.repository.*;
import me.zhengjie.modules.project.service.ProjectCostService;
import me.zhengjie.modules.project.service.ProjectService;
import me.zhengjie.modules.project.service.dto.ProjectDto;
import me.zhengjie.modules.project.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.project.service.dto.ProjectTypeQueryCriteria;
import me.zhengjie.modules.project.service.mapstruct.ProjectMapper;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.SysExchangeRateService;
import me.zhengjie.modules.system.service.SysGoalSettingService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.task.domain.*;
import me.zhengjie.modules.task.repository.TaskDaliyRepository;
import me.zhengjie.modules.task.repository.TaskRepository;
import me.zhengjie.modules.task.repository.TaskUserRepository;
import me.zhengjie.modules.task.service.TaskService;
import me.zhengjie.modules.task.service.dto.TaskDto;
import me.zhengjie.modules.task.service.dto.TaskUserTotalDetailMongoDto;
import me.zhengjie.modules.task.service.mapstruct.TaskMapper;
import me.zhengjie.utils.*;
import me.zhengjie.utils.enums.DataScopeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
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.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
 * @author HuaZhe
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-12-15
 **/
@Service
@RequiredArgsConstructor
public class ProjectServiceImpl implements ProjectService { // TODO redis化
    private final ProjectRepository projectRepository;
    private final ProjectMapper projectMapper;
    private final ProjectTypeRepository projectTypeRepository;
    private final UserRepository userRepository;
    private final DictDetailRepository dictDetailRepository;
    private final ProjectTaskRepository projectTaskRepository;
    private final RoleService roleService;
    private final TaskUserRepository taskUserRepository;
    private final ProjectCostRepository projectCostRepository;
    private final ProjectCostOtherRepository projectCostOtherRepository;
    private final TaskRepository taskRepository;
    private final TaskDaliyRepository taskDaliyRepository;
    private final ProjectCostService projectCostService;
    private final ProjectProgressRepository projectProgressRepository;
    private final ProjectPerformanceRepository projectPerformanceRepository;
    private final ProjectPerformanceDetailRepository projectPerformanceDetailRepository;
    private final CostRepository costRepository;
    private final ContractProjectRepository contractProjectRepository;
    private final SysGoalSettingService sysGoalSettingService;
    @Autowired
    private TaskService taskService;
    private final TaskMapper taskMapper;
    private final SysExchangeRateService sysExchangeRateService;
    private final MongoTemplate mongoTemplate;
    @Override
    public Map<String, Object> queryAll(ProjectQueryCriteria criteria, Pageable pageable) {
        if (criteria.getLiableUserId() == null) {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            // 查询用户角色
            List<RoleSmallDto> roleSet = roleService.findByUsersId(userId);
            if (roleSet.stream().anyMatch(role -> DataScopeEnum.find(role.getDataScope()) == DataScopeEnum.THIS_LEVEL)) {
                // 根据用户ID查询负责的项目ID
                List<Long> projectIdList = projectRepository.findIdByLiableUserId(userId);
                // 根据用户ID查询参与的项目ID
                List<Long> taskUserProjectIdList = projectCostRepository.findProjectIdByUserId(userId);
                // 检索条件
                List<Long> totalProjectIdList = Stream.of(taskUserProjectIdList, projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
                if (totalProjectIdList.size() == 0) {
                    return PageUtil.toPage(Collections.emptyList(), 0);
                }
                criteria.setLiableUserId("-" + userId + "-");
            }
        }
        Page<Project> page = projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        // 将实体类转换为DTO(重写)
        Function<Project, ProjectDto> func = new Function<Project, ProjectDto>() {
            @Override
            public ProjectDto apply(Project project) {
                // 将实体类转换成DTO
                ProjectDto projectDto = projectMapper.toDto(project);
                // 根据项目类型ID查询项目类型信息
                ProjectType projectType = projectTypeRepository.findById(projectDto.getProjectTypeId()).orElseGet(ProjectType::new);
                ValidationUtil.isNull(project.getId(), "ProjectType", "id", projectDto.getProjectTypeId());
                // 项目类型名称
                projectDto.setProjectTypeName(projectType.getName());
                // 判断是否有负责人
                if (projectDto.getLiableUserId() != null) {
                    // 负责人名称
                    String liableUserName = null;
                    // 负责人ID列表
                    List<Long> liableUserIdList = new ArrayList<>();
                    // 负责人ID
                    String handleLiableUserId = projectDto.getLiableUserId().replace("-", "");
                    // 负责人ID列表
                    String[] handleLiableUserIdList = handleLiableUserId.split(",");
                    // 循环负责人ID列表
                    for (String liableUserId : handleLiableUserIdList) {
                        // 负责人ID列表
                        liableUserIdList.add(Long.valueOf(liableUserId));
                        // 根据负责人ID查询用户信息
                        User user = userRepository.findById(Long.valueOf(liableUserId)).orElseGet(User::new);
                        ValidationUtil.isNull(project.getId(), "User", "id", projectDto.getLiableUserId());
                        // 判断负责人名称
                        liableUserName = liableUserName == null ? user.getNickName() : liableUserName + "," + user.getNickName();
                    }
                    // 负责人ID列表
                    projectDto.setLiableUserIdList(liableUserIdList);
                    // 负责人名称
                    projectDto.setLiableUserName(liableUserName);
                }
                ProjectTaskSummary projectTaskSummary = projectTaskRepository.findSummaryByProjectId(project.getId());
                projectDto.setTaskStartDate(projectTaskSummary.getTaskStartDate());
                projectDto.setTaskEndDate(projectTaskSummary.getTaskEndDate());
                projectDto.setTotalTaskTime(projectTaskSummary.getTotalTaskTime());
                ProjectCostSummary projectCostSummary = projectCostRepository.findSummaryByProjectId(project.getId());
                projectDto.setTotalLaborCost(projectCostSummary.getTotalLaborCost());
                // 其他项目成本
                List<ProjectCostOther> projectCostOtherList = projectCostOtherRepository.findByProjectId(project.getId());
                projectDto.setTotalOtherCost(projectCostOtherList.stream().map(ProjectCostOther::getProjectCost).reduce(BigDecimal.ZERO, BigDecimal::add));
                // 查询项目的任务数据
                TaskInterface taskInterface = taskRepository.collectByProjectId(project.getId());
                projectDto.setActualTaskTime(taskInterface.getPlanHours());
                // 根据日期和项目ID取得日报信息
                Query query = new Query(Criteria.where("projectId").is(project.getId()));
                List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
                Aggregation customerAgg = Aggregation.newAggregation(
                        Aggregation.match(Criteria.where("task").in(taskMongoList)),
                        Aggregation.project("userId", "taskHours", "costHours"),
                        Aggregation.group("userId").sum("taskHours").as("taskHours").sum("costHours").as("costHours")
                );
                AggregationResults<Map> aggregate = mongoTemplate.aggregate(customerAgg, TaskUserMongo.class, Map.class);
                BigDecimal actualCost =aggregate.getMappedResults().stream().filter(data -> data.get("_id") != null).map(data -> {
                    BigDecimal moneyTotalCost = projectCostService.calcUserCostByHours(Long.parseLong(String.valueOf(data.get("_id"))), Double.valueOf(String.valueOf(data.get("costHours"))));
                    return moneyTotalCost;
                }).reduce(BigDecimal.ZERO, BigDecimal::add);
                // 实际消耗成本
                projectDto.setActualLaborCost(actualCost);
                // 项目二次处理
                projectDto = customHandle(projectDto);
                // 返回处理好的Dto
                return projectDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<ProjectDto> queryAll2(ProjectQueryCriteria criteria) {
        return projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    private ProjectDto customHandle(ProjectDto projectDto) {
        // 任务合计(已分配)
        Double divideTaskTime = 0D;
        // 任务合计(已完成)
        Double completedTaskTime = 0D;
        // 根据项目ID查询任务列表
        Criteria criteria = new Criteria();
        criteria.and("projectId").is(projectDto.getId());
        Query query = new Query(criteria);
        List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
        Criteria criteriaAggr = Criteria.where("task").in(taskMongoList);
        Aggregation customerAgg = Aggregation.newAggregation(
                Aggregation.match(criteriaAggr),
                Aggregation.project("taskStatus", "taskHours"),
                Aggregation.group("taskStatus").count().as("taskStatusCnt").sum("taskHours").as("taskHours")
        );
        AggregationResults<TaskUserTotalDetailMongoDto> taskUserMongoList = mongoTemplate.aggregate(customerAgg, TaskUserMongo.class, TaskUserTotalDetailMongoDto.class);
        for (TaskUserTotalDetailMongoDto taskUserTotalDetailMongoDto : taskUserMongoList.getMappedResults()) {
            if (Constant.TASK_STATUS_COMPLETED.equals(taskUserTotalDetailMongoDto.get_id())) {
                completedTaskTime += taskUserTotalDetailMongoDto.getTaskHours();
            }
            divideTaskTime += taskUserTotalDetailMongoDto.getTaskHours();
        }
        // 任务合计(已分配)
        projectDto.setDivideTaskTime(DoubleUtil.maximumDigitLimit(divideTaskTime, 2));
        // 任务合计(已完成)
        projectDto.setCompletedTaskTime(DoubleUtil.maximumDigitLimit(completedTaskTime, 2));
        // 任务合计(未完成)
        projectDto.setIncompleteTaskTime(DoubleUtil.maximumDigitLimit(divideTaskTime - completedTaskTime, 2));
        return projectDto;
    }
    @Override
    public List<ProjectDto> queryAll(ProjectQueryCriteria criteria) {
        if (criteria.getLiableUserId() == null) {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            // 查询用户角色
            List<RoleSmallDto> roleSet = roleService.findByUsersId(userId);
            if (roleSet.stream().anyMatch(role -> DataScopeEnum.find(role.getDataScope()) == DataScopeEnum.THIS_LEVEL)) {
                criteria.setLiableUserId("-" + userId + "-");
            }
        }
        return projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    @Override
    public List<ProjectDto> queryRelevant(ProjectQueryCriteria criteria) {
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        List<Long> projectIdList = new ArrayList<>();
        // 判断角色等级
        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
            // 根据用户ID查询参与的项目ID
            //List<Long> taskUserProjectIdList = taskDaliyRepository.findProjectIdByUserId(SecurityUtils.getCurrentUserId());
            //如果当前用户属于一个任务,那么他也可以看见当前这个任务的项目
            Query query = Query.query(Criteria.where("containUserList").is(SecurityUtils.getCurrentUserId()));
            List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
            ArrayList<Long> projectList = new ArrayList<>();
            for (TaskMongo taskMongo : taskMongoList) {
                projectList.add(taskMongo.getProjectId());
            }
            // 根据用户ID查询负责的项目ID
            projectIdList = projectRepository.findIdByLiableUserId(SecurityUtils.getCurrentUserId());
            // 检索条件
            List<Long> totalProjectIdList = Stream.of(projectList, projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
            if (totalProjectIdList.size() == 0) {
                return Collections.emptyList();
            }
            criteria.setIdInList(totalProjectIdList);
        }
        // 项目列表
        List<ProjectDto> projectDtoList = projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        // 循环项目列表
        for (int i = 0; i < projectDtoList.size(); i++) {
            // 项目
            ProjectDto projectDto = projectDtoList.get(i);
            if (projectDto.getLiableUserId() != null && !"".equals(projectDto.getLiableUserId())) {
                // 负责人ID列表
                List<Long> liableUserIdList = new ArrayList<>();
                // 负责人ID
                String handleLiableUserId = projectDto.getLiableUserId().replace("-", "");
                // 负责人ID列表
                String[] handleLiableUserIdList = handleLiableUserId.split(",");
                // 循环负责人ID列表
                for (String liableUserId : handleLiableUserIdList) {
                    // 负责人ID列表
                    liableUserIdList.add(Long.valueOf(liableUserId));
                }
                // 负责人ID列表
                projectDto.setLiableUserIdList(liableUserIdList);
            }
        }
        if (!(min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY)){
            for (ProjectDto projectDto : projectDtoList) {
                projectDto.setFlag(true);
            }
            return projectDtoList;
        }
        for (ProjectDto projectDto : projectDtoList) {
            for (Long project : projectIdList) {
                //当前用户所负责的项目ID
                //如果当前用户负责的项目ID在这个集合中,就给那个项目打一个标识
                if (projectDto.getId().equals(project)) {
                    projectDto.setFlag(true);
                    break;
                } else {
                    projectDto.setFlag(false);
                }
            }
        }
        return projectDtoList;
    }
    @Override
    @Transactional
    public ProjectDto findById(Long id) {
        Project project = projectRepository.findById(id).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", id);
        return projectMapper.toDto(project);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectDto create(Project resources) {
        return projectMapper.toDto(projectRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Project resources) {
        Project project = projectRepository.findById(resources.getId()).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", resources.getId());
        project.copy(resources);
        projectRepository.save(project);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            // 根据项目ID查询任务日报
            List<TaskDaliy> taskDaliyList = taskDaliyRepository.findByProjectId(id);
            // 判断任务日报数量
            if (taskDaliyList.size() == 0) {
                projectRepository.deleteById(id);
                projectTaskRepository.deleteByProjectId(id);
                projectCostRepository.deleteByProjectId(id);
                projectProgressRepository.deleteByProjectId(id);
                projectPerformanceRepository.deleteByProjectId(id);
                projectPerformanceDetailRepository.deleteByProjectId(id);
                costRepository.deleteByProjectId(id);
                taskRepository.deleteByProjectId(id);
                taskUserRepository.deleteByProjectId(id);
                taskDaliyRepository.deleteByProjectId(id);
                contractProjectRepository.deleteByProjectId(id);
            } else {
                throw new BadRequestException("存在任务日报的项目无法删除!");
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProjectAdmit(Long[] ids) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUserId();
        // 查询用户角色
        List<RoleSmallDto> roleSet = roleService.findByUsersId(userId);
        Long min = roleSet.stream().mapToLong(RoleSmallDto::getLevel).min().getAsLong();
        for (Long id : ids) {
            // 查询项目
            Project project = projectRepository.findByIdUpdate(id);
            if (min == Constant.ROLE_LEVEL_SUPER) {
                project.setApproveStatus(Constant.APPROVE_STATUS_ACKNOWLEDGED);
            } else if (min == Constant.ROLE_LEVEL_GENERAL) {
                project.setApproveStatus(Constant.APPROVE_STATUS_MASTER_ACKNOWLEDGED);
            } else if (min == Constant.ROLE_LEVEL_MANAGER) {
                project.setApproveStatus(Constant.APPROVE_STATUS_LEADER_ACKNOWLEDGED);
            }
            // 更新项目
            update(project);
            // 已承认的项目,生成任务
            if (Constant.APPROVE_STATUS_ACKNOWLEDGED.equals(project.getProjectStatus())) {
                // 查询项目任务
                List<ProjectTask> projectTaskList = projectTaskRepository.findByProjectId(id);
                List<TaskMongo> taskMongoList = mongoTemplate.find(Query.query(new Criteria("projectId").is(id)), TaskMongo.class);
                if (taskMongoList.size() == 0) {
                    // 从项目任务拷贝到任务中
                    for (int i = 0; i < projectTaskList.size(); i++) {
                        TaskMongo taskMongo = new TaskMongo();
                        taskMongo.setProjectId(projectTaskList.get(i).getProjectId());
                        taskMongo.setName(projectTaskList.get(i).getName());
//                        // TODO
//                        taskMongo.setTagList(Arrays.asList(projectTaskList.get(i).getTaskClassification()));
                        if (projectTaskList.get(i).getDescription() != null) {
                            taskMongo.setDescription(projectTaskList.get(i).getDescription());
                        }
                        taskMongo.setPlanHours(projectTaskList.get(i).getPlanHours());
                        if (projectTaskList.get(i).getPlanWorkload() != null) {
                            taskMongo.setPlanWorkload(projectTaskList.get(i).getPlanWorkload());
                        }
                        if (projectTaskList.get(i).getPlanWorkloadUnit() != null) {
                            taskMongo.setPlanWorkloadUnit(projectTaskList.get(i).getPlanWorkloadUnit());
                        }
                        if (projectTaskList.get(i).getRemarks() != null) {
                            taskMongo.setDescription(projectTaskList.get(i).getRemarks());
                        }
//                    task.setPriority(Constant.PRIORITY_LOW);
                        // 绩效区分
                        taskMongo.setPerformanceType(projectTaskList.get(i).getPerformanceType());
                        // 未开始
                        taskMongo.setTaskStatus(Constant.TASK_STATUS_NOT_STARTED);
                        taskMongo.setPlanStartTime(projectTaskList.get(i).getPlanStartTime());
                        taskMongo.setPlanEndTime(projectTaskList.get(i).getPlanEndTime());
                        mongoTemplate.insert(taskMongo);
                    }
                }
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProjectDisavow(Long[] ids) {
        for (Long id : ids) {
            // 查询项目
            Project project = projectRepository.findByIdUpdate(id);
            project.setApproveStatus(Constant.APPROVE_STATUS_UNRECOGNIZED);
            // 更新项目
            update(project);
        }
    }
    @Override
    public void download(List<ProjectDto> all, HttpServletResponse response) throws IOException { // TODO
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectDto project : all) {
            String projectTypeName = project.getProjectTypeId() != null ? projectTypeRepository.findById(project.getProjectTypeId()).orElseGet(ProjectType::new).getName() : "";
            String projectDistinguish = project.getProjectDistinguish() != null ? dictDetailRepository.findByDictNameAndValue(Constant.PROJECT_DISTINGUISH, project.getProjectDistinguish()).getLabel() : "";
            String projectStatus = project.getProjectStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.PROJECT_STATUS, project.getProjectStatus()).getLabel() : "";
            String approveStatus = project.getApproveStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.APPROVE_STATUS, project.getApproveStatus()).getLabel() : "";
            String unitCurrency = project.getUnitCurrency() != null ? dictDetailRepository.findByDictNameAndValue(Constant.STANDARD_UNIT_CURRENCY, project.getUnitCurrency()).getLabel() : "";
            // 负责人名称
            String liableUserName = null;
            if (project.getLiableUserId() != null && !"".equals(project.getLiableUserId())) {
                // 处理后负责人ID
                String handleLiableUserId = project.getLiableUserId().replace("-", "");
                // 处理后负责人ID列表
                String[] handleLiableUserIdList = handleLiableUserId.split(",");
                // 循环处理后负责人ID列表
                for (String liableUserId : handleLiableUserIdList) {
                    // 根据负责人ID查询用户信息
                    User user = userRepository.findById(Long.valueOf(liableUserId)).orElseGet(User::new);
                    // 判断负责人名称
                    liableUserName = liableUserName == null ? user.getNickName() : liableUserName + "," + user.getNickName();
                }
            }
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", project.getName());
            map.put("项目类型", projectTypeName);
            map.put("项目区分:", projectDistinguish);
            map.put("需求说明", project.getRequirement());
            map.put("单价币种", unitCurrency);
            // TODO
//            map.put("单价金额", project.getUnitPrice());
//            map.put("报价金额", project.getTotalPrice());
            map.put("责任人", liableUserName);
            map.put("计划开始日期", project.getPlanStartDate());
            map.put("计划结束日期", project.getPlanEndDate());
            map.put("项目状态", projectStatus);
            map.put("批准状态", approveStatus);
            map.put("备注", project.getRemarks());
            map.put("创建者", project.getCreateBy());
            map.put("创建时间", project.getCreateTime());
            map.put("更新者", project.getUpdateBy());
            map.put("更新时间", project.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public List<ProjectDto> queryPartakeAll(ProjectQueryCriteria criteria) {
        // 根据用户ID查询项目ID
        List<Long> partakeProjectIds = taskUserRepository.findProjectIdByUserId(criteria.getTaskUserId());
        // 判断长度
        if (partakeProjectIds.size() == 0) {
            return new ArrayList<>();
        }
        // 项目检索条件
        criteria.setIdInList(partakeProjectIds);
        criteria.setProjectStatusNotEqual(Constant.PROJECT_STATUS_COMPLETED);
        return projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    @Override
    public List<Map<String, Object>> queryProjectCost(ProjectQueryCriteria criteria) throws ParseException {
        // 判断入参完整性
        if (criteria.getTargetYear() == null || "".equals(criteria.getTargetYear())) {
            return null;
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        Sort sort = Sort.by(Sort.Order.desc("createTime"));
        ProjectQueryCriteria criteria1 = new ProjectQueryCriteria();
//        criteria1.setProjectDistinguish("project_distinguish_product"); // TODO
        criteria1.setProjectStatusNotEqual(Constant.PROJECT_STATUS_COMPLETED);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Project> projectList = projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria1, criteriaBuilder), sort);
        for (Project project : projectList) {
            Query query = new Query(
                    Criteria.where("projectId").is(project.getId())
                            .and("planStartTime").gte(sdf.parse(criteria.getTargetYear() + "-01-01"))
            );
            List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
            Map<String, Object> result = new HashMap<>();
            result.put("projectName", project.getName());
            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(new Query(Criteria.where("task").in(taskMongoList)), TaskUserMongo.class);
            result.put("taskHours", taskUserMongoList.stream().mapToDouble(TaskUserMongo::getTaskHours).sum());
            result.put("consumedHours", taskUserMongoList.stream().mapToDouble(TaskUserMongo::getCostHours).sum());
            if (!result.get("consumedHours").equals(0.0D)) {
                resultList.add(result);
            }
        }
        return resultList;
    }
    @Override
    public List<Map<String, Object>> querySubgroupTurnover(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getTargetYear() == null || "".equals(criteria.getTargetYear())) {
            return null;
        }
        // 根据字典名称查询
        List<DictDetail> dictDetailList = dictDetailRepository.findByDictName(Constant.PROJECT_DISTINGUISH);
        // 查询汇率列表
        List<SysExchangeRateDto> sysExchangeRateDtoList = sysExchangeRateService.queryAll(new SysExchangeRateQueryCriteria());
        // 根据目标年份查询分组营业额
        List<ProjectSummary> projectSummaryList = projectRepository.findSubgroupTurnoverByTargetYear(criteria.getTargetYear());
        // 根据目标年份查询分组目标金额
        SysGoalSettingQueryCriteria sysGoalSettingQueryCriteria = new SysGoalSettingQueryCriteria();
        sysGoalSettingQueryCriteria.setTargetYear(criteria.getTargetYear());
        List<SysGoalSettingDto> sysGoalSettingDtoList = sysGoalSettingService.queryAll(sysGoalSettingQueryCriteria);
        // 返回列表
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 循环项目区分
        for (int i = 0; i < dictDetailList.size(); i++) {
            // 返回集合
            Map<String, Object> returnMap = new HashMap<>();
            // 当前项目区分
            DictDetail dictDetail = dictDetailList.get(i);
            // 返回集合
            returnMap.put("projectDistinguish", dictDetail.getLabel());
            // 营业额
            BigDecimal contractPrice = new BigDecimal(0);
            // 循环分组营业额
            for (int j = 0; j < projectSummaryList.size(); j++) {
                // 当前项目区分
                ProjectSummary projectSummary = projectSummaryList.get(j);
                // 判断与项目区分是否一致
                if (dictDetail.getValue().equals(projectSummary.getProjectDistinguish())) {
                    // 当前汇率列表
                    List<SysExchangeRateDto> currentSysExchangeRateDtoList = sysExchangeRateDtoList.stream().filter(item -> item.getUnitCurrency().equals(projectSummary.getUnitCurrency())).collect(Collectors.toList());
                    // 判断当前汇率列表长度
                    if (currentSysExchangeRateDtoList.size() == 1) {
                        // 营业额
                        contractPrice = contractPrice.add(projectSummary.getContractPrice().multiply(currentSysExchangeRateDtoList.get(0).getExchangeRate()));
                    }
                }
                // 判断循环是否结束
                if (j == projectSummaryList.size() - 1) {
                    // 返回集合
                    returnMap.put("contractPrice", contractPrice);
                }
            }
            // 循环分组目标金额
            for (int j = 0; j < sysGoalSettingDtoList.size(); j++) {
                // 判断与项目区分是否一致
                if (dictDetail.getValue().equals(sysGoalSettingDtoList.get(j).getProjectDistinguish())) {
                    // 返回集合
                    returnMap.put("targetAmount", sysGoalSettingDtoList.get(j).getTargetAmount());
                    break;
                }
                // 判断循环是否结束
                if (j == sysGoalSettingDtoList.size() - 1) {
                    // 返回集合
                    returnMap.put("targetAmount", new BigDecimal(0));
                }
            }
            // 返回列表
            returnList.add(returnMap);
        }
        return returnList;
    }
    @Override
    public List<Map<String, Object>> querySubgroupWorkingHours(ProjectQueryCriteria criteria) {
        // 根据字典名称查询
        List<DictDetail> dictDetailList = dictDetailRepository.findByDictName(Constant.PROJECT_DISTINGUISH);
        // 查询项目列表
        List<Project> projectList = projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<Long> projectIdList = projectList.stream().map(Project::getId).collect(Collectors.toList());
        // 查询任务列表
        List<TaskInterface> taskInterfaceList = taskRepository.findSubgroupWorkingHoursByProjectId(projectIdList);
        // 返回列表
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 循环项目区分
        for (int i = 0; i < dictDetailList.size(); i++) {
            // 已分配工时
            Double divideHours = 0D;
            // 未完成工时
            Double incompleteHours = 0D;
            // 返回集合
            Map<String, Object> returnMap = new HashMap<>();
            // 当前项目区分
            DictDetail dictDetail = dictDetailList.get(i);
            // 返回集合
            returnMap.put("projectDistinguish", dictDetail.getLabel());
            // 当前任务列表
            List<TaskInterface> currentTaskInterfaceList = taskInterfaceList.stream().filter(item -> item.getProjectDistinguish().equals(dictDetail.getValue())).collect(Collectors.toList());
            // 循环当前任务列表
            for (int j = 0; j < currentTaskInterfaceList.size(); j++) {
                // 当前任务
                TaskInterface currentTaskInterface = currentTaskInterfaceList.get(j);
                Task task = taskRepository.findById(currentTaskInterface.getTaskId()).orElseGet(Task::new);
                // 当前任务二次处理
                TaskDto taskDto = taskMapper.toDto(task);
                taskDto = taskService.customHandleMini(taskDto);
                // 已分配工时
                divideHours += taskDto.getDivideHours();
                // 未完成工时
                incompleteHours += (taskDto.getDivideHours() - taskDto.getCompletedHours());
            }
            // 返回集合
            returnMap.put("divideHours", DoubleUtil.maximumDigitLimit(divideHours, 2));
            returnMap.put("incompleteHours", DoubleUtil.maximumDigitLimit(incompleteHours, 2));
            // 返回列表
            returnList.add(returnMap);
        }
        return returnList;
    }
    @Override
    public Map<String, Object> queryProjectWorkingHours(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getId() == null) {
            return null;
        }
        // 根据项目ID查询项目
        ProjectDto projectDto = projectMapper.toDto(projectRepository.findById(criteria.getId()).orElseGet(Project::new));
        // 项目二次处理
        projectDto = customHandle(projectDto);
        // 返回集合
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("divideHours", projectDto.getDivideTaskTime());
        returnMap.put("incompleteHours", projectDto.getIncompleteTaskTime());
        return returnMap;
    }
    @Override
    public List<Map<String, Object>> queryTypeContractPrice(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getProjectDistinguish() == null || "".equals(criteria.getProjectDistinguish()) || criteria.getTargetYear() == null || "".equals(criteria.getTargetYear())) {
            return null;
        }
        // 查询汇率列表
        List<SysExchangeRateDto> sysExchangeRateDtoList = sysExchangeRateService.queryAll(new SysExchangeRateQueryCriteria());
        // 根据项目区分、目标年份查询类型营业额
        List<ProjectSummary> projectSummaryList = projectRepository.findTypeContractPriceByProjectDistinguishAndTargetYear(criteria.getProjectDistinguish(), criteria.getTargetYear());
        // 项目类型列表
        List<String> projectTypeNameList = projectSummaryList.stream().map(ProjectSummary::getProjectTypeName).distinct().collect(Collectors.toList());
        // 返回列表
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 循环项目类型列表
        for (int i = 0; i < projectTypeNameList.size(); i++) {
            // 项目类型
            String projectTypeName = projectTypeNameList.get(i);
            // 返回集合
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("name", projectTypeName);
            // 当前项目类型营业额列表
            List<ProjectSummary> currentProjectSummaryList = projectSummaryList.stream().filter(item -> item.getProjectTypeName().equals(projectTypeName)).collect(Collectors.toList());
            // 营业额
            BigDecimal contractPrice = new BigDecimal(0);
            // 循环当前项目类型营业额列表
            for (int j = 0; j < currentProjectSummaryList.size(); j++) {
                // 当前项目类型营业额
                ProjectSummary currentProjectSummary = currentProjectSummaryList.get(j);
                // 当前汇率列表
                List<SysExchangeRateDto> currentSysExchangeRateDtoList = sysExchangeRateDtoList.stream().filter(item -> item.getUnitCurrency().equals(currentProjectSummary.getUnitCurrency())).collect(Collectors.toList());
                // 判断当前汇率列表长度
                if (currentSysExchangeRateDtoList.size() == 1) {
                    // 营业额
                    contractPrice = contractPrice.add(currentProjectSummary.getContractPrice().multiply(currentSysExchangeRateDtoList.get(0).getExchangeRate()));
                }
            }
            returnMap.put("value", contractPrice);
            // 返回列表
            returnList.add(returnMap);
        }
        return returnList;
    }
    @Override
    public List<Map<String, Object>> queryTypeWorkingHours(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getProjectDistinguish() == null || "".equals(criteria.getProjectDistinguish()) || criteria.getTargetYear() == null || "".equals(criteria.getTargetYear())) {
            return null;
        }
        // 根据项目区分、目标年份查询项目
        List<Project> projectList = projectRepository.findProjectByProjectDistinguishAndTargetYear(criteria.getProjectDistinguish(), criteria.getTargetYear());
        // 查询项目类型列表
        ProjectTypeQueryCriteria projectTypeQueryCriteria = new ProjectTypeQueryCriteria();
        List<ProjectType> projectTypeList = projectTypeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, projectTypeQueryCriteria, criteriaBuilder));
        // 返回列表
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 循环项目类型列表
        for (int i = 0; i < projectTypeList.size(); i++) {
            // 项目类型
            ProjectType projectType = projectTypeList.get(i);
            // 处理后项目列表
            List<Project> handleProjectList = projectList.stream().filter(item -> item.getProjectTypeId() == projectType.getId()).collect(Collectors.toList());
            // 判断处理后项目列表长度
            if (handleProjectList.size() != 0) {
                // 处理后项目ID列表
                List<Long> handleProjectIdList = handleProjectList.stream().map(Project::getId).collect(Collectors.toList());
                // 根据项目ID查询总工时
                Double sumWorkingHours = taskRepository.sumWorkingHoursByProjectId(handleProjectIdList);
                // 返回集合
                Map<String, Object> returnMap = new HashMap<>();
                returnMap.put("name", projectType.getName());
                returnMap.put("value", sumWorkingHours);
                // 返回列表
                returnList.add(returnMap);
            }
        }
        return returnList;
    }
    @Override
    public List<ProjectDto> querySubgroupTopHours(ProjectQueryCriteria criteria) {
        // 判断入参完整性
        if (criteria.getProjectDistinguish() == null || "".equals(criteria.getProjectDistinguish())) {
            return null;
        }
        // 查询项目列表
        List<ProjectDto> projectDtoList = projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        // 循环项目列表
        for (int i = 0; i < projectDtoList.size(); i++) {
            // 当前项目
            ProjectDto projectDto = projectDtoList.get(i);
            // 项目二次处理
            projectDto = customHandle(projectDto);
        }
        // 按照任务合计(未完成)进行降序排列
        projectDtoList = projectDtoList.stream().sorted(Comparator.comparing(ProjectDto::getIncompleteTaskTime).reversed()).collect(Collectors.toList());
        return projectDtoList;
    }
    @Override
    //@Cacheable(cacheNames = "project",key = "{#p0}")
    public List<ProjectDto> queryRelevantOfDaily(Long userId) {
        List<TaskUserMongo> taskUserMongos = mongoTemplate.find(Query.query(new Criteria("userId").is(userId)
                .and("taskStatus").in(Constant.TASK_STATUS_NOT_STARTED, Constant.TASK_STATUS_IN_HAND, Constant.TASK_STATUS_TEST, Constant.TASK_STATUS_UNRECOGNIZED)), TaskUserMongo.class);
        List<Long> projectIds = taskUserMongos.stream().map(taskUserMongo -> taskUserMongo.getTask().getProjectId()).distinct().collect(Collectors.toList());
        List<Project> projectList = projectRepository.findByProjectStatusInAndIdIn(Arrays.asList(Constant.PROJECT_STATUS_NOT_STARTED, Constant.PROJECT_STATUS_UNDER_WAY), projectIds);
        return projectList.stream().map(project -> {
            ProjectDto projectDto = new ProjectDto();
            projectDto.setId(project.getId());
            projectDto.setName(project.getName());
            return projectDto;
        }).collect(Collectors.toList());
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/quartz/service/impl/DingTalkServiceImpl.java
@@ -1,755 +1,771 @@
package me.zhengjie.modules.quartz.service.impl;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.*;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.quartz.service.dto.OapiDingTalkAccessToken;
import me.zhengjie.modules.quartz.service.dto.OapiDingTalkRecordResult;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.SysRostering;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.SysRosteringRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service
@RequiredArgsConstructor
public class DingTalkServiceImpl {
    private final AttendanceRepository attendanceRepository;
    private final UserRepository userRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final OpaiDingTalkService opaiDingTalkService;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final AttendanceLeaveRepository attendanceLeaveRepository;
    private final SysRosteringRepository sysRosteringRepository;
    private final AttendanceCardreplacementRepository attendanceCardreplacementRepository;
    /**
     * 凌晨0点执行,新增用户考勤信息
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void getDingTalkAttendanceList(Timestamp attendDate, List attUser) throws Exception {
        // 日期格式化
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 获取当前日期
        String strTodayDate = df.format(new Date());
        // 获取考勤日期类
        Calendar calAttendDay = Calendar.getInstance();
        // 参数日期为null(定时任务)
        if (ObjectUtils.isEmpty(attendDate)) {
            // 考勤日期类
            calAttendDay.setTime(Timestamp.valueOf(strTodayDate + " 00:00:00"));
        } else {
            // 考勤日期类
            calAttendDay.setTime(attendDate);
        }
        // 参数日期为null(定时任务) 或者 参数日期小于等于今天在创建(考勤按钮调用)
        if (ObjectUtils.isEmpty(attendDate) || attendDate.compareTo(Timestamp.valueOf(strTodayDate + " 00:00:00")) <= 0) {
            // 用户列表
            List<User> userList = new ArrayList<>();
            // 参数用户不为空(考勤按钮调用)
            if (ObjectUtils.isNotEmpty(attUser)) {
                // 用户列表
                userList = attUser;
            } else {
                // 用户列表:查询状态正常的员工
                userList = getUserList();
            }
            // 参数日期
            String strAttendDate = "";
            // 节假日列表
            SysConfigHoliday sysConfigHoliday = new SysConfigHoliday();
            // 参数日期不为null(考勤按钮调用)
            if (ObjectUtils.isNotEmpty(attendDate)) {
                // 参数日期
                strAttendDate = df.format(attendDate);
                // 节假日列表
                sysConfigHoliday = sysConfigHolidayRepository.findByHolidayDate(strAttendDate);
            } else {
                // 节假日列表
                sysConfigHoliday = sysConfigHolidayRepository.findByHolidayDate(strTodayDate);
            }
            // 遍历用户列表
            for (User user : userList) {
                // 用户钉钉号不为null
                if (ObjectUtils.isNotEmpty(user.getDingding())) {
                    // 用户排班
                    SysRostering sysRostering = sysRosteringRepository.findByRosId(user.getSysRostering().getId());
                    // 考勤记录
                    Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(user.getId(), (ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate));
                    // 考勤记录为null
                    if (ObjectUtil.isEmpty(attendance)) {
                        // 新建考勤记录
                        attendance = new Attendance();
                    }
                    // 考勤记录
                    attendance.setUserId(user.getId());
                    attendance.setAttendanceDate(Timestamp.valueOf(ObjectUtils.isEmpty(attendDate) ? strTodayDate + " 00:00:00" : strAttendDate + " 00:00:00"));
                    attendance.setStartClockResults((ObjectUtil.isNotEmpty(attendance.getStartClockResults()) && attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_NORMAL)) ? attendance.getStartClockResults() : Constant.ATTENDANCE_STATE_WAITFOR);
                    attendance.setEndClockResults((ObjectUtil.isNotEmpty(attendance.getEndClockResults()) && attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_NORMAL)) ? attendance.getEndClockResults() : Constant.ATTENDANCE_STATE_WAITFOR);
                    // 考勤日期类是否是周末、节假日、工作日
                    if (sysConfigHoliday == null && (calAttendDay.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calAttendDay.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)) {
                        // 考勤记录:日期类型-双休
                        attendance.setDateType(Constant.DATE_TYPE_WEEKEND);
                    } else if (sysConfigHoliday != null && sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
                        // 考勤记录:日期类型-节假日
                        attendance.setDateType(Constant.DATE_TYPE_LEGAL_HOLIDAYS);
                    } else {
                        // 考勤记录:日期类型-工作日
                        attendance.setDateType(Constant.DATE_TYPE_WEEKDAY);
                    }
                    // 时间格式化
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                    // 考勤记
                    attendance.setRosteringWorkStartTime(Timestamp.valueOf((ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate) + " " + dateTimeFormatter.format(sysRostering.getWorkStartTime())));
                    attendance.setRosteringWorkEndTime(Timestamp.valueOf((ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate) + " " + dateTimeFormatter.format(sysRostering.getWorkEndTime())));
                    attendance.setRosteringLunchStartTime(Timestamp.valueOf((ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate) + " " + dateTimeFormatter.format(sysRostering.getLunchStartTime())));
                    attendance.setRosteringLunchEndTime(Timestamp.valueOf((ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate) + " " + dateTimeFormatter.format(sysRostering.getLunchEndTime())));
                    // 保存
                    attendanceRepository.save(attendance);
                }
            }
        }
    }
    /**
     * 中午12点30执行,更新早打卡情况
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void getDingTalkAttendanceListOfNoon(String attendDate, List attUser) throws Exception {
        // 获取钉钉Token
        OapiDingTalkAccessToken oapiDingTalkAccessToken = opaiDingTalkService.getAccessToken();
        // errcode = 0,表示正常返回
        if (0 == oapiDingTalkAccessToken.getErrcode()) {
            // 日期格式化
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            // 参数日期
            String strAttendDate = "";
            // 参数日期不为null(考勤按钮调用)
            if (ObjectUtils.isNotEmpty(attendDate)) {
                // 参数日期
                strAttendDate = attendDate;
            } else {
                // 参数日期
                strAttendDate = df.format(new Date());
            }
            // 获取参数日期类
            Calendar calAttendDate = Calendar.getInstance();
            calAttendDate.setTime(Timestamp.valueOf(strAttendDate + " 00:00:00"));
            // 用户列表
            List<User> userList = new ArrayList<>();
            // 参数用户不为空(考勤按钮调用)
            if(ObjectUtils.isNotEmpty(attUser)){
                // 用户列表
                userList = attUser;
            }else{
                // 用户列表:查询状态正常的员工
                userList = getUserList();
            }
            // 遍历用户列表
            for (User user : userList) {
                // 用户钉钉号不为null
                if (ObjectUtils.isNotEmpty(user.getDingding())) {
                    // 考勤记录:根据用户和日期查询
                    Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(user.getId(), strAttendDate);
                    // 如果是周六或者周日或节假日,打卡状态为等待的话,就改状态为休息(oapiDingTalkRecordResultList为空的情况下)
                    if (ObjectUtils.isNotEmpty(attendance) && (calAttendDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calAttendDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || attendance.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS))) {
                        // 开始打卡结果
                        if(attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_WAITFOR)){
                            attendance.setStartClockResults(Constant.ATTENDANCE_STATE_REST);
                            attendance.setStartLocationResults(Constant.LOCATION_RESULTS_REST);
                            attendance.setActualWorkStartTime(null);
                        }
                        // 结束打卡结果
                        if(attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_WAITFOR)){
                            attendance.setEndClockResults(Constant.ATTENDANCE_STATE_REST);
                            attendance.setEndLocationResults(Constant.LOCATION_RESULTS_REST);
                            attendance.setActualWorkEndTime(null);
                        }
                    }
                    // 钉钉ID
                    List<String> userDinDingList = new ArrayList<>();
                    userDinDingList.add(user.getDingding());
                    // 钉钉数据
                    List<OapiDingTalkRecordResult> oapiDingTalkRecordResultList = new ArrayList<>();
                    oapiDingTalkRecordResultList = opaiDingTalkService.getAttendanceList(oapiDingTalkRecordResultList, oapiDingTalkAccessToken.getAccessToken(), strAttendDate + " 00:00:00", userDinDingList, 0l, 50l);
                    // 遍历钉钉数据
                    for (OapiDingTalkRecordResult oapiDingTalkRecordResult : oapiDingTalkRecordResultList) {
                        // 无打卡记录
                        if ("NotSigned".equals(oapiDingTalkRecordResult.getTimeResult())) {
                            // 钉钉数据
                            oapiDingTalkRecordResult.setUserCheckTime(null);
                        }
                        // 早打卡
                        if ("OnDuty".equals(oapiDingTalkRecordResult.getCheckType())) {
                            // 调用验证状态方法
                            Boolean flag = getCardSupplement(attendance.getUserId(),attendance.getStartClockResults(),attendance.getActualWorkStartTime());
                            // 考勤记录
                            attendance.setStartClockResults(flag == true ? attendance.getStartClockResults() : (ObjectUtil.isEmpty(oapiDingTalkRecordResult.getUserCheckTime()) ? Constant.ATTENDANCE_STATE_NOTSIGNED : checkResult(user.getSysRostering(), oapiDingTalkRecordResult.getUserCheckTime(), 1)));
                            attendance.setStartLocationResults(flag == true ? attendance.getStartLocationResults() : setLocationResults(oapiDingTalkRecordResult.getLocationResult()));
                            attendance.setActualWorkStartTime(flag == true ? attendance.getActualWorkStartTime() : oapiDingTalkRecordResult.getUserCheckTime());
                        }
                        // 晚打卡
                        if ("OffDuty".equals(oapiDingTalkRecordResult.getCheckType())) {
                            // 调用验证状态方法
                            Boolean flag = getCardSupplement(attendance.getUserId(),attendance.getEndClockResults(),attendance.getActualWorkEndTime());
                            // 考勤记录
                            attendance.setEndClockResults(flag == true ? attendance.getEndClockResults() : (ObjectUtil.isEmpty(oapiDingTalkRecordResult.getUserCheckTime()) ? Constant.ATTENDANCE_STATE_NOTSIGNED : checkResult(user.getSysRostering(), oapiDingTalkRecordResult.getUserCheckTime(), 2)));
                            attendance.setEndLocationResults(flag == true ? attendance.getEndLocationResults() : setLocationResults(oapiDingTalkRecordResult.getLocationResult()));
                            attendance.setActualWorkEndTime(flag == true ? attendance.getActualWorkEndTime() : oapiDingTalkRecordResult.getUserCheckTime());
                        }
                    }
                    // 修改考勤打卡状态
                    if (ObjectUtils.isNotEmpty(attendance)) {
                        attendance = updateRecord(user, attendance, true, attendDate);
                        attendanceRepository.save(attendance);
                    }
                }
            }
        }
    }
    /**
     * 凌晨02:30执行,更新晚打卡情况
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void getDingTalkAttendanceListOfNight(String attendDate, List attUser) throws Exception {
        // 获取钉钉Token
        OapiDingTalkAccessToken oapiDingTalkAccessToken = opaiDingTalkService.getAccessToken();
        // errcode = 0,表示正常返回
        if (0 == oapiDingTalkAccessToken.getErrcode()) {
            // 获取参数日期类
            Calendar calAttendDate = Calendar.getInstance();
            // 日期格式化
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            // 参数日期
            String strAttendDate = "";
            // 参数日期不为null(考勤按钮调用)
            if (ObjectUtils.isNotEmpty(attendDate)) {
                // 参数日期
                strAttendDate = attendDate;
            } else {
                // 参数日期类
                calAttendDate.add(Calendar.DATE, -1);
                // 参数日期
                strAttendDate = df.format(calAttendDate.getTime());
            }
            // 参数日期类
            calAttendDate.setTime(Timestamp.valueOf(strAttendDate + " 00:00:00"));
            // 用户列表
            List<User> userList = new ArrayList<>();
            // 参数用户不为空(考勤按钮调用)
            if(ObjectUtils.isNotEmpty(attUser)){
                // 用户列表
                userList = attUser;
            }else{
                // 用户列表:查询状态正常的员工
                userList = getUserList();
            }
            // 遍历用户列表
            for (User user : userList) {
                // 用户钉钉号不为null
                if (ObjectUtils.isNotEmpty(user.getDingding())) {
                    // 考勤记录:根据用户和日期查询
                    Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(user.getId(), strAttendDate);
                    // 如果是周六或者周日或节假日,打卡状态为等待的话,就改状态为休息(oapiDingTalkRecordResultList为空的情况下)
                    if (ObjectUtils.isNotEmpty(attendance) && (calAttendDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calAttendDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || attendance.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS))) {
                        // 开始打卡结果
                        if(attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_WAITFOR)){
                            attendance.setStartClockResults(Constant.ATTENDANCE_STATE_REST);
                            attendance.setStartLocationResults(Constant.LOCATION_RESULTS_REST);
                            attendance.setActualWorkStartTime(null);
                        }
                        // 结束打卡结果
                        if(attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_WAITFOR)){
                            attendance.setEndClockResults(Constant.ATTENDANCE_STATE_REST);
                            attendance.setEndLocationResults(Constant.LOCATION_RESULTS_REST);
                            attendance.setActualWorkEndTime(null);
                        }
                    }
                    // 钉钉ID
                    List<String> userDinDingList = new ArrayList<>();
                    userDinDingList.add(user.getDingding());
                    // 钉钉数据
                    List<OapiDingTalkRecordResult> oapiDingTalkRecordResultList = new ArrayList<>();
                    oapiDingTalkRecordResultList = opaiDingTalkService.getAttendanceList(oapiDingTalkRecordResultList, oapiDingTalkAccessToken.getAccessToken(), strAttendDate + " 00:00:00", userDinDingList, 0l, 50l);
                    // 遍历钉钉数据
                    for (OapiDingTalkRecordResult oapiDingTalkRecordResult : oapiDingTalkRecordResultList) {
                        // 无打卡记录
                        if ("NotSigned".equals(oapiDingTalkRecordResult.getTimeResult())) {
                            // 钉钉数据
                            oapiDingTalkRecordResult.setUserCheckTime(null);
                        }
                        // 早打卡
                        if ("OnDuty".equals(oapiDingTalkRecordResult.getCheckType())) {
                            // 调用验证状态方法
                            Boolean flag = getCardSupplement(attendance.getUserId(),attendance.getStartClockResults(),attendance.getActualWorkStartTime());
                            // 考勤记录
                            attendance.setStartClockResults(flag == true ? attendance.getStartClockResults() : (ObjectUtil.isEmpty(oapiDingTalkRecordResult.getUserCheckTime()) ? Constant.ATTENDANCE_STATE_NOTSIGNED : checkResult(user.getSysRostering(), oapiDingTalkRecordResult.getUserCheckTime(), 1)));
                            attendance.setStartLocationResults(flag == true ? attendance.getStartLocationResults() : setLocationResults(oapiDingTalkRecordResult.getLocationResult()));
                            attendance.setActualWorkStartTime(flag == true ? attendance.getActualWorkStartTime() : oapiDingTalkRecordResult.getUserCheckTime());
                        }
                        // 晚打卡
                        if ("OffDuty".equals(oapiDingTalkRecordResult.getCheckType())) {
                            // 调用验证状态方法
                            Boolean flag = getCardSupplement(attendance.getUserId(),attendance.getEndClockResults(),attendance.getActualWorkEndTime());
                            // 考勤记录
                            attendance.setEndClockResults(flag == true ? attendance.getEndClockResults() : (ObjectUtil.isEmpty(oapiDingTalkRecordResult.getUserCheckTime()) ? Constant.ATTENDANCE_STATE_NOTSIGNED : checkResult(user.getSysRostering(), oapiDingTalkRecordResult.getUserCheckTime(), 2)));
                            attendance.setEndLocationResults(flag == true ? attendance.getEndLocationResults() : setLocationResults(oapiDingTalkRecordResult.getLocationResult()));
                            attendance.setActualWorkEndTime(flag == true ? attendance.getActualWorkEndTime() : oapiDingTalkRecordResult.getUserCheckTime());
                        }
                    }
                    // 修改考勤打卡状态
                    if (ObjectUtils.isNotEmpty(attendance)) {
                        attendance = updateRecord(user, attendance, false, attendDate);
                        attendanceRepository.save(attendance);
                    }
                }
            }
        }
    }
    /**
     * 中午12点30或凌晨02:30执行定时任务
     * @throws Exception
     */
    public void getDingTalkAttendanceListOfNoonOrNight(String attendDate, List attUser) throws Exception {
        // 中午12点30执行,更新早打卡情况
        getDingTalkAttendanceListOfNoon(attendDate, attUser);
        // 凌晨02:30执行,更新晚打卡情况
        getDingTalkAttendanceListOfNight(attendDate, attUser);
    }
    /**
     * 查询其他状态表并调用方法修改
     * @param user
     */
    public Attendance updateRecord(User user, Attendance attendance, Boolean day, String attendDate){
        // 查询考勤请假表
        List<AttendanceLeave> attendanceLeaveLists = attendanceLeaveRepository.findByUserIdAndDate(user.getId(),attendance.getRosteringWorkStartTime().toLocalDateTime(),attendance.getRosteringWorkEndTime().toLocalDateTime());
        for(AttendanceLeave attendanceLeave : attendanceLeaveLists){
            // 上午/下午/全天
            if(attendanceLeave.getLeaveStartTime().toLocalDateTime().isBefore(attendance.getRosteringLunchStartTime().toLocalDateTime()) && attendanceLeave.getLeaveEndTime().toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0){
                getMornOrNoon(user,attendance,attendDate,attendance.getRosteringWorkStartTime(), attendance.getRosteringLunchEndTime(),day);
            }else if(attendanceLeave.getLeaveStartTime().toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 && attendanceLeave.getLeaveEndTime().toLocalDateTime().compareTo(attendance.getRosteringWorkEndTime().toLocalDateTime()) <= 0){
                getMornOrNoon(user,attendance,attendDate,attendance.getRosteringLunchStartTime(),attendance.getRosteringWorkEndTime(),day);
            }else{
                getMornOrNoon(user,attendance,attendDate,attendanceLeave.getLeaveStartTime(),attendanceLeave.getLeaveEndTime(),day);
            }
        }
        //查询出差表
        AttendanceBusinessTravel attendanceBusinessTravel = attendanceBusinessTravelRepository.findByUserAndDate(user.getId(),attendance.getAttendanceDate().toLocalDateTime(),attendance.getAttendanceDate().toLocalDateTime());
        if(ObjectUtils.isNotEmpty(attendanceBusinessTravel)){
            getMornOrNoon(user,attendance,attendDate,attendanceBusinessTravel.getTravelStartTime(),attendance.getRosteringWorkEndTime(),day);
        }// 查询外出表o
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(user.getId(),attendance.getRosteringWorkStartTime().toLocalDateTime(),attendance.getRosteringWorkEndTime().toLocalDateTime());
        for(AttendanceGoOut attendanceGoOut : attendanceGoOutList) {
            // 上午/下午
            if (attendanceGoOut.getOutStartTime().toLocalDateTime().isBefore(attendance.getRosteringLunchStartTime().toLocalDateTime()) && attendanceGoOut.getOutEndTime().toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0) {
                getMornOrNoon(user, attendance, attendDate, attendance.getRosteringWorkStartTime(), attendance.getRosteringLunchEndTime(), day);
            } else if (attendanceGoOut.getOutStartTime().toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 &&  attendanceGoOut.getOutEndTime().toLocalDateTime().compareTo(attendance.getRosteringWorkEndTime().toLocalDateTime()) <= 0) {
                getMornOrNoon(user, attendance, attendDate, attendance.getRosteringLunchStartTime(),attendance.getRosteringWorkEndTime() ,day);
            } else {
                getMornOrNoon(user, attendance, attendDate, attendanceGoOut.getOutStartTime(),  attendanceGoOut.getOutEndTime(), day);
            }
        }
        return attendance;
    }
    /**
     * 请假优先于出差优先于外出
     * @param user
     * @param attendance
     * @param attendDate
     * @param startDate
     * @param endDate
     */
    public void getMornOrNoon(User user,Attendance attendance,String attendDate,Timestamp startDate,Timestamp endDate,Boolean day){
        // 查询考勤请假表
        List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.findByUserIdAndDate(user.getId(),startDate.toLocalDateTime(),endDate.toLocalDateTime());
        Double leaveDuration = new Double(0.00);//钉钉方法的时长
        Double leaveStartDuration = new Double(0.00);//考勤按钮的时长
        Double leaveEndDuration = new Double(0.00);//考勤按钮的时长
        // 请假优先于出差优先于外出
        if(attendanceLeaveList.size() < 1){
            // 查询考勤出差表
            AttendanceBusinessTravel attendanceBusinessTravel = attendanceBusinessTravelRepository.findByUserAndDate(user.getId(),attendance.getAttendanceDate().toLocalDateTime(),attendance.getAttendanceDate().toLocalDateTime());
            Double bussDuration = new Double(0.00);
            Double bussStartDuration = new Double(0.00);//考勤按钮的时长
            Double bussEndDuration = new Double(0.00);//考勤按钮的时长
            if(ObjectUtils.isEmpty(attendanceBusinessTravel)){
                // 查询考勤外出表
                List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(user.getId(),attendance.getRosteringWorkStartTime().toLocalDateTime(),attendance.getRosteringWorkEndTime().toLocalDateTime());
                Double outDuration = new Double(0.00);
                Double outStartDuration = new Double(0.00);// 考勤按钮的时长
                Double outEndDuration = new Double(0.00);// 考勤按钮的时长
                for(AttendanceGoOut attendanceGoOut : attendanceGoOutList){
                    // attendDate不等于null 说明是考勤信息按钮
                    if(ObjectUtils.isNotEmpty(attendDate)){
                        // 上午时长、下午时长
                        outStartDuration += getStartDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance);
                        outEndDuration += getEndDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance);
                        //调用方法修改考勤打卡状态
                        updateAttendanceRecord(null,attendance,Constant.ATTENDANCE_STATE_GOOUT,day,outStartDuration,outEndDuration);
                    }else{
                        // 上午or下午总时长
                        outDuration += getDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance,day);
                        updateAttendanceRecord(outDuration,attendance,Constant.ATTENDANCE_STATE_GOOUT, day,null,null);
                    }
                }
            }else{
                if(ObjectUtils.isNotEmpty(attendanceBusinessTravel)){
                    // attendDate不等于null 说明是考勤信息按钮
                    if(ObjectUtils.isNotEmpty(attendDate)){
                        // 上午时长、下午时长
                        bussStartDuration += getStartDuration(attendanceBusinessTravel.getTravelStartTime(),attendance.getRosteringWorkEndTime(),attendance);
                        bussEndDuration += getEndDuration(attendanceBusinessTravel.getTravelStartTime(),attendance.getRosteringWorkEndTime(),attendance);
                        //调用方法修改考勤打卡状态
                        updateAttendanceRecord(null,attendance,Constant.ATTENDANCE_STATE_BUSINESS,day,bussStartDuration,bussEndDuration);
                    }else{
                        // 上午or下午总时长
                        bussDuration += getDuration(attendanceBusinessTravel.getTravelStartTime(),attendance.getRosteringWorkEndTime(),attendance,day);
                        updateAttendanceRecord(bussDuration,attendance,Constant.ATTENDANCE_STATE_BUSINESS,day,null,null);
                    }
                }
            }
        }else{
            for(AttendanceLeave attendanceLeave : attendanceLeaveList){
                // attendDate不等于null 说明是考勤信息按钮
                if(ObjectUtils.isNotEmpty(attendDate)){
                    // 上午总时长、下午总时长
                    leaveStartDuration += getStartDuration(attendanceLeave.getLeaveStartTime(),attendanceLeave.getLeaveEndTime(),attendance);
                    leaveEndDuration += getEndDuration(attendanceLeave.getLeaveStartTime(),attendanceLeave.getLeaveEndTime(),attendance);
                    //调用方法修改考勤打卡状态
                    updateAttendanceRecord(null,attendance,Constant.ATTENDANCE_STATE_LEAVE,day,leaveStartDuration,leaveEndDuration);
                }else{
                    // 上午or下午总时长
                    leaveDuration += getDuration(attendanceLeave.getLeaveStartTime(),attendanceLeave.getLeaveEndTime(),attendance,day);
                    //调用方法修改考勤打卡状态
                    updateAttendanceRecord(leaveDuration,attendance,Constant.ATTENDANCE_STATE_LEAVE,day,null,null);
                }
            }
        }
    }
    /**
     * 获取上午/下午时长(请假、出差、外出)
     * @param startDate
     * @param endDate
     * @param attendance
     * @return
     */
    public Double getDuration(Timestamp startDate, Timestamp endDate, Attendance attendance,Boolean day){
        Double duration = new Double(0.00);
        // 上午总时长
        if(day){
            if(startDate.toLocalDateTime().isBefore(attendance.getRosteringLunchStartTime().toLocalDateTime()) && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0){
                Integer leaveSTime =  calculateTimes(startDate.toLocalDateTime(), endDate.toLocalDateTime());
                duration += Double.valueOf(new BigDecimal((float) leaveSTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
            if(startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 ||
                    startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) > 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) <= 0){
                Integer leaveSTime =  calculateTimes(startDate.toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime());
                duration += Double.valueOf(new BigDecimal((float) leaveSTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
        }else{
            // 下午总时长
            if(startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringWorkEndTime().toLocalDateTime()) <= 0){
                Integer leaveETime =  calculateTimes(startDate.toLocalDateTime(), endDate.toLocalDateTime());
                duration += Double.valueOf(new BigDecimal((float) leaveETime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
            if(startDate.toLocalDateTime().isBefore(attendance.getRosteringLunchEndTime().toLocalDateTime()) && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0){
                Integer leaveETime =  calculateTimes(attendance.getRosteringLunchEndTime().toLocalDateTime(), endDate.toLocalDateTime());
                duration += Double.valueOf(new BigDecimal((float) leaveETime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
        }
        return duration;
    }
    /**
     * 修改考勤记录打卡状态
     * @param attendance
     * @param type
     */
    public void updateAttendanceRecord(Double duration, Attendance attendance, String type, Boolean day,Double stDuration,Double enDuration){
        // 上午排班开始时间到排班午休开始时间的时长
        Integer workMorningTime =  calculateTimes(attendance.getRosteringWorkStartTime().toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime());
        Double result = Double.valueOf(new BigDecimal((float) workMorningTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        // 上午实际打卡时间到排班午休开始时间的时长
        Double result1 = new Double(0.00);
        if(ObjectUtils.isNotEmpty(attendance.getActualWorkStartTime()) && attendance.getActualWorkStartTime().compareTo(attendance.getRosteringLunchStartTime()) <= 0){
            Integer actualTime =  calculateTimes(attendance.getActualWorkStartTime().toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime());
            result1 = Double.valueOf(new BigDecimal((float) actualTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        // 下午休排班结束时间到下午排班结束时间的时长
        Integer workNoonTime =  calculateTimes(attendance.getRosteringLunchEndTime().toLocalDateTime(), attendance.getRosteringWorkEndTime().toLocalDateTime());
        Double noonResult = Double.valueOf(new BigDecimal((float) workNoonTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        // 下午排班午休结束时间到下班打卡的实际时间的时长
        Double noonResult1 = new Double(0.00);
        if(ObjectUtils.isNotEmpty(attendance.getActualWorkEndTime()) && attendance.getActualWorkEndTime().compareTo(attendance.getRosteringLunchEndTime()) >= 0){
            Integer actualTime =  calculateTimes(attendance.getRosteringLunchEndTime().toLocalDateTime(), attendance.getActualWorkEndTime().toLocalDateTime());
            noonResult1 = Double.valueOf(new BigDecimal((float) actualTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        // 没打卡的情况下,修改考勤打卡状态
        if(attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_NOTSIGNED) && attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_NOTSIGNED)){
            // duration为null说明是考勤信息按钮
            if(ObjectUtils.isEmpty(duration)){
                if(stDuration > 0 && enDuration == 0){
                    setAttendance(stDuration,null,result,null,attendance,type);
                }else if(enDuration > 0 && stDuration == 0){
                    setAttendance(null,enDuration,null,noonResult,attendance,type);
                }else{
                    setAttendance(stDuration,null,result,null,attendance,type);
                    setAttendance(null,enDuration,null,noonResult,attendance,type);
                }
            }else{
                // 上午
                if(day){
                    // 上午时长 >= 上午排班时间 改打卡状态 否则 缺时
                    if(duration >= result){
                        attendance.setStartClockResults(type);
                        attendance.setStartLocationResults(null);
                    }else{
                        attendance.setStartClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
                    }
                }else{
                    // 下午时长 >= 下午排班时间 改打卡状态 否则 缺时
                    if(duration >= noonResult){
                        attendance.setEndClockResults(type);
                        attendance.setEndLocationResults(null);
                    }else{
                        attendance.setEndClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
                    }
                }
            }
        }else{
            // duration为null说明是考勤信息按钮
            if(ObjectUtils.isEmpty(duration)){
                if(stDuration > 0 && enDuration == 0){
                    setAttendanceStart(stDuration,null,result1,result,null,attendance,type);
                }else if(enDuration > 0 && stDuration == 0){
                    setAttendanceStart(null,enDuration,noonResult1,null,noonResult,attendance,type);
                }else{
                    setAttendanceStart(stDuration,null,result1,result,null,attendance,type);
                    setAttendanceStart(null,enDuration,noonResult1,null,noonResult,attendance,type);
                }
            }else{
                //打卡的情况,修改考勤状态
                if(day){
                    if((duration + result1) >= result){
                        attendance.setStartClockResults(type);
                        attendance.setStartLocationResults(null);
                    }else{
                        attendance.setStartClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
                    }
                }else{
                    if((duration + noonResult1) >= noonResult){
                        attendance.setEndClockResults(type);
                        attendance.setEndLocationResults(null);
                    }else{
                        attendance.setEndClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
                    }
                }
            }
        }
    }
    /**
     * 计算时间差
     * @param start
     * @param end
     * @return
     */
    public Integer calculateTimes(LocalDateTime start, LocalDateTime end){
        Integer time = 0;
        Duration duration = null;
        duration = Duration.between(start, start.toLocalDate().atTime(end.toLocalTime()));
        Long StartSeconds = duration.getSeconds();
        time += StartSeconds.intValue();
        return time;
    }
    /**
     * 考勤状态
     * @param sysRostering
     * @param timestamp
     * @param type
     * @return
     */
    public String checkResult(SysRostering sysRostering, Timestamp timestamp, Integer type) {
        String result = ObjectUtil.isEmpty(timestamp) ? Constant.ATTENDANCE_STATE_NOTSIGNED : Constant.ATTENDANCE_STATE_NORMAL;
        if (type.equals(1)) {
            if (timestamp.toLocalDateTime().toLocalTime().isAfter(sysRostering.getWorkStartTime())) {
                result = Constant.ATTENDANCE_START_LATE;
            }
        } else {
            if (timestamp.toLocalDateTime().toLocalTime().isBefore(sysRostering.getWorkEndTime())) {
                result = Constant.ATTENDANCE_START_EARLY;
            }
        }
        return result;
    }
    /**
     * 判断返回位置状态
     * @param locationResults
     * @return
     */
    public String setLocationResults(String locationResults){
        String result = "";
        if(locationResults.equals("Normal")) {
            result = Constant.LOCATION_RESULTS_NORMAL;
        } else if(locationResults.equals("Outside")){
            result = Constant.LOCATION_RESULTS_OUTSIDE;
        } else if(locationResults.equals("NotSigned")){
            result = Constant.LOCATION_RESULTS_NOTSIGNED;
        }
        return result;
    }
    /**
     * 查询用户
     */
    public List<User> getUserList(){
        List<User> userList = userRepository.findAllByEnabled(true);
        return userList;
    }
    /**
     * 没打卡情况(考勤按钮)
     * @param sDuration
     * @param eDuration
     * @param result
     * @param noonResult
     * @param attendance
     * @param type
     */
    public void setAttendance(Double sDuration,Double eDuration,Double result,Double noonResult,Attendance attendance,String type){
        if(ObjectUtils.isEmpty(eDuration) && ObjectUtils.isEmpty(noonResult)){
            // 上午时长 >= 上午排班时间 改打卡状态 否则 缺时
            if(sDuration >= result){
                attendance.setStartClockResults(type);
                attendance.setStartLocationResults(null);
            }else{
                attendance.setStartClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
            }
        }
        if(ObjectUtils.isEmpty(sDuration) && ObjectUtils.isEmpty(result)){
            // 下午时长 >= 下午排班时间 改打卡状态 否则 缺时
            if(eDuration >= noonResult){
                attendance.setEndClockResults(type);
                attendance.setEndLocationResults(null);
            }else{
                attendance.setEndClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
            }
        }
    }
    /**
     * 打卡情况(考勤按钮)
     * @param sDuration
     * @param eDuration
     * @param result
     * @param noonResult
     * @param attendance
     * @param type
     */
    public void setAttendanceStart(Double sDuration,Double eDuration,Double result1,Double result,Double noonResult,Attendance attendance,String type){
        if(ObjectUtils.isEmpty(eDuration) && sDuration > 0){
            if((sDuration + result1) >= result){
                attendance.setStartClockResults(type);
                attendance.setStartLocationResults(null);
            }else{
                attendance.setStartClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
            }
        }
        if(ObjectUtils.isEmpty(sDuration) && eDuration > 0){
            if((eDuration + result1) >= noonResult){
                attendance.setEndClockResults(type);
                attendance.setEndLocationResults(null);
            }else{
                attendance.setEndClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
            }
        }
    }
    public Double getStartDuration(Timestamp startDate, Timestamp endDate, Attendance attendance){
        Double duration = new Double(0.00);
        // 上午总时长
        if(startDate.toLocalDateTime().isBefore(attendance.getRosteringLunchStartTime().toLocalDateTime()) && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0){
            Integer leaveSTime =  calculateTimes(startDate.toLocalDateTime(), endDate.toLocalDateTime());
            duration += Double.valueOf(new BigDecimal((float) leaveSTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        if(startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 ||
                startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) > 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) <= 0){
            Integer leaveSTime =  calculateTimes(startDate.toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime());
            duration += Double.valueOf(new BigDecimal((float) leaveSTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        return duration;
    }
    public Double getEndDuration(Timestamp startDate, Timestamp endDate, Attendance attendance){
        Double duration = new Double(0.00);
        // 下午总时长
        if(startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0){
            Integer leaveETime =  calculateTimes(startDate.toLocalDateTime(), endDate.toLocalDateTime());
            duration += Double.valueOf(new BigDecimal((float) leaveETime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        if(startDate.toLocalDateTime().isBefore(attendance.getRosteringLunchEndTime().toLocalDateTime()) && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0){
            Integer leaveETime =  calculateTimes(attendance.getRosteringLunchEndTime().toLocalDateTime(), endDate.toLocalDateTime());
            duration += Double.valueOf(new BigDecimal((float) leaveETime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        return duration;
    }
    /**
     * 验证是否有通过的补卡记录
     * @param userId
     * @param st
     * @param checkTime
     * @return
     */
    public Boolean getCardSupplement(Long userId,String st,Timestamp checkTime){
        if(ObjectUtils.isNotEmpty(checkTime)){
            // 查询补卡记录
            AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findByUserIdAndTime(userId,checkTime);
            if(ObjectUtils.isNotEmpty(attendanceCardreplacement) && st.equals(Constant.ATTENDANCE_STATE_NORMAL)){
                return true;
            }
        }
        return false;
    }
}
package me.zhengjie.modules.quartz.service.impl;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.*;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
import me.zhengjie.modules.quartz.service.dto.OapiDingTalkAccessToken;
import me.zhengjie.modules.quartz.service.dto.OapiDingTalkRecordResult;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.SysRostering;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.SysRosteringRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service
@RequiredArgsConstructor
public class DingTalkServiceImpl {
    private final AttendanceRepository attendanceRepository;
    private final UserRepository userRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final OpaiDingTalkService opaiDingTalkService;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final AttendanceLeaveRepository attendanceLeaveRepository;
    private final SysRosteringRepository sysRosteringRepository;
    private final AttendanceCardreplacementRepository attendanceCardreplacementRepository;
    /**
     * 凌晨0点执行,新增用户考勤信息
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void getDingTalkAttendanceList(Timestamp attendDate, List attUser) throws Exception {
        // 日期格式化
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 获取当前日期
        String strTodayDate = df.format(new Date());
        // 获取考勤日期类
        Calendar calAttendDay = Calendar.getInstance();
        // 参数日期为null(定时任务)
        if (ObjectUtils.isEmpty(attendDate)) {
            // 考勤日期类
            calAttendDay.setTime(Timestamp.valueOf(strTodayDate + " 00:00:00"));
        } else {
            // 考勤日期类
            calAttendDay.setTime(attendDate);
        }
        // 参数日期为null(定时任务) 或者 参数日期小于等于今天在创建(考勤按钮调用)
        if (ObjectUtils.isEmpty(attendDate) || attendDate.compareTo(Timestamp.valueOf(strTodayDate + " 00:00:00")) <= 0) {
            // 用户列表
            List<User> userList = new ArrayList<>();
            // 参数用户不为空(考勤按钮调用)
            if (ObjectUtils.isNotEmpty(attUser)) {
                // 用户列表
                userList = attUser;
            } else {
                // 用户列表:查询状态正常的员工
                userList = getUserList();
            }
            // 参数日期
            String strAttendDate = "";
            // 节假日列表
            SysConfigHoliday sysConfigHoliday = new SysConfigHoliday();
            // 参数日期不为null(考勤按钮调用)
            if (ObjectUtils.isNotEmpty(attendDate)) {
                // 参数日期
                strAttendDate = df.format(attendDate);
                // 节假日列表
                sysConfigHoliday = sysConfigHolidayRepository.findByHolidayDate(strAttendDate);
            } else {
                // 节假日列表
                sysConfigHoliday = sysConfigHolidayRepository.findByHolidayDate(strTodayDate);
            }
            // 遍历用户列表
            for (User user : userList) {
                // 用户钉钉号不为null
                if (ObjectUtils.isNotEmpty(user.getDingding())) {
                    // 用户排班
                    SysRostering sysRostering = sysRosteringRepository.findByRosId(user.getSysRostering().getId());
                    // 考勤记录
                    Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(user.getId(), (ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate));
                    // 考勤记录为null
                    if (ObjectUtil.isEmpty(attendance)) {
                        // 新建考勤记录
                        attendance = new Attendance();
                    }
                    // 考勤记录
                    attendance.setUserId(user.getId());
                    attendance.setAttendanceDate(Timestamp.valueOf(ObjectUtils.isEmpty(attendDate) ? strTodayDate + " 00:00:00" : strAttendDate + " 00:00:00"));
                    attendance.setStartClockResults((ObjectUtil.isNotEmpty(attendance.getStartClockResults()) && attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_NORMAL)) ? attendance.getStartClockResults() : Constant.ATTENDANCE_STATE_WAITFOR);
                    attendance.setEndClockResults((ObjectUtil.isNotEmpty(attendance.getEndClockResults()) && attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_NORMAL)) ? attendance.getEndClockResults() : Constant.ATTENDANCE_STATE_WAITFOR);
                    // 考勤日期类是否是周末、节假日、工作日
                    if (sysConfigHoliday == null && (calAttendDay.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calAttendDay.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)) {
                        // 考勤记录:日期类型-双休
                        attendance.setDateType(Constant.DATE_TYPE_WEEKEND);
                    } else if (sysConfigHoliday != null && sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
                        // 考勤记录:日期类型-节假日
                        attendance.setDateType(Constant.DATE_TYPE_LEGAL_HOLIDAYS);
                    } else if (sysConfigHoliday != null && sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_HOLIDAYS)) {
                        // 考勤记录:日期类型-法定节假日
                        attendance.setDateType(Constant.DATE_TYPE_HOLIDAYS);
                    } else {
                        // 考勤记录:日期类型-工作日
                        attendance.setDateType(Constant.DATE_TYPE_WEEKDAY);
                    }
                    // 时间格式化
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                    // 考勤记
                    attendance.setRosteringWorkStartTime(Timestamp.valueOf((ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate) + " " + dateTimeFormatter.format(sysRostering.getWorkStartTime())));
                    attendance.setRosteringWorkEndTime(Timestamp.valueOf((ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate) + " " + dateTimeFormatter.format(sysRostering.getWorkEndTime())));
                    attendance.setRosteringLunchStartTime(Timestamp.valueOf((ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate) + " " + dateTimeFormatter.format(sysRostering.getLunchStartTime())));
                    attendance.setRosteringLunchEndTime(Timestamp.valueOf((ObjectUtils.isEmpty(attendDate) ? strTodayDate : strAttendDate) + " " + dateTimeFormatter.format(sysRostering.getLunchEndTime())));
                    // 保存
                    attendanceRepository.save(attendance);
                }
            }
        }
    }
    /**
     * 中午12点30执行,更新早打卡情况
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void getDingTalkAttendanceListOfNoon(String attendDate, List attUser) throws Exception {
        // 获取钉钉Token
        OapiDingTalkAccessToken oapiDingTalkAccessToken = opaiDingTalkService.getAccessToken();
        // errcode = 0,表示正常返回
        if (0 == oapiDingTalkAccessToken.getErrcode()) {
            // 日期格式化
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            // 参数日期
            String strAttendDate = "";
            // 参数日期不为null(考勤按钮调用)
            if (ObjectUtils.isNotEmpty(attendDate)) {
                // 参数日期
                strAttendDate = attendDate;
            } else {
                // 参数日期
                strAttendDate = df.format(new Date());
            }
            // 获取参数日期类
            Calendar calAttendDate = Calendar.getInstance();
            calAttendDate.setTime(Timestamp.valueOf(strAttendDate + " 00:00:00"));
            // 用户列表
            List<User> userList = new ArrayList<>();
            // 参数用户不为空(考勤按钮调用)
            if(ObjectUtils.isNotEmpty(attUser)){
                // 用户列表
                userList = attUser;
            }else{
                // 用户列表:查询状态正常的员工
                userList = getUserList();
            }
            // 遍历用户列表
            for (User user : userList) {
                // 用户钉钉号不为null
                if (ObjectUtils.isNotEmpty(user.getDingding())) {
                    // 考勤记录:根据用户和日期查询
                    Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(user.getId(), strAttendDate);
                    // 如果是周六或者周日或节假日,打卡状态为等待的话,就改状态为休息(oapiDingTalkRecordResultList为空的情况下)
                    if (ObjectUtils.isNotEmpty(attendance) && (calAttendDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calAttendDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || attendance.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS) || attendance.getDateType().equals(Constant.DATE_TYPE_HOLIDAYS))) {
                        // 开始打卡结果
                        if(attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_WAITFOR)){
                            attendance.setStartClockResults(Constant.ATTENDANCE_STATE_REST);
                            attendance.setStartLocationResults(Constant.LOCATION_RESULTS_REST);
                            attendance.setActualWorkStartTime(null);
                        }
                        // 结束打卡结果
                        if(attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_WAITFOR)){
                            attendance.setEndClockResults(Constant.ATTENDANCE_STATE_REST);
                            attendance.setEndLocationResults(Constant.LOCATION_RESULTS_REST);
                            attendance.setActualWorkEndTime(null);
                        }
                    }
                    // 钉钉ID
                    List<String> userDinDingList = new ArrayList<>();
                    userDinDingList.add(user.getDingding());
                    // 钉钉数据
                    List<OapiDingTalkRecordResult> oapiDingTalkRecordResultList = new ArrayList<>();
                    oapiDingTalkRecordResultList = opaiDingTalkService.getAttendanceList(oapiDingTalkRecordResultList, oapiDingTalkAccessToken.getAccessToken(), strAttendDate + " 00:00:00", userDinDingList, 0l, 50l);
                    // 遍历钉钉数据
                    for (OapiDingTalkRecordResult oapiDingTalkRecordResult : oapiDingTalkRecordResultList) {
                        // 无打卡记录
                        if ("NotSigned".equals(oapiDingTalkRecordResult.getTimeResult())) {
                            // 钉钉数据
                            oapiDingTalkRecordResult.setUserCheckTime(null);
                        }
                        // 早打卡
                        if ("OnDuty".equals(oapiDingTalkRecordResult.getCheckType())) {
                            // 调用验证状态方法
                            Boolean flag = getCardSupplement(attendance.getUserId(),attendance.getStartClockResults(),attendance.getActualWorkStartTime());
                            // 考勤记录
                            attendance.setStartClockResults(flag == true ? attendance.getStartClockResults() : (ObjectUtil.isEmpty(oapiDingTalkRecordResult.getUserCheckTime()) ? Constant.ATTENDANCE_STATE_NOTSIGNED : checkResult(user.getSysRostering(), oapiDingTalkRecordResult.getUserCheckTime(), 1)));
                            attendance.setStartLocationResults(flag == true ? attendance.getStartLocationResults() : setLocationResults(oapiDingTalkRecordResult.getLocationResult()));
                            attendance.setActualWorkStartTime(flag == true ? attendance.getActualWorkStartTime() : oapiDingTalkRecordResult.getUserCheckTime());
                        }
                        // 晚打卡
                        if ("OffDuty".equals(oapiDingTalkRecordResult.getCheckType())) {
                            // 调用验证状态方法
                            Boolean flag = getCardSupplement(attendance.getUserId(),attendance.getEndClockResults(),attendance.getActualWorkEndTime());
                            // 考勤记录
                            attendance.setEndClockResults(flag == true ? attendance.getEndClockResults() : (ObjectUtil.isEmpty(oapiDingTalkRecordResult.getUserCheckTime()) ? Constant.ATTENDANCE_STATE_NOTSIGNED : checkResult(user.getSysRostering(), oapiDingTalkRecordResult.getUserCheckTime(), 2)));
                            attendance.setEndLocationResults(flag == true ? attendance.getEndLocationResults() : setLocationResults(oapiDingTalkRecordResult.getLocationResult()));
                            attendance.setActualWorkEndTime(flag == true ? attendance.getActualWorkEndTime() : oapiDingTalkRecordResult.getUserCheckTime());
                        }
                    }
                    // 修改考勤打卡状态
                    if (ObjectUtils.isNotEmpty(attendance)) {
                        attendance = updateRecord(user, attendance, true, attendDate);
                        attendanceRepository.save(attendance);
                    }
                }
            }
        }
    }
    /**
     * 凌晨02:30执行,更新晚打卡情况
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void getDingTalkAttendanceListOfNight(String attendDate, List attUser) throws Exception {
        // 获取钉钉Token
        OapiDingTalkAccessToken oapiDingTalkAccessToken = opaiDingTalkService.getAccessToken();
        // errcode = 0,表示正常返回
        if (0 == oapiDingTalkAccessToken.getErrcode()) {
            // 获取参数日期类
            Calendar calAttendDate = Calendar.getInstance();
            // 日期格式化
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            // 参数日期
            String strAttendDate = "";
            // 参数日期不为null(考勤按钮调用)
            if (ObjectUtils.isNotEmpty(attendDate)) {
                // 参数日期
                strAttendDate = attendDate;
            } else {
                // 参数日期类
                calAttendDate.add(Calendar.DATE, -1);
                // 参数日期
                strAttendDate = df.format(calAttendDate.getTime());
            }
            // 参数日期类
            calAttendDate.setTime(Timestamp.valueOf(strAttendDate + " 00:00:00"));
            // 用户列表
            List<User> userList = new ArrayList<>();
            // 参数用户不为空(考勤按钮调用)
            if(ObjectUtils.isNotEmpty(attUser)){
                // 用户列表
                userList = attUser;
            }else{
                // 用户列表:查询状态正常的员工
                userList = getUserList();
            }
            // 遍历用户列表
            for (User user : userList) {
                // 用户钉钉号不为null
                if (ObjectUtils.isNotEmpty(user.getDingding())) {
                    // 考勤记录:根据用户和日期查询
                    Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(user.getId(), strAttendDate);
                    // 如果是周六或者周日或节假日,打卡状态为等待的话,就改状态为休息(oapiDingTalkRecordResultList为空的情况下)
                    if (ObjectUtils.isNotEmpty(attendance) && (calAttendDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calAttendDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || attendance.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS) || attendance.getDateType().equals(Constant.DATE_TYPE_HOLIDAYS))) {
                        // 开始打卡结果
                        if(attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_WAITFOR)){
                            attendance.setStartClockResults(Constant.ATTENDANCE_STATE_REST);
                            attendance.setStartLocationResults(Constant.LOCATION_RESULTS_REST);
                            attendance.setActualWorkStartTime(null);
                        }
                        // 结束打卡结果
                        if(attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_WAITFOR)){
                            attendance.setEndClockResults(Constant.ATTENDANCE_STATE_REST);
                            attendance.setEndLocationResults(Constant.LOCATION_RESULTS_REST);
                            attendance.setActualWorkEndTime(null);
                        }
                    }
                    // 钉钉ID
                    List<String> userDinDingList = new ArrayList<>();
                    userDinDingList.add(user.getDingding());
                    // 钉钉数据
                    List<OapiDingTalkRecordResult> oapiDingTalkRecordResultList = new ArrayList<>();
                    oapiDingTalkRecordResultList = opaiDingTalkService.getAttendanceList(oapiDingTalkRecordResultList, oapiDingTalkAccessToken.getAccessToken(), strAttendDate + " 00:00:00", userDinDingList, 0l, 50l);
                    // 遍历钉钉数据
                    for (OapiDingTalkRecordResult oapiDingTalkRecordResult : oapiDingTalkRecordResultList) {
                        // 无打卡记录
                        if ("NotSigned".equals(oapiDingTalkRecordResult.getTimeResult())) {
                            // 钉钉数据
                            oapiDingTalkRecordResult.setUserCheckTime(null);
                        }
                        // 早打卡
                        if ("OnDuty".equals(oapiDingTalkRecordResult.getCheckType())) {
                            // 调用验证状态方法
                            Boolean flag = getCardSupplement(attendance.getUserId(),attendance.getStartClockResults(),attendance.getActualWorkStartTime());
                            // 考勤记录
                            attendance.setStartClockResults(flag == true ? attendance.getStartClockResults() : (ObjectUtil.isEmpty(oapiDingTalkRecordResult.getUserCheckTime()) ? Constant.ATTENDANCE_STATE_NOTSIGNED : checkResult(user.getSysRostering(), oapiDingTalkRecordResult.getUserCheckTime(), 1)));
                            attendance.setStartLocationResults(flag == true ? attendance.getStartLocationResults() : setLocationResults(oapiDingTalkRecordResult.getLocationResult()));
                            attendance.setActualWorkStartTime(flag == true ? attendance.getActualWorkStartTime() : oapiDingTalkRecordResult.getUserCheckTime());
                        }
                        // 晚打卡
                        if ("OffDuty".equals(oapiDingTalkRecordResult.getCheckType())) {
                            // 调用验证状态方法
                            Boolean flag = getCardSupplement(attendance.getUserId(),attendance.getEndClockResults(),attendance.getActualWorkEndTime());
                            // 考勤记录
                            attendance.setEndClockResults(flag == true ? attendance.getEndClockResults() : (ObjectUtil.isEmpty(oapiDingTalkRecordResult.getUserCheckTime()) ? Constant.ATTENDANCE_STATE_NOTSIGNED : checkResult(user.getSysRostering(), oapiDingTalkRecordResult.getUserCheckTime(), 2)));
                            attendance.setEndLocationResults(flag == true ? attendance.getEndLocationResults() : setLocationResults(oapiDingTalkRecordResult.getLocationResult()));
                            attendance.setActualWorkEndTime(flag == true ? attendance.getActualWorkEndTime() : oapiDingTalkRecordResult.getUserCheckTime());
                        }
                    }
                    // 修改考勤打卡状态
                    if (ObjectUtils.isNotEmpty(attendance)) {
                        attendance = updateRecord(user, attendance, false, attendDate);
                        attendanceRepository.save(attendance);
                    }
                }
            }
        }
    }
    /**
     * 中午12点30或凌晨02:30执行定时任务
     * @throws Exception
     */
    public void getDingTalkAttendanceListOfNoonOrNight(String attendDate, List attUser) throws Exception {
        // 中午12点30执行,更新早打卡情况
        getDingTalkAttendanceListOfNoon(attendDate, attUser);
        // 凌晨02:30执行,更新晚打卡情况
        getDingTalkAttendanceListOfNight(attendDate, attUser);
    }
    /**
     * 查询其他状态表并调用方法修改
     * @param user
     */
    public Attendance updateRecord(User user, Attendance attendance, Boolean day, String attendDate){
        // 查询考勤请假表
        List<AttendanceLeave> attendanceLeaveLists = attendanceLeaveRepository.findByUserIdAndDate(user.getId(),attendance.getRosteringWorkStartTime().toLocalDateTime(),attendance.getRosteringWorkEndTime().toLocalDateTime());
        for(AttendanceLeave attendanceLeave : attendanceLeaveLists){
            // 上午/下午/全天
            if(attendanceLeave.getLeaveStartTime().toLocalDateTime().isBefore(attendance.getRosteringLunchStartTime().toLocalDateTime()) && attendanceLeave.getLeaveEndTime().toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0){
                getMornOrNoon(user,attendance,attendDate,attendance.getRosteringWorkStartTime(), attendance.getRosteringLunchEndTime(),day);
            }else if(attendanceLeave.getLeaveStartTime().toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 && attendanceLeave.getLeaveEndTime().toLocalDateTime().compareTo(attendance.getRosteringWorkEndTime().toLocalDateTime()) <= 0){
                getMornOrNoon(user,attendance,attendDate,attendance.getRosteringLunchStartTime(),attendance.getRosteringWorkEndTime(),day);
            }else{
                getMornOrNoon(user,attendance,attendDate,attendanceLeave.getLeaveStartTime(),attendanceLeave.getLeaveEndTime(),day);
            }
        }
        //查询出差表
        AttendanceBusinessTravel attendanceBusinessTravel = attendanceBusinessTravelRepository.findByUserAndDate(user.getId(),attendance.getAttendanceDate().toLocalDateTime(),attendance.getAttendanceDate().toLocalDateTime());
        if(ObjectUtils.isNotEmpty(attendanceBusinessTravel)){
            getMornOrNoon(user,attendance,attendDate,attendanceBusinessTravel.getTravelStartTime(),attendance.getRosteringWorkEndTime(),day);
        }// 查询外出表o
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(user.getId(),attendance.getRosteringWorkStartTime().toLocalDateTime(),attendance.getRosteringWorkEndTime().toLocalDateTime());
        for(AttendanceGoOut attendanceGoOut : attendanceGoOutList) {
            // 上午/下午
            if (attendanceGoOut.getOutStartTime().toLocalDateTime().isBefore(attendance.getRosteringLunchStartTime().toLocalDateTime()) && attendanceGoOut.getOutEndTime().toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0) {
                getMornOrNoon(user, attendance, attendDate, attendance.getRosteringWorkStartTime(), attendance.getRosteringLunchEndTime(), day);
            } else if (attendanceGoOut.getOutStartTime().toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 &&  attendanceGoOut.getOutEndTime().toLocalDateTime().compareTo(attendance.getRosteringWorkEndTime().toLocalDateTime()) <= 0) {
                getMornOrNoon(user, attendance, attendDate, attendance.getRosteringLunchStartTime(),attendance.getRosteringWorkEndTime() ,day);
            } else {
                getMornOrNoon(user, attendance, attendDate, attendanceGoOut.getOutStartTime(),  attendanceGoOut.getOutEndTime(), day);
            }
        }
        return attendance;
    }
    /**
     * 请假优先于出差优先于外出
     * @param user
     * @param attendance
     * @param attendDate
     * @param startDate
     * @param endDate
     */
    public void getMornOrNoon(User user,Attendance attendance,String attendDate,Timestamp startDate,Timestamp endDate,Boolean day){
        // 查询考勤请假表
        List<AttendanceLeave> attendanceLeaveList = attendanceLeaveRepository.findByUserIdAndDate(user.getId(),startDate.toLocalDateTime(),endDate.toLocalDateTime());
        Double leaveDuration = new Double(0.00);//钉钉方法的时长
        Double leaveStartDuration = new Double(0.00);//考勤按钮的时长
        Double leaveEndDuration = new Double(0.00);//考勤按钮的时长
        // 请假优先于出差优先于外出
        if(attendanceLeaveList.size() < 1){
            // 查询考勤出差表
            AttendanceBusinessTravel attendanceBusinessTravel = attendanceBusinessTravelRepository.findByUserAndDate(user.getId(),attendance.getAttendanceDate().toLocalDateTime(),attendance.getAttendanceDate().toLocalDateTime());
            Double bussDuration = new Double(0.00);
            Double bussStartDuration = new Double(0.00);//考勤按钮的时长
            Double bussEndDuration = new Double(0.00);//考勤按钮的时长
            if(ObjectUtils.isEmpty(attendanceBusinessTravel)){
                // 查询考勤外出表
                List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(user.getId(),attendance.getRosteringWorkStartTime().toLocalDateTime(),attendance.getRosteringWorkEndTime().toLocalDateTime());
                Double outDuration = new Double(0.00);
                Double outStartDuration = new Double(0.00);// 考勤按钮的时长
                Double outEndDuration = new Double(0.00);// 考勤按钮的时长
                for(AttendanceGoOut attendanceGoOut : attendanceGoOutList){
                    // attendDate不等于null 说明是考勤信息按钮
                    if(ObjectUtils.isNotEmpty(attendDate)){
                        // 上午时长、下午时长
                        outStartDuration += getStartDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance);
                        outEndDuration += getEndDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance);
                        //调用方法修改考勤打卡状态
                        updateAttendanceRecord(null,attendance,Constant.ATTENDANCE_STATE_GOOUT,day,outStartDuration,outEndDuration);
                    }else{
                        // 上午or下午总时长
                        outDuration += getDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance,day);
                        updateAttendanceRecord(outDuration,attendance,Constant.ATTENDANCE_STATE_GOOUT, day,null,null);
                    }
                }
            }else{
                if(ObjectUtils.isNotEmpty(attendanceBusinessTravel)){
                    // attendDate不等于null 说明是考勤信息按钮
                    if(ObjectUtils.isNotEmpty(attendDate)){
                        // 上午时长、下午时长
                        bussStartDuration += getStartDuration(attendanceBusinessTravel.getTravelStartTime(),attendance.getRosteringWorkEndTime(),attendance);
                        bussEndDuration += getEndDuration(attendanceBusinessTravel.getTravelStartTime(),attendance.getRosteringWorkEndTime(),attendance);
                        //调用方法修改考勤打卡状态
                        updateAttendanceRecord(null,attendance,Constant.ATTENDANCE_STATE_BUSINESS,day,bussStartDuration,bussEndDuration);
                    }else{
                        // 上午or下午总时长
                        bussDuration += getDuration(attendanceBusinessTravel.getTravelStartTime(),attendance.getRosteringWorkEndTime(),attendance,day);
                        updateAttendanceRecord(bussDuration,attendance,Constant.ATTENDANCE_STATE_BUSINESS,day,null,null);
                    }
                }
            }
        }else{
            // 查询考勤外出表
            List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(user.getId(),attendance.getRosteringWorkStartTime().toLocalDateTime(),attendance.getRosteringWorkEndTime().toLocalDateTime());
            for(AttendanceGoOut attendanceGoOut : attendanceGoOutList){
                // attendDate不等于null 说明是考勤信息按钮
                if(ObjectUtils.isNotEmpty(attendDate)){
                    // 上午时长、下午时长
                    leaveStartDuration += getStartDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance);
                    leaveEndDuration += getEndDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance);
                }else{
                    // 上午or下午总时长
                    leaveDuration += getDuration(attendanceGoOut.getOutStartTime(),attendanceGoOut.getOutEndTime(),attendance,day);
                }
            }
            for(AttendanceLeave attendanceLeave : attendanceLeaveList){
                // attendDate不等于null 说明是考勤信息按钮
                if(ObjectUtils.isNotEmpty(attendDate)){
                    // 上午总时长、下午总时长
                    leaveStartDuration += getStartDuration(attendanceLeave.getLeaveStartTime(),attendanceLeave.getLeaveEndTime(),attendance);
                    leaveEndDuration += getEndDuration(attendanceLeave.getLeaveStartTime(),attendanceLeave.getLeaveEndTime(),attendance);
                    //调用方法修改考勤打卡状态
                    updateAttendanceRecord(null,attendance,Constant.ATTENDANCE_STATE_LEAVE,day,leaveStartDuration,leaveEndDuration);
                }else{
                    // 上午or下午总时长
                    leaveDuration += getDuration(attendanceLeave.getLeaveStartTime(),attendanceLeave.getLeaveEndTime(),attendance,day);
                    //调用方法修改考勤打卡状态
                    updateAttendanceRecord(leaveDuration,attendance,Constant.ATTENDANCE_STATE_LEAVE,day,null,null);
                }
            }
        }
    }
    /**
     * 获取上午/下午时长(请假、出差、外出)
     * @param startDate
     * @param endDate
     * @param attendance
     * @return
     */
    public Double getDuration(Timestamp startDate, Timestamp endDate, Attendance attendance,Boolean day){
        Double duration = new Double(0.00);
        // 上午总时长
        if(day){
            if(startDate.toLocalDateTime().isBefore(attendance.getRosteringLunchStartTime().toLocalDateTime()) && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0){
                Integer leaveSTime =  calculateTimes(startDate.toLocalDateTime(), endDate.toLocalDateTime());
                duration += Double.valueOf(new BigDecimal((float) leaveSTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
            if(startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 ||
                    startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) > 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) <= 0){
                Integer leaveSTime =  calculateTimes(startDate.toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime());
                duration += Double.valueOf(new BigDecimal((float) leaveSTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
        }else{
            // 下午总时长
            if(startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringWorkEndTime().toLocalDateTime()) <= 0){
                Integer leaveETime =  calculateTimes(startDate.toLocalDateTime(), endDate.toLocalDateTime());
                duration += Double.valueOf(new BigDecimal((float) leaveETime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
            if(startDate.toLocalDateTime().isBefore(attendance.getRosteringLunchEndTime().toLocalDateTime()) && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0){
                Integer leaveETime =  calculateTimes(attendance.getRosteringLunchEndTime().toLocalDateTime(), endDate.toLocalDateTime());
                duration += Double.valueOf(new BigDecimal((float) leaveETime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
        }
        return duration;
    }
    /**
     * 修改考勤记录打卡状态
     * @param attendance
     * @param type
     */
    public void updateAttendanceRecord(Double duration, Attendance attendance, String type, Boolean day,Double stDuration,Double enDuration){
        // 上午排班开始时间到排班午休开始时间的时长
        Integer workMorningTime =  calculateTimes(attendance.getRosteringWorkStartTime().toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime());
        Double result = Double.valueOf(new BigDecimal((float) workMorningTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        // 上午实际打卡时间到排班午休开始时间的时长
        Double result1 = new Double(0.00);
        if(ObjectUtils.isNotEmpty(attendance.getActualWorkStartTime()) && attendance.getActualWorkStartTime().compareTo(attendance.getRosteringLunchStartTime()) <= 0){
            Integer actualTime =  calculateTimes(attendance.getActualWorkStartTime().toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime());
            result1 = Double.valueOf(new BigDecimal((float) actualTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        // 下午休排班结束时间到下午排班结束时间的时长
        Integer workNoonTime =  calculateTimes(attendance.getRosteringLunchEndTime().toLocalDateTime(), attendance.getRosteringWorkEndTime().toLocalDateTime());
        Double noonResult = Double.valueOf(new BigDecimal((float) workNoonTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        // 下午排班午休结束时间到下班打卡的实际时间的时长
        Double noonResult1 = new Double(0.00);
        if(ObjectUtils.isNotEmpty(attendance.getActualWorkEndTime()) && attendance.getActualWorkEndTime().compareTo(attendance.getRosteringLunchEndTime()) >= 0){
            Integer actualTime =  calculateTimes(attendance.getRosteringLunchEndTime().toLocalDateTime(), attendance.getActualWorkEndTime().toLocalDateTime());
            noonResult1 = Double.valueOf(new BigDecimal((float) actualTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        // 没打卡的情况下,修改考勤打卡状态
        if(attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_NOTSIGNED) && attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_NOTSIGNED)){
            // duration为null说明是考勤信息按钮
            if(ObjectUtils.isEmpty(duration)){
                if(stDuration > 0 && enDuration == 0){
                    setAttendance(stDuration,null,result,null,attendance,type);
                }else if(enDuration > 0 && stDuration == 0){
                    setAttendance(null,enDuration,null,noonResult,attendance,type);
                }else{
                    setAttendance(stDuration,null,result,null,attendance,type);
                    setAttendance(null,enDuration,null,noonResult,attendance,type);
                }
            }else{
                // 上午
                if(day){
                    // 上午时长 >= 上午排班时间 改打卡状态 否则 缺时
                    if(duration >= result){
                        attendance.setStartClockResults(type);
                        attendance.setStartLocationResults(null);
                    }else{
                        attendance.setStartClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
                    }
                }else{
                    // 下午时长 >= 下午排班时间 改打卡状态 否则 缺时
                    if(duration >= noonResult){
                        attendance.setEndClockResults(type);
                        attendance.setEndLocationResults(null);
                    }else{
                        attendance.setEndClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
                    }
                }
            }
        }else{
            // duration为null说明是考勤信息按钮
            if(ObjectUtils.isEmpty(duration)){
                if(stDuration > 0 && enDuration == 0){
                    setAttendanceStart(stDuration,null,result1,result,null,attendance,type);
                }else if(enDuration > 0 && stDuration == 0){
                    setAttendanceStart(null,enDuration,noonResult1,null,noonResult,attendance,type);
                }else{
                    setAttendanceStart(stDuration,null,result1,result,null,attendance,type);
                    setAttendanceStart(null,enDuration,noonResult1,null,noonResult,attendance,type);
                }
            }else{
                //打卡的情况,修改考勤状态
                if(day){
                    if((duration + result1) >= result){
                        attendance.setStartClockResults(type);
                        attendance.setStartLocationResults(null);
                    }else{
                        attendance.setStartClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
                    }
                }else{
                    if((duration + noonResult1) >= noonResult){
                        attendance.setEndClockResults(type);
                        attendance.setEndLocationResults(null);
                    }else{
                        attendance.setEndClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
                    }
                }
            }
        }
    }
    /**
     * 计算时间差
     * @param start
     * @param end
     * @return
     */
    public Integer calculateTimes(LocalDateTime start, LocalDateTime end){
        Integer time = 0;
        Duration duration = null;
        duration = Duration.between(start, start.toLocalDate().atTime(end.toLocalTime()));
        Long StartSeconds = duration.getSeconds();
        time += StartSeconds.intValue();
        return time;
    }
    /**
     * 考勤状态
     * @param sysRostering
     * @param timestamp
     * @param type
     * @return
     */
    public String checkResult(SysRostering sysRostering, Timestamp timestamp, Integer type) {
        String result = ObjectUtil.isEmpty(timestamp) ? Constant.ATTENDANCE_STATE_NOTSIGNED : Constant.ATTENDANCE_STATE_NORMAL;
        if (type.equals(1)) {
            if (timestamp.toLocalDateTime().toLocalTime().isAfter(sysRostering.getWorkStartTime())) {
                result = Constant.ATTENDANCE_START_LATE;
            }
        } else {
            if (timestamp.toLocalDateTime().toLocalTime().isBefore(sysRostering.getWorkEndTime())) {
                result = Constant.ATTENDANCE_START_EARLY;
            }
        }
        return result;
    }
    /**
     * 判断返回位置状态
     * @param locationResults
     * @return
     */
    public String setLocationResults(String locationResults){
        String result = "";
        if(locationResults.equals("Normal")) {
            result = Constant.LOCATION_RESULTS_NORMAL;
        } else if(locationResults.equals("Outside")){
            result = Constant.LOCATION_RESULTS_OUTSIDE;
        } else if(locationResults.equals("NotSigned")){
            result = Constant.LOCATION_RESULTS_NOTSIGNED;
        }
        return result;
    }
    /**
     * 查询用户
     */
    public List<User> getUserList(){
        List<User> userList = userRepository.findAllByEnabled(true);
        return userList;
    }
    /**
     * 没打卡情况(考勤按钮)
     * @param sDuration
     * @param eDuration
     * @param result
     * @param noonResult
     * @param attendance
     * @param type
     */
    public void setAttendance(Double sDuration,Double eDuration,Double result,Double noonResult,Attendance attendance,String type){
        if(ObjectUtils.isEmpty(eDuration) && ObjectUtils.isEmpty(noonResult)){
            // 上午时长 >= 上午排班时间 改打卡状态 否则 缺时
            if(sDuration >= result){
                attendance.setStartClockResults(type);
                attendance.setStartLocationResults(null);
            }else{
                attendance.setStartClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
            }
        }
        if(ObjectUtils.isEmpty(sDuration) && ObjectUtils.isEmpty(result)){
            // 下午时长 >= 下午排班时间 改打卡状态 否则 缺时
            if(eDuration >= noonResult){
                attendance.setEndClockResults(type);
                attendance.setEndLocationResults(null);
            }else{
                attendance.setEndClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
            }
        }
    }
    /**
     * 打卡情况(考勤按钮)
     * @param sDuration
     * @param eDuration
     * @param result
     * @param noonResult
     * @param attendance
     * @param type
     */
    public void setAttendanceStart(Double sDuration,Double eDuration,Double result1,Double result,Double noonResult,Attendance attendance,String type){
        if(ObjectUtils.isEmpty(eDuration) && sDuration > 0){
            if((sDuration + result1) >= result){
                attendance.setStartClockResults(type);
                attendance.setStartLocationResults(null);
            }else{
                attendance.setStartClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
            }
        }
        if(ObjectUtils.isEmpty(sDuration) && eDuration > 0){
            if((eDuration + result1) >= noonResult){
                attendance.setEndClockResults(type);
                attendance.setEndLocationResults(null);
            }else{
                attendance.setEndClockResults(Constant.ATTENDANCE_STATE_LACK_OF_TIME);
            }
        }
    }
    public Double getStartDuration(Timestamp startDate, Timestamp endDate, Attendance attendance){
        Double duration = new Double(0.00);
        // 上午总时长
        if(startDate.toLocalDateTime().isBefore(attendance.getRosteringLunchStartTime().toLocalDateTime()) && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0){
            Integer leaveSTime =  calculateTimes(startDate.toLocalDateTime(), endDate.toLocalDateTime());
            duration += Double.valueOf(new BigDecimal((float) leaveSTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        if(startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0 ||
                startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) > 0 && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) <= 0){
            Integer leaveSTime =  calculateTimes(startDate.toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime());
            duration += Double.valueOf(new BigDecimal((float) leaveSTime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        return duration;
    }
    public Double getEndDuration(Timestamp startDate, Timestamp endDate, Attendance attendance){
        Double duration = new Double(0.00);
        // 下午总时长
        if(startDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0){
            Integer leaveETime =  calculateTimes(startDate.toLocalDateTime(), endDate.toLocalDateTime());
            duration += Double.valueOf(new BigDecimal((float) leaveETime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        if(startDate.toLocalDateTime().isBefore(attendance.getRosteringLunchEndTime().toLocalDateTime()) && endDate.toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) >= 0){
            Integer leaveETime =  calculateTimes(attendance.getRosteringLunchEndTime().toLocalDateTime(), endDate.toLocalDateTime());
            duration += Double.valueOf(new BigDecimal((float) leaveETime / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        return duration;
    }
    /**
     * 验证是否有通过的补卡记录
     * @param userId
     * @param st
     * @param checkTime
     * @return
     */
    public Boolean getCardSupplement(Long userId,String st,Timestamp checkTime){
        if(ObjectUtils.isNotEmpty(checkTime)){
            // 查询补卡记录
            AttendanceCardreplacement attendanceCardreplacement = attendanceCardreplacementRepository.findByUserIdAndTime(userId,checkTime);
            if(ObjectUtils.isNotEmpty(attendanceCardreplacement) && st.equals(Constant.ATTENDANCE_STATE_NORMAL)){
                return true;
            }
        }
        return false;
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/salary/service/impl/NewSalaryServiceImpl.java
@@ -1,790 +1,815 @@
/*
 *  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.salary.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.service.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.AttendanceQueryCriteria;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.service.ProjectPerformanceDetailService;
import me.zhengjie.modules.project.service.dto.ProjectPerformanceDetailQueryCriteria;
import me.zhengjie.modules.salary.domain.NewSalary;
import me.zhengjie.modules.salary.repository.NewSalaryRepository;
import me.zhengjie.modules.salary.service.NewSalaryService;
import me.zhengjie.modules.salary.service.dto.NewSalaryDto;
import me.zhengjie.modules.salary.service.dto.NewSalaryQueryCriteria;
import me.zhengjie.modules.salary.service.mapstruct.NewSalaryMapper;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.SysConfigIndividualIncomeTaxService;
import me.zhengjie.modules.system.service.SysUserLevelOtherService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.task.service.TaskDaliyService;
import me.zhengjie.modules.task.service.dto.TaskDaliyQueryCriteria;
import me.zhengjie.modules.treatment.domain.MeritLevel;
import me.zhengjie.modules.treatment.domain.MeritWage;
import me.zhengjie.modules.treatment.repository.MeritLevelRepository;
import me.zhengjie.modules.treatment.repository.MeritWageRepository;
import me.zhengjie.modules.treatment.service.UserInsuranceService;
import me.zhengjie.modules.treatment.service.UserLevelWageService;
import me.zhengjie.modules.treatment.service.dto.UserInsuranceDto;
import me.zhengjie.modules.treatment.service.dto.UserInsuranceQueryCriteria;
import me.zhengjie.modules.treatment.service.dto.UserLevelWageDto;
import me.zhengjie.modules.treatment.service.dto.UserLevelWageQueryCriteria;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
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.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
 * @author ZLH
 * @date 2023-08-23
 **/
@Service
@RequiredArgsConstructor
public class NewSalaryServiceImpl implements NewSalaryService {
    private final NewSalaryRepository newSalaryRepository;
    private final NewSalaryMapper newSalaryMapper;
    private final UserRepository userRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final RoleService roleService;
    private final DictDetailRepository dictDetailRepository;
    // ==================== 以下为定时生成工资记录主要依赖 ====================
    private final UserService userService;
    private final UserLevelWageService userLevelWageService;
    private final UserInsuranceService userInsuranceService;
    private final SysUserLevelOtherService sysUserLevelOtherService;
    private final AttendanceService attendanceService;
    private final TaskDaliyService taskDaliyService;
    private final SysConfigIndividualIncomeTaxService sysConfigIndividualIncomeTaxService;
    private final ProjectPerformanceDetailService projectPerformanceDetailService;
    // ==================== 以上为定时生成工资记录主要依赖 ====================
    private final MeritWageRepository meritWageRepository;
    private final MeritLevelRepository meritLevelRepository;
    @Override
    public Map<String, Object> queryAll(NewSalaryQueryCriteria criteria, Pageable pageable) {
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        // 判断角色等级
        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
            // 工资查询类
            criteria.setUserId(SecurityUtils.getCurrentUserId());
            criteria.setPublicityStatus(Constant.PUBLICITY_STATUS_YES);
        } else if (criteria.getCompanyId() != null) {
            UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
            userQueryCriteria.setEnabled(true);
            userQueryCriteria.setCompanyId(criteria.getCompanyId());
            List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, userQueryCriteria, criteriaBuilder));
            List<Long> userIds = users.stream().map(user -> user.getId()).collect(Collectors.toList());
            if (criteria.getUserIds() == null) {
                criteria.setUserIds(userIds);
            } else {
                criteria.setUserIds(criteria.getUserIds().stream().filter(userId -> userIds.contains(userId)).collect(Collectors.toList()));
            }
            if (criteria.getUserIds().isEmpty()) {
                return PageUtil.toPage(Collections.emptyList(), 0);
            }
        }
        Page<NewSalary> page = newSalaryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        // 将实体类转换为DTO(重写)
        Function<NewSalary, NewSalaryDto> func = new Function<NewSalary, NewSalaryDto>() {
            @Override
            public NewSalaryDto apply(NewSalary t) {
                // 将实体类转换成DTO
                NewSalaryDto newSalaryDto = newSalaryMapper.toDto(t);
                // 根据用户ID查询用户信息
                User user = userRepository.findById(newSalaryDto.getUserId()).orElseGet(User::new);
                ValidationUtil.isNull(user.getId(), "User", "id", newSalaryDto.getUserId());
                // 用户昵称
                newSalaryDto.setUserNickName(user.getNickName());
                // 返回处理好的DTO
                return newSalaryDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<NewSalaryDto> queryAll(NewSalaryQueryCriteria criteria) {
        return newSalaryMapper.toDto(newSalaryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    @Override
    @Transactional
    public NewSalaryDto findById(Long id) {
        NewSalary newSalary = newSalaryRepository.findById(id).orElseGet(NewSalary::new);
        ValidationUtil.isNull(newSalary.getId(), "NewSalary", "id", id);
        return newSalaryMapper.toDto(newSalary);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public NewSalaryDto create(NewSalary resources) {
        // 根据用户ID和工资年月查询
        List<NewSalary> newSalaryList = newSalaryRepository.findByUserIdAndSalaryYearMonth(resources.getUserId(), resources.getSalaryYearMonth());
        // 判断列表长度
        if (newSalaryList.size() > 0) {
            throw new BadRequestException("找到相同用户相同年月的工资记录!");
        }
//        NewSalary savedSalary = newSalaryRepository.save(resources);
//        if (savedSalary.getId() != null) {
//            // 保存成功
//        } else {
//            // 保存失败
//            Prin
//        }
        return newSalaryMapper.toDto(newSalaryRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(NewSalary resources) {
        // 根据用户ID和工资年月查询
        List<NewSalary> newSalaryList = newSalaryRepository.findByUserIdAndSalaryYearMonth(resources.getUserId(), resources.getSalaryYearMonth());
        // 判断列表长度
        if (newSalaryList.size() > 1) {
            throw new BadRequestException("找到相同用户相同年月的工资记录!");
        } else if (newSalaryList.size() == 1) {
            // 判断是否是同一条记录
            if (newSalaryList.get(0).getId().longValue() != resources.getId().longValue()) {
                throw new BadRequestException("找到相同用户相同年月的工资记录!");
            }
        }
        NewSalary newSalary = newSalaryRepository.findById(resources.getId()).orElseGet(NewSalary::new);
        // 判断承认状态
        if (Constant.APPROVE_STATUS_ACKNOWLEDGED.equals(newSalary.getApproveStatus())) {
            throw new BadRequestException("已承认的工资记录无法进行修改!");
        }
        ValidationUtil.isNull(newSalary.getId(), "Salary", "id", resources.getId());
        newSalary.copy(resources);
        newSalaryRepository.save(newSalary);
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            newSalaryRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<NewSalaryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (NewSalaryDto newSalaryDto : all) {
            String userNickName = newSalaryDto.getUserId() != null ? userRepository.findById(newSalaryDto.getUserId()).orElseGet(User::new).getNickName() : "";
            String publicityStatus = newSalaryDto.getPublicityStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.PUBLICITY_STATUS, newSalaryDto.getPublicityStatus()).getLabel() : "";
            String approveStatus = newSalaryDto.getApproveStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.APPROVE_STATUS, newSalaryDto.getApproveStatus()).getLabel() : "";
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("员工姓名", userNickName);
            map.put("工资年月", newSalaryDto.getSalaryYearMonth());
            map.put("基本工资", newSalaryDto.getBasicWage());
            map.put("全勤小时数", newSalaryDto.getFullDays());
            map.put("缺勤小时数", newSalaryDto.getAbsenceDays());
            map.put("实际基础工资", newSalaryDto.getActualBasicWage());
            map.put("其他补助", newSalaryDto.getTravelAllowance());
//            map.put("绩效工资", newSalaryDto.getAchievementsWage());
//            map.put("应完成绩效工时", newSalaryDto.getNeedCompletedAchievementsHours());
//            map.put("已完成绩效工时", newSalaryDto.getAlreadyCompletedAchievementsHours());
//            map.put("实际绩效工资", newSalaryDto.getActualAchievementsWage());
//            map.put("业绩工资", newSalaryDto.getPerformanceWage());
//            map.put("应完成业绩工时", newSalaryDto.getNeedCompletedPerformanceHours());
//            map.put("已完成业绩工时", newSalaryDto.getAlreadyCompletedPerformanceHours());
//            map.put("实际业绩工资", newSalaryDto.getActualPerformanceWage());
//            map.put("团队工资", newSalaryDto.getTeamWage());
//            map.put("实达标团队工时", newSalaryDto.getActualComplianceTeamHours());
//            map.put("已完成团队工时", newSalaryDto.getAlreadyCompletedTeamHours());
//            map.put("实际团队工资", newSalaryDto.getActualTeamWage());
            map.put("公积金基数", newSalaryDto.getAccumulationFund());
            map.put("公积金个人缴纳比例", newSalaryDto.getAccumulationFundPersonal());
            map.put("公积金个人缴纳金额", newSalaryDto.getAccumulationFundPersonalAmount());
            map.put("公积金公司缴纳比例", newSalaryDto.getAccumulationFundCompany());
            map.put("公积金公司缴纳金额", newSalaryDto.getAccumulationFundCompanyAmount());
            map.put("养老险基数", newSalaryDto.getRetirementInsurance());
            map.put("养老险个人缴纳比例", newSalaryDto.getRetirementInsurancePersonal());
            map.put("养老险个人缴纳金额", newSalaryDto.getRetirementInsurancePersonalAmount());
            map.put("养老险公司缴纳比例", newSalaryDto.getRetirementInsuranceCompany());
            map.put("养老险公司缴纳金额", newSalaryDto.getRetirementInsuranceCompanyAmount());
            map.put("医疗险基数", newSalaryDto.getMedicalInsurance());
            map.put("医疗险个人缴纳比例", newSalaryDto.getMedicalInsurancePersonal());
            map.put("医疗险个人缴纳金额", newSalaryDto.getMedicalInsurancePersonalAmount());
            map.put("医疗险公司缴纳比例", newSalaryDto.getMedicalInsuranceCompany());
            map.put("医疗险公司缴纳金额", newSalaryDto.getMedicalInsuranceCompanyAmount());
            map.put("失业险基数", newSalaryDto.getUnemploymentInsurance());
            map.put("失业险个人缴纳比例", newSalaryDto.getUnemploymentInsurancePersonal());
            map.put("失业险个人缴纳金额", newSalaryDto.getUnemploymentInsurancePersonalAmount());
            map.put("失业险公司缴纳比例", newSalaryDto.getUnemploymentInsuranceCompany());
            map.put("失业险公司缴纳金额", newSalaryDto.getUnemploymentInsuranceCompanyAmount());
            map.put("生育险基数", newSalaryDto.getBirthInsurance());
            map.put("生育险个人缴纳比例", newSalaryDto.getBirthInsurancePersonal());
            map.put("生育险个人缴纳金额", newSalaryDto.getBirthInsurancePersonalAmount());
            map.put("生育险公司缴纳比例", newSalaryDto.getBirthInsuranceCompany());
            map.put("生育险公司缴纳金额", newSalaryDto.getBirthInsuranceCompanyAmount());
            map.put("工伤险基数", newSalaryDto.getEmploymentInsurance());
            map.put("工伤险个人缴纳比例", newSalaryDto.getEmploymentInsurancePersonal());
            map.put("工伤险个人缴纳金额", newSalaryDto.getEmploymentInsurancePersonalAmount());
            map.put("工伤险公司缴纳比例", newSalaryDto.getEmploymentInsuranceCompany());
            map.put("工伤险公司缴纳金额", newSalaryDto.getEmploymentInsuranceCompanyAmount());
            map.put("税前金额", newSalaryDto.getPreTaxAmount());
            map.put("个人所得税", newSalaryDto.getIndividualIncomeTax());
            map.put("税后金额", newSalaryDto.getAfterTaxAmount());
            map.put("备注", newSalaryDto.getRemarks());
            map.put("公示状态", publicityStatus);
            map.put("承认状态", approveStatus);
            map.put("创建者", newSalaryDto.getCreateBy());
            map.put("创建时间", newSalaryDto.getCreateTime());
            map.put("更新者", newSalaryDto.getUpdateBy());
            map.put("更新时间", newSalaryDto.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public Integer queryWorkDays(NewSalaryQueryCriteria criteria) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (criteria.getUserId() == null) {
            return 0;
        }
//        User user = userRepository.findById(criteria.getUserId()).orElseGet(User::new);
//        // 员工的创建时间
//        String stTime = sdf.format(user.getCreateTime()).substring(0, 7);
//
//        if (stTime.equals(criteria.getTargetYearMonth().substring(0, 7))) {
//            criteria.setTargetYearMonth(sdf.format(user.getCreateTime()).substring(0, 10));
//        }
        // 国际时间转中国时间
        String targetYearMonth = criteria.getTargetYearMonth();
        // 节日查询类
        SysConfigHolidayQueryCriteria sysConfigHolidayQueryCriteria = new SysConfigHolidayQueryCriteria();
        sysConfigHolidayQueryCriteria.setHolidayDateLike(targetYearMonth.substring(0, 7));
        // 获取某月节日数据
        List<SysConfigHoliday> sysConfigHolidayList = sysConfigHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, sysConfigHolidayQueryCriteria, criteriaBuilder));
        // 查询某月工作天数
        return DateUtil.getWorkDayOfMonth(sysConfigHolidayList, targetYearMonth);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publicity(Long[] ids) {
        // 循环ID列表
        for (Long id : ids) {
            // 查询工资
            NewSalary newSalary = newSalaryRepository.findById(id).orElseGet(NewSalary::new);
            ValidationUtil.isNull(newSalary.getId(), "Salary", "id", id);
            // 公示状态
            newSalary.setPublicityStatus(Constant.PUBLICITY_STATUS_YES);
            // 保存
            newSalaryRepository.save(newSalary);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(Long[] ids) {
        // 循环ID列表
        for (Long id : ids) {
            // 查询工资
            NewSalary newSalary = newSalaryRepository.findById(id).orElseGet(NewSalary::new);
            ValidationUtil.isNull(newSalary.getId(), "Salary", "id", id);
            // 承认状态
            newSalary.setApproveStatus(Constant.APPROVE_STATUS_ACKNOWLEDGED);
            // 保存
            newSalaryRepository.save(newSalary);
        }
    }
    @Override
    public void generate(NewSalaryQueryCriteria criteria) {
        List<String> errors = new ArrayList<>();
        // 用户检索类
        UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
        userQueryCriteria.setEnabled(true);
        if (criteria.getSelectedValue1() != null) {
            userQueryCriteria.setUserIds(criteria.getSelectedValue1());
        }
        // 获取用户列表
        List<UserSmallDto> userDtoList = userService.querySmallAll(userQueryCriteria);
        // 循环用户列表
        for (int i = 0; i < userDtoList.size(); i++) {
            try {
                // 单个用户工资结算
                singleUserSalarySettlement(userDtoList.get(i).getId(), criteria.getTargetYearMonth(), errors);
            } catch (Exception e) {
                // 跳过本次循环
                continue;
            }
        }
        // 在循环结束后处理错误
        if (!errors.isEmpty()) {
            // 将所有的错误信息收集到一个字符串中
            String errorMessage = String.join("; ", errors);
            // 抛出一个新的异常
            throw new RuntimeException(errorMessage);
        }
    }
    @Override
    public Double getMeritWage(Double completedAchievementsHoursRate, Long level) {
        //获取到当前这个级别的业绩工资
        MeritWage meritWage = meritWageRepository.findByLevelId(level);
        //根据业绩工资去查一下当前这个等级的业绩工资下分几个等级
        List<MeritLevel> meritLevelList = meritLevelRepository.findByMeritWageId(meritWage.getId());
        Double resultMoney = 0D;
        for (MeritLevel meritLevel : meritLevelList) {
            if (completedAchievementsHoursRate >= meritLevel.getMeritStandard()) {
                resultMoney = meritLevel.getMeritMoney();
            }
        }
        return resultMoney;
    }
    // 单个用户工资结算
    private void singleUserSalarySettlement(Long userId, String targetYearMonth, List<String> errors) {
        // 工资实体类
        NewSalary newSalary = new NewSalary();
        newSalary.setUserId(userId);
        Timestamp salaryYearMonth = Timestamp.valueOf(LocalDate.parse(targetYearMonth, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
        newSalary.setSalaryYearMonth(salaryYearMonth);
        newSalary.setPublicityStatus(Constant.PUBLICITY_STATUS_NOT);
        newSalary.setApproveStatus(Constant.APPROVE_STATUS_UNRECOGNIZED);
        try {
            // 获取出差补助
            newSalary = getUserBussSubsidy(userId, targetYearMonth, newSalary);
//            // 获取加班补助工资
//            newSalary = getUserOverTimeSubsidy(userId, targetYearMonth, newSalary);
            // 获取用户级别工资
            newSalary = getUserLevelWage(userId, targetYearMonth, newSalary, errors);
//            // 获取用户级别其他(旧版,新版无个人业绩比例字段)
//            newSalary = getUserLevelOther(userId, targetYearMonth, newSalary);
            // 获取工作天数
            newSalary = getWorkDays(targetYearMonth, newSalary);
            // 获取出勤小时数
            newSalary = getAttendanceHours(userId, targetYearMonth, newSalary);
//            // 获取已完成工时
//            newSalary = getCompletedWork(userId, targetYearMonth, newSalary);
            // 获取用户级别保险
            newSalary = getUserLevelInsurance(userId, targetYearMonth, newSalary);
        } catch (BadRequestException | ParseException e) {
            errors.add(e.getMessage());
            return;
        } catch (Exception e) {
            return;
        }
        List<NewSalary> oldNewSalaryList = newSalaryRepository.findByUserIdAndSalaryYearMonth(userId, salaryYearMonth);
        if (oldNewSalaryList.size() > 0) {
            for (NewSalary oldNewSalary : oldNewSalaryList) {
                oldNewSalary.copy(newSalary);
                newSalaryRepository.save(oldNewSalary);
            }
        } else {
            newSalaryRepository.save(newSalary);
        }
//        create(newSalary);
//        try {
            // 保存
//            create(newSalary);
//        } catch (Exception e) {
//            // 删除
//            deleteByUserIdAndSalaryYearMonthAndCreateNew(newSalary);
//        }
    }
    // 获取用户级别工资
    private NewSalary getUserLevelWage(Long userId, String targetYearMonth, NewSalary newSalary, List<String> errors) {
        // 用户级别工资检索类
        UserLevelWageQueryCriteria userLevelWageQueryCriteria = new UserLevelWageQueryCriteria();
        userLevelWageQueryCriteria.setUserId(userId);
        userLevelWageQueryCriteria.setTargetYearMonth(targetYearMonth);
        try {
            Double coefficient = 1.0;
            UserDto userDto = userService.findById(userId);
            LocalDate createDate = userDto.getCreateTime().toLocalDateTime().toLocalDate();
            if (userDto.getInternshipTime() != null) {
                LocalDate localDate1 = createDate.plusMonths(userDto.getInternshipTime());
                LocalDate localDate2 = LocalDate.parse(targetYearMonth, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                if (!localDate2.isAfter(localDate1)) {
                    coefficient = 0.8;
                }
            }
            // 查询指定年月用户级别工资
            UserLevelWageDto userLevelWageDto = userLevelWageService.queryTargetYearMonth(userLevelWageQueryCriteria);
            // 级别基本工资
            BigDecimal basicWage = userLevelWageDto.getBasicWage().multiply(BigDecimal.valueOf(coefficient));
            // 级别等级工资
            BigDecimal rankWage = userLevelWageDto.getRankWage().multiply(BigDecimal.valueOf(coefficient));
            // 绩效工资
            BigDecimal performanceWage = userLevelWageDto.getPerformanceWage().multiply(BigDecimal.valueOf(coefficient));
            // 设置工资条的基本工资
            newSalary.setBasicWage(basicWage.add(rankWage).add(performanceWage));
            // 设置工资条的绩效工资
            newSalary.setAchievementsWage(BigDecimal.ZERO);
            // 设置工资条的业绩工资
            newSalary.setPerformanceWage(BigDecimal.ZERO);
            // 设置工资条实际业绩工资
            newSalary.setActualPerformanceWage(BigDecimal.ZERO);
            // 设置工资条的团队工资
            newSalary.setTeamWage(BigDecimal.ZERO);
        } catch (RuntimeException | ParseException e) {
            errors.add(e.getMessage());
            return null;
        }
        // 返回
        return newSalary;
    }
    // 获取出差补助
    private NewSalary getUserBussSubsidy(Long userId, String targetYearMonth, NewSalary newSalary) throws ParseException {
        // 用户级别工资检索类
        UserLevelWageQueryCriteria userLevelWageQueryCriteria = new UserLevelWageQueryCriteria();
        userLevelWageQueryCriteria.setUserId(userId);
        userLevelWageQueryCriteria.setTargetYearMonth(targetYearMonth + " 00:00:00");
        // 获取出差补助金额
        Double bussMoney = userLevelWageService.queryTravelAllowance(userLevelWageQueryCriteria);
        // 设置出差补助的金额
        newSalary.setTravelAllowance(new BigDecimal(bussMoney));
        // 税前工资累计
        newSalary.setPreTaxAmount(newSalary.getPreTaxAmount().add(newSalary.getTravelAllowance()));
        return newSalary;
    }
    // 获取加班补助工资
    private NewSalary getUserOverTimeSubsidy(Long userId, String targetYearMonth, NewSalary newSalary) throws ParseException {
        // 用户级别工资检索类
        UserLevelWageQueryCriteria userLevelWageQueryCriteria = new UserLevelWageQueryCriteria();
        userLevelWageQueryCriteria.setUserId(userId);
        userLevelWageQueryCriteria.setTargetYearMonth(targetYearMonth + " 00:00:00");
        // 获取加班补助金额
        Double overTimeMoney = userLevelWageService.queryOverTimeAllowance(userLevelWageQueryCriteria);
        // 设置加班补助的金额
        newSalary.setOvertimeAllowance(new BigDecimal(overTimeMoney));
        return newSalary;
    }
    // 获取用户级别保险
    private NewSalary getUserLevelInsurance(Long userId, String targetYearMonth, NewSalary newSalary) throws ParseException {
        UserDto userDto = userService.findById(userId);
        LocalDate createDate = userDto.getCreateTime().toLocalDateTime().toLocalDate();
        if (userDto.getInternshipTime() != null) {
            LocalDate localDate1 = createDate.plusMonths(userDto.getInternshipTime());
            LocalDate localDate2 = LocalDate.parse(targetYearMonth, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (localDate1.isAfter(localDate2)) {
                // 税前工资累计
                newSalary.setAfterTaxAmount(newSalary.getPreTaxAmount());
                return newSalary;
            }
        }
        // 用户级别保险查询类
        UserInsuranceQueryCriteria criteria = new UserInsuranceQueryCriteria();
        criteria.setUserId(userId);
        criteria.setTargetYearMonth(targetYearMonth);
        // 查询指定年月用户级别保险
        UserInsuranceDto userInsuranceDto = userInsuranceService.queryTargetYearMonth(criteria);
        // 公积金基数
        newSalary.setAccumulationFund(userInsuranceDto.getAccumulationFund());
        // 公积金个人缴纳比例
        newSalary.setAccumulationFundPersonal(userInsuranceDto.getAccumulationFundPersonal());
        // 公积金个人缴纳金额
        newSalary.setAccumulationFundPersonalAmount(userInsuranceDto.getAccumulationFund().multiply(new BigDecimal(userInsuranceDto.getAccumulationFundPersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 公积金公司缴纳比例
        newSalary.setAccumulationFundCompany(userInsuranceDto.getAccumulationFundCompany());
        // 公积金公司缴纳金额
        newSalary.setAccumulationFundCompanyAmount(userInsuranceDto.getAccumulationFund().multiply(new BigDecimal(userInsuranceDto.getAccumulationFundCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 养老险基数
        newSalary.setRetirementInsurance(userInsuranceDto.getRetirementInsurance());
        // 养老险个人缴纳比例
        newSalary.setRetirementInsurancePersonal(userInsuranceDto.getRetirementInsurancePersonal());
        // 养老险个人缴纳金额
        newSalary.setRetirementInsurancePersonalAmount(userInsuranceDto.getRetirementInsurance().multiply(new BigDecimal(userInsuranceDto.getRetirementInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 养老险公司缴纳比例
        newSalary.setRetirementInsuranceCompany(userInsuranceDto.getRetirementInsuranceCompany());
        // 养老险公司缴纳金额
        newSalary.setRetirementInsuranceCompanyAmount(userInsuranceDto.getRetirementInsurance().multiply(new BigDecimal(userInsuranceDto.getRetirementInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 医疗险基数
        newSalary.setMedicalInsurance(userInsuranceDto.getMedicalInsurance());
        // 医疗险个人缴纳比例
        newSalary.setMedicalInsurancePersonal(userInsuranceDto.getMedicalInsurancePersonal());
        // 医疗险个人缴纳金额
        newSalary.setMedicalInsurancePersonalAmount(userInsuranceDto.getMedicalInsurance().multiply(new BigDecimal(userInsuranceDto.getMedicalInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 医疗险公司缴纳比例
        newSalary.setMedicalInsuranceCompany(userInsuranceDto.getMedicalInsuranceCompany());
        // 医疗险公司缴纳金额
        newSalary.setMedicalInsuranceCompanyAmount(userInsuranceDto.getMedicalInsurance().multiply(new BigDecimal(userInsuranceDto.getMedicalInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 失业险基数
        newSalary.setUnemploymentInsurance(userInsuranceDto.getUnemploymentInsurance());
        // 失业险个人缴纳比例
        newSalary.setUnemploymentInsurancePersonal(userInsuranceDto.getUnemploymentInsurancePersonal());
        // 失业险个人缴纳金额
        newSalary.setUnemploymentInsurancePersonalAmount(userInsuranceDto.getUnemploymentInsurance().multiply(new BigDecimal(userInsuranceDto.getUnemploymentInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 失业险公司缴纳比例
        newSalary.setUnemploymentInsuranceCompany(userInsuranceDto.getUnemploymentInsuranceCompany());
        // 失业险公司缴纳金额
        newSalary.setUnemploymentInsuranceCompanyAmount(userInsuranceDto.getUnemploymentInsurance().multiply(new BigDecimal(userInsuranceDto.getUnemploymentInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 生育险基数
        newSalary.setBirthInsurance(userInsuranceDto.getBirthInsurance());
        // 生育险个人缴纳比例
        newSalary.setBirthInsurancePersonal(userInsuranceDto.getBirthInsurancePersonal());
        // 生育险个人缴纳金额
        newSalary.setBirthInsurancePersonalAmount(userInsuranceDto.getBirthInsurance().multiply(new BigDecimal(userInsuranceDto.getBirthInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 生育险公司缴纳比例
        newSalary.setBirthInsuranceCompany(userInsuranceDto.getBirthInsuranceCompany());
        // 生育险公司缴纳金额
        newSalary.setBirthInsuranceCompanyAmount(userInsuranceDto.getBirthInsurance().multiply(new BigDecimal(userInsuranceDto.getBirthInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 工伤险基数
        newSalary.setEmploymentInsurance(userInsuranceDto.getEmploymentInsurance());
        // 工伤险个人缴纳比例
        newSalary.setEmploymentInsurancePersonal(userInsuranceDto.getEmploymentInsurancePersonal());
        // 工伤险个人缴纳金额
        newSalary.setEmploymentInsurancePersonalAmount(userInsuranceDto.getEmploymentInsurance().multiply(new BigDecimal(userInsuranceDto.getEmploymentInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 工伤险公司缴纳比例
        newSalary.setEmploymentInsuranceCompany(userInsuranceDto.getEmploymentInsuranceCompany());
        // 工伤险公司缴纳金额
        newSalary.setEmploymentInsuranceCompanyAmount(userInsuranceDto.getEmploymentInsurance().multiply(new BigDecimal(userInsuranceDto.getEmploymentInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 税前工资累计
        newSalary.setAfterTaxAmount(newSalary.getPreTaxAmount()
            // 公积金个人缴纳金额
            .subtract(newSalary.getAccumulationFundPersonalAmount())
            // 养老险个人缴纳金额
            .subtract(newSalary.getRetirementInsurancePersonalAmount())
            // 医疗险个人缴纳金额
            .subtract(newSalary.getMedicalInsurancePersonalAmount())
            // 失业险个人缴纳金额
            .subtract(newSalary.getUnemploymentInsurancePersonalAmount())
            // 生育险个人缴纳金额
            .subtract(newSalary.getBirthInsurancePersonalAmount())
            // 工伤险个人缴纳金额
            .subtract(newSalary.getEmploymentInsurancePersonalAmount())
        );
        // 返回
        return newSalary;
    }
    // 获取用户级别其他
    private NewSalary getUserLevelOther(Long userId, String targetYearMonth, NewSalary newSalary) {
        // 用户级别其他查询类
        SysUserLevelOtherQueryCriteria sysUserLevelOtherQueryCriteria = new SysUserLevelOtherQueryCriteria();
        sysUserLevelOtherQueryCriteria.setUserId(userId);
        sysUserLevelOtherQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询指定年月用户级别其他(旧版,新版无个人业绩比例字段)
        SysUserLevelOtherDto sysUserLevelOtherDto = sysUserLevelOtherService.queryTargetYearMonth(sysUserLevelOtherQueryCriteria);
        // 个人业绩比例(旧版,新版无个人业绩比例字段)
//        newSalary.setPersonalPerformanceProportion(sysUserLevelOtherDto.getPersonalPerformanceProportion());
        // 返回
        return newSalary;
    }
    // 获取工作天数
    private NewSalary getWorkDays(String targetYearMonth, NewSalary newSalary) {
        // 工资查询类
        NewSalaryQueryCriteria newSalaryQueryCriteria = new NewSalaryQueryCriteria();
        newSalaryQueryCriteria.setUserId(newSalary.getUserId());
        newSalaryQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询某月工作天数
        Integer workDays = queryWorkDays(newSalaryQueryCriteria);
        // 全勤小时数
        newSalary.setFullDays(Double.valueOf(workDays * 8));
        // 应完成绩效工时
        newSalary.setNeedCompletedAchievementsHours(Double.valueOf(workDays * 8));
//        newSalary.setNeedCompletedPerformanceHours(Double.valueOf(workDays * 8 * 1.1));
        // 返回
        return newSalary;
    }
    // 获取出勤小时数
    private NewSalary getAttendanceHours(Long userId, String targetYearMonth, NewSalary newSalary) {
        // 考勤查询类
        AttendanceQueryCriteria attendanceQueryCriteria = new AttendanceQueryCriteria();
        attendanceQueryCriteria.setUserId(userId);
        attendanceQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询某月出勤小时数
        Double attendanceHours = attendanceService.queryAttendanceHours(attendanceQueryCriteria);
        // 缺勤小时数
        newSalary.setAbsenceDays(newSalary.getFullDays() > attendanceHours ? Double.valueOf(newSalary.getFullDays() - attendanceHours) : 0);
        // 缺勤小时数
        BigDecimal absenceDays = new BigDecimal(newSalary.getAbsenceDays());
        // 实际基础工资
        newSalary.setActualBasicWage(newSalary.getBasicWage().subtract(newSalary.getBasicWage().multiply(absenceDays).divide(new BigDecimal(newSalary.getFullDays()), 2, RoundingMode.HALF_UP)));
        // 税前工资累计
        newSalary.setPreTaxAmount(newSalary.getPreTaxAmount().add(newSalary.getActualBasicWage()));
        // 返回
        return newSalary;
    }
    // 获取达标工时
    private NewSalary getComplianceWork(Long userId, String targetYearMonth, NewSalary newSalary) {
        // 任务日报查询类
        ProjectPerformanceDetailQueryCriteria taskDaliyQueryCriteria = new ProjectPerformanceDetailQueryCriteria();
        taskDaliyQueryCriteria.setUserId(userId);
        taskDaliyQueryCriteria.setYearMonth(Timestamp.valueOf(targetYearMonth + " 00:00:00"));
        // 查询某月已达标工时
        Double complianceWork = projectPerformanceDetailService.queryComplianceWork(taskDaliyQueryCriteria);
        // 实达标团队工时
        newSalary.setActualComplianceTeamHours(complianceWork);
        // 返回
        return newSalary;
    }
    // 获取已完成工时
    private NewSalary getCompletedWork(Long userId, String targetYearMonth, NewSalary newSalary) {
        // 任务日报查询类
        TaskDaliyQueryCriteria taskDaliyQueryCriteria = new TaskDaliyQueryCriteria();
        taskDaliyQueryCriteria.setUserId(userId);
        taskDaliyQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询某月已完成工时
        Double completedWork = taskDaliyService.queryCompletedWork(taskDaliyQueryCriteria, false);
        // 已完成绩效工时
        newSalary.setAlreadyCompletedAchievementsHours(completedWork);
//        // 已完成业绩工时
//        newSalary.setAlreadyCompletedPerformanceHours(completedWork);
//        // 已完成团队工时
//        newSalary.setAlreadyCompletedTeamHours(completedWork);
        Double otherWage = taskDaliyService.queryOtherWage(taskDaliyQueryCriteria);
        newSalary.setPieceRate(BigDecimal.valueOf(otherWage));
        // 绩效定时器
        while (true) {
            // 判断预计绩效工资、应完成绩效工时是否为空
            if (newSalary.getAchievementsWage() != null && newSalary.getNeedCompletedAchievementsHours() != null) {
                // 实际绩效工资
                newSalary.setActualAchievementsWage(newSalary.getAchievementsWage().multiply(new BigDecimal(completedWork)).divide(new BigDecimal(newSalary.getNeedCompletedAchievementsHours())));
                // 清空绩效定时器
                break;
            }
        }
        // 业绩定时器
        while (true) {
            // 判断预计业绩工资、应完成业绩工时是否为空
            if (newSalary.getPerformanceWage() != null && newSalary.getNeedCompletedPerformanceHours() != null) {
                // 实际业绩工资
                newSalary.setActualPerformanceWage(completedWork >= newSalary.getNeedCompletedPerformanceHours() ? newSalary.getPerformanceWage() : new BigDecimal(0));
            }
            // 清空业绩定时器
            break;
        }
//        // 团队定时器
//        while (true) {
//            // 判断预计团队工资、实达标团队工时是否为空
//            if (newSalary.getTeamWage() != null && newSalary.getActualComplianceTeamHours() != null) {
//                // 实际团队工资
//                newSalary.setActualTeamWage(newSalary.getActualComplianceTeamHours() != 0 ? newSalary.getTeamWage().multiply(new BigDecimal(newSalary.getActualComplianceTeamHours() / completedWork)) : new BigDecimal(0));
//                // 清空团队定时器
//                break;
//            }
//        }
        // 统计定时器
        while (true) {
            // 判断 实际基础工资、实际绩效工资、实际业绩工资、实际团队工资、公积金个人缴纳金额、养老险个人缴纳金额、
            // 医疗险个人缴纳金额、失业险个人缴纳金额、生育险个人缴纳金额、工伤险个人缴纳金额 是否为空
            if (
                    newSalary.getActualBasicWage() != null &&
                            newSalary.getActualAchievementsWage() != null &&
                            newSalary.getActualPerformanceWage() != null &&
                            newSalary.getActualTeamWage() != null &&
                            newSalary.getAccumulationFundPersonalAmount() != null &&
                            newSalary.getRetirementInsurancePersonalAmount() != null &&
                            newSalary.getMedicalInsurancePersonalAmount() != null &&
                            newSalary.getUnemploymentInsurancePersonalAmount() != null &&
                            newSalary.getBirthInsurancePersonalAmount() != null &&
                            newSalary.getEmploymentInsurancePersonalAmount() != null
            ) {
                // 税前金额
                newSalary.setPreTaxAmount(newSalary.getActualBasicWage().add(newSalary.getActualAchievementsWage()).add(newSalary.getActualPerformanceWage()).add(newSalary.getActualTeamWage()));
                // 查询个人所得税列表
                List<SysConfigIndividualIncomeTaxDto> sysConfigIndividualIncomeTaxDtoList = sysConfigIndividualIncomeTaxService.queryAll(new SysConfigIndividualIncomeTaxQueryCriteria());
                // 税额
                BigDecimal taxAmount = new BigDecimal(0);
                // 计税金额
                BigDecimal taxableAmount = newSalary.getPreTaxAmount().subtract(newSalary.getAccumulationFundPersonalAmount()).subtract(newSalary.getRetirementInsurancePersonalAmount())
                        .subtract(newSalary.getMedicalInsurancePersonalAmount()).subtract(newSalary.getUnemploymentInsurancePersonalAmount()).subtract(newSalary.getBirthInsurancePersonalAmount())
                        .subtract(newSalary.getEmploymentInsurancePersonalAmount());
                // 循环个人所得税列表
                for (int i = 0; i < sysConfigIndividualIncomeTaxDtoList.size(); i++) {
                    // 判断计税金额所在个人所得税范围
                    if (sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd() != null &&
                            taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd()) == 1) {
                        // 税额
                        taxAmount.add(
                                (sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd().subtract(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountStart()))
                                        .multiply(new BigDecimal(sysConfigIndividualIncomeTaxDtoList.get(i).getTaxRate()).divide(new BigDecimal(100)))
                        );
                    } else if (
                            (taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountStart()) == 1 ||
                                    taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountStart()) == 0) &&
                                    (sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd() == null ||
                                            taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd()) == -1 ||
                                            taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd()) == 0)
                    ) {
                        // 税额
                        taxAmount.add(
                                (taxableAmount.subtract(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountStart()))
                                        .multiply(new BigDecimal(sysConfigIndividualIncomeTaxDtoList.get(i).getTaxRate()).divide(new BigDecimal(100)))
                        );
                    }
                    // 判断循环是否结束
                    if (i == sysConfigIndividualIncomeTaxDtoList.size() - 1) {
                        // 个人所得税
//                        newSalary.setIndividualIncomeTax(taxAmount);
                        newSalary.setIndividualIncomeTax(new BigDecimal(0));
                        // 税后金额
                        newSalary.setAfterTaxAmount(taxableAmount.subtract(taxAmount).compareTo(new BigDecimal(0)) == -1 ? new BigDecimal(0) : taxableAmount.subtract(taxAmount));
                    }
                }
                // 清空统计定时器
                break;
            }
        }
        // 返回
        return newSalary;
    }
    // ==================== 以上为定时生成工资记录主要逻辑 ====================
/*
 *  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.salary.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.service.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.AttendanceQueryCriteria;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.service.ProjectPerformanceDetailService;
import me.zhengjie.modules.project.service.dto.ProjectPerformanceDetailQueryCriteria;
import me.zhengjie.modules.salary.domain.NewSalary;
import me.zhengjie.modules.salary.repository.NewSalaryRepository;
import me.zhengjie.modules.salary.service.NewSalaryService;
import me.zhengjie.modules.salary.service.dto.NewSalaryDto;
import me.zhengjie.modules.salary.service.dto.NewSalaryQueryCriteria;
import me.zhengjie.modules.salary.service.mapstruct.NewSalaryMapper;
import me.zhengjie.modules.system.domain.SysConfigHoliday;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.SysConfigIndividualIncomeTaxService;
import me.zhengjie.modules.system.service.SysUserLevelOtherService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.task.service.TaskDaliyService;
import me.zhengjie.modules.task.service.dto.TaskDaliyQueryCriteria;
import me.zhengjie.modules.treatment.domain.MeritLevel;
import me.zhengjie.modules.treatment.domain.MeritWage;
import me.zhengjie.modules.treatment.repository.MeritLevelRepository;
import me.zhengjie.modules.treatment.repository.MeritWageRepository;
import me.zhengjie.modules.treatment.service.UserInsuranceService;
import me.zhengjie.modules.treatment.service.UserLevelWageService;
import me.zhengjie.modules.treatment.service.dto.UserInsuranceDto;
import me.zhengjie.modules.treatment.service.dto.UserInsuranceQueryCriteria;
import me.zhengjie.modules.treatment.service.dto.UserLevelWageDto;
import me.zhengjie.modules.treatment.service.dto.UserLevelWageQueryCriteria;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
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.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
 * @author ZLH
 * @date 2023-08-23
 **/
@Service
@RequiredArgsConstructor
public class NewSalaryServiceImpl implements NewSalaryService {
    private final NewSalaryRepository newSalaryRepository;
    private final NewSalaryMapper newSalaryMapper;
    private final UserRepository userRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final RoleService roleService;
    private final DictDetailRepository dictDetailRepository;
    // ==================== 以下为定时生成工资记录主要依赖 ====================
    private final UserService userService;
    private final UserLevelWageService userLevelWageService;
    private final UserInsuranceService userInsuranceService;
    private final SysUserLevelOtherService sysUserLevelOtherService;
    private final AttendanceService attendanceService;
    private final TaskDaliyService taskDaliyService;
    private final SysConfigIndividualIncomeTaxService sysConfigIndividualIncomeTaxService;
    private final ProjectPerformanceDetailService projectPerformanceDetailService;
    // ==================== 以上为定时生成工资记录主要依赖 ====================
    private final MeritWageRepository meritWageRepository;
    private final MeritLevelRepository meritLevelRepository;
    @Override
    public Map<String, Object> queryAll(NewSalaryQueryCriteria criteria, Pageable pageable) {
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        // 判断角色等级
        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
            // 工资查询类
            criteria.setUserId(SecurityUtils.getCurrentUserId());
            criteria.setPublicityStatus(Constant.PUBLICITY_STATUS_YES);
        } else if (criteria.getCompanyId() != null) {
            UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
            userQueryCriteria.setEnabled(true);
            userQueryCriteria.setCompanyId(criteria.getCompanyId());
            List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, userQueryCriteria, criteriaBuilder));
            List<Long> userIds = users.stream().map(user -> user.getId()).collect(Collectors.toList());
            if (criteria.getUserIds() == null) {
                criteria.setUserIds(userIds);
            } else {
                criteria.setUserIds(criteria.getUserIds().stream().filter(userId -> userIds.contains(userId)).collect(Collectors.toList()));
            }
            if (criteria.getUserIds().isEmpty()) {
                return PageUtil.toPage(Collections.emptyList(), 0);
            }
        }
        Page<NewSalary> page = newSalaryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        // 将实体类转换为DTO(重写)
        Function<NewSalary, NewSalaryDto> func = new Function<NewSalary, NewSalaryDto>() {
            @Override
            public NewSalaryDto apply(NewSalary t) {
                // 将实体类转换成DTO
                NewSalaryDto newSalaryDto = newSalaryMapper.toDto(t);
                // 根据用户ID查询用户信息
                User user = userRepository.findById(newSalaryDto.getUserId()).orElseGet(User::new);
                ValidationUtil.isNull(user.getId(), "User", "id", newSalaryDto.getUserId());
                // 用户昵称
                newSalaryDto.setUserNickName(user.getNickName());
                // 返回处理好的DTO
                return newSalaryDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<NewSalaryDto> queryAll(NewSalaryQueryCriteria criteria) {
        return newSalaryMapper.toDto(newSalaryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    @Override
    @Transactional
    public NewSalaryDto findById(Long id) {
        NewSalary newSalary = newSalaryRepository.findById(id).orElseGet(NewSalary::new);
        ValidationUtil.isNull(newSalary.getId(), "NewSalary", "id", id);
        return newSalaryMapper.toDto(newSalary);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public NewSalaryDto create(NewSalary resources) {
        // 根据用户ID和工资年月查询
        List<NewSalary> newSalaryList = newSalaryRepository.findByUserIdAndSalaryYearMonth(resources.getUserId(), resources.getSalaryYearMonth());
        // 判断列表长度
        if (newSalaryList.size() > 0) {
            throw new BadRequestException("找到相同用户相同年月的工资记录!");
        }
//        NewSalary savedSalary = newSalaryRepository.save(resources);
//        if (savedSalary.getId() != null) {
//            // 保存成功
//        } else {
//            // 保存失败
//            Prin
//        }
        return newSalaryMapper.toDto(newSalaryRepository.save(resources));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(NewSalary resources) {
        // 根据用户ID和工资年月查询
        List<NewSalary> newSalaryList = newSalaryRepository.findByUserIdAndSalaryYearMonth(resources.getUserId(), resources.getSalaryYearMonth());
        // 判断列表长度
        if (newSalaryList.size() > 1) {
            throw new BadRequestException("找到相同用户相同年月的工资记录!");
        } else if (newSalaryList.size() == 1) {
            // 判断是否是同一条记录
            if (newSalaryList.get(0).getId().longValue() != resources.getId().longValue()) {
                throw new BadRequestException("找到相同用户相同年月的工资记录!");
            }
        }
        NewSalary newSalary = newSalaryRepository.findById(resources.getId()).orElseGet(NewSalary::new);
        // 判断承认状态
        if (Constant.APPROVE_STATUS_ACKNOWLEDGED.equals(newSalary.getApproveStatus())) {
            throw new BadRequestException("已承认的工资记录无法进行修改!");
        }
        ValidationUtil.isNull(newSalary.getId(), "Salary", "id", resources.getId());
        newSalary.copy(resources);
        newSalaryRepository.save(newSalary);
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            newSalaryRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<NewSalaryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (NewSalaryDto newSalaryDto : all) {
            String userNickName = newSalaryDto.getUserId() != null ? userRepository.findById(newSalaryDto.getUserId()).orElseGet(User::new).getNickName() : "";
            String publicityStatus = newSalaryDto.getPublicityStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.PUBLICITY_STATUS, newSalaryDto.getPublicityStatus()).getLabel() : "";
            String approveStatus = newSalaryDto.getApproveStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.APPROVE_STATUS, newSalaryDto.getApproveStatus()).getLabel() : "";
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("员工姓名", userNickName);
            map.put("工资年月", newSalaryDto.getSalaryYearMonth().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM")));
            map.put("基本工资", newSalaryDto.getBasicWage());
            map.put("全勤小时数", newSalaryDto.getFullDays());
            map.put("缺勤小时数", newSalaryDto.getAbsenceDays());
            map.put("实际基础工资", newSalaryDto.getActualBasicWage());
            map.put("其他补助", newSalaryDto.getTravelAllowance().add(newSalaryDto.getOvertimeAllowance()));
//            map.put("绩效工资", newSalaryDto.getAchievementsWage());
//            map.put("应完成绩效工时", newSalaryDto.getNeedCompletedAchievementsHours());
//            map.put("已完成绩效工时", newSalaryDto.getAlreadyCompletedAchievementsHours());
//            map.put("实际绩效工资", newSalaryDto.getActualAchievementsWage());
//            map.put("业绩工资", newSalaryDto.getPerformanceWage());
//            map.put("应完成业绩工时", newSalaryDto.getNeedCompletedPerformanceHours());
//            map.put("已完成业绩工时", newSalaryDto.getAlreadyCompletedPerformanceHours());
//            map.put("实际业绩工资", newSalaryDto.getActualPerformanceWage());
//            map.put("团队工资", newSalaryDto.getTeamWage());
//            map.put("实达标团队工时", newSalaryDto.getActualComplianceTeamHours());
//            map.put("已完成团队工时", newSalaryDto.getAlreadyCompletedTeamHours());
//            map.put("实际团队工资", newSalaryDto.getActualTeamWage());
            map.put("公积金基数", newSalaryDto.getAccumulationFund());
            map.put("公积金个人缴纳比例", newSalaryDto.getAccumulationFundPersonal());
            map.put("公积金个人缴纳金额", newSalaryDto.getAccumulationFundPersonalAmount());
            map.put("公积金公司缴纳比例", newSalaryDto.getAccumulationFundCompany());
            map.put("公积金公司缴纳金额", newSalaryDto.getAccumulationFundCompanyAmount());
            map.put("养老险基数", newSalaryDto.getRetirementInsurance());
            map.put("养老险个人缴纳比例", newSalaryDto.getRetirementInsurancePersonal());
            map.put("养老险个人缴纳金额", newSalaryDto.getRetirementInsurancePersonalAmount());
            map.put("养老险公司缴纳比例", newSalaryDto.getRetirementInsuranceCompany());
            map.put("养老险公司缴纳金额", newSalaryDto.getRetirementInsuranceCompanyAmount());
            map.put("医疗险基数", newSalaryDto.getMedicalInsurance());
            map.put("医疗险个人缴纳比例", newSalaryDto.getMedicalInsurancePersonal());
            map.put("医疗险个人缴纳金额", newSalaryDto.getMedicalInsurancePersonalAmount());
            map.put("医疗险公司缴纳比例", newSalaryDto.getMedicalInsuranceCompany());
            map.put("医疗险公司缴纳金额", newSalaryDto.getMedicalInsuranceCompanyAmount());
            map.put("失业险基数", newSalaryDto.getUnemploymentInsurance());
            map.put("失业险个人缴纳比例", newSalaryDto.getUnemploymentInsurancePersonal());
            map.put("失业险个人缴纳金额", newSalaryDto.getUnemploymentInsurancePersonalAmount());
            map.put("失业险公司缴纳比例", newSalaryDto.getUnemploymentInsuranceCompany());
            map.put("失业险公司缴纳金额", newSalaryDto.getUnemploymentInsuranceCompanyAmount());
            map.put("生育险基数", newSalaryDto.getBirthInsurance());
            map.put("生育险个人缴纳比例", newSalaryDto.getBirthInsurancePersonal());
            map.put("生育险个人缴纳金额", newSalaryDto.getBirthInsurancePersonalAmount());
            map.put("生育险公司缴纳比例", newSalaryDto.getBirthInsuranceCompany());
            map.put("生育险公司缴纳金额", newSalaryDto.getBirthInsuranceCompanyAmount());
            map.put("工伤险基数", newSalaryDto.getEmploymentInsurance());
            map.put("工伤险个人缴纳比例", newSalaryDto.getEmploymentInsurancePersonal());
            map.put("工伤险个人缴纳金额", newSalaryDto.getEmploymentInsurancePersonalAmount());
            map.put("工伤险公司缴纳比例", newSalaryDto.getEmploymentInsuranceCompany());
            map.put("工伤险公司缴纳金额", newSalaryDto.getEmploymentInsuranceCompanyAmount());
            map.put("税前金额", newSalaryDto.getPreTaxAmount());
            map.put("个人所得税", newSalaryDto.getIndividualIncomeTax());
            map.put("税后金额", newSalaryDto.getAfterTaxAmount());
            map.put("备注", newSalaryDto.getRemarks());
            map.put("公示状态", publicityStatus);
            map.put("承认状态", approveStatus);
            map.put("创建者", newSalaryDto.getCreateBy());
            map.put("创建时间", newSalaryDto.getCreateTime());
            map.put("更新者", newSalaryDto.getUpdateBy());
            map.put("更新时间", newSalaryDto.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public Integer queryWorkDays(NewSalaryQueryCriteria criteria) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (criteria.getUserId() == null) {
            return 0;
        }
//        User user = userRepository.findById(criteria.getUserId()).orElseGet(User::new);
//        // 员工的创建时间
//        String stTime = sdf.format(user.getCreateTime()).substring(0, 7);
//
//        if (stTime.equals(criteria.getTargetYearMonth().substring(0, 7))) {
//            criteria.setTargetYearMonth(sdf.format(user.getCreateTime()).substring(0, 10));
//        }
        // 国际时间转中国时间
        String targetYearMonth = criteria.getTargetYearMonth();
        // 节日查询类
        SysConfigHolidayQueryCriteria sysConfigHolidayQueryCriteria = new SysConfigHolidayQueryCriteria();
        sysConfigHolidayQueryCriteria.setHolidayDateLike(targetYearMonth.substring(0, 7));
        // 获取某月节日数据
        List<SysConfigHoliday> sysConfigHolidayList = sysConfigHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, sysConfigHolidayQueryCriteria, criteriaBuilder));
        // 查询某月工作天数
        return DateUtil.getWorkDayOfMonth(sysConfigHolidayList, targetYearMonth);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publicity(Long[] ids) {
        // 循环ID列表
        for (Long id : ids) {
            // 查询工资
            NewSalary newSalary = newSalaryRepository.findById(id).orElseGet(NewSalary::new);
            ValidationUtil.isNull(newSalary.getId(), "Salary", "id", id);
            // 公示状态
            newSalary.setPublicityStatus(Constant.PUBLICITY_STATUS_YES);
            // 保存
            newSalaryRepository.save(newSalary);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(Long[] ids) {
        // 循环ID列表
        for (Long id : ids) {
            // 查询工资
            NewSalary newSalary = newSalaryRepository.findById(id).orElseGet(NewSalary::new);
            ValidationUtil.isNull(newSalary.getId(), "Salary", "id", id);
            // 承认状态
            newSalary.setApproveStatus(Constant.APPROVE_STATUS_ACKNOWLEDGED);
            // 保存
            newSalaryRepository.save(newSalary);
        }
    }
    @Override
    public void generate(NewSalaryQueryCriteria criteria) {
        List<String> errors = new ArrayList<>();
        // 用户检索类
        UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
        userQueryCriteria.setEnabled(true);
        if (criteria.getSelectedValue1() != null) {
            userQueryCriteria.setUserIds(criteria.getSelectedValue1());
        }
        // 获取用户列表
        List<UserSmallDto> userDtoList = userService.querySmallAll(userQueryCriteria);
        // 循环用户列表
        for (int i = 0; i < userDtoList.size(); i++) {
            try {
                // 单个用户工资结算
                singleUserSalarySettlement(userDtoList.get(i).getId(), criteria.getTargetYearMonth(), errors);
            } catch (Exception e) {
                // 跳过本次循环
                continue;
            }
        }
        // 在循环结束后处理错误
        if (!errors.isEmpty()) {
            // 将所有的错误信息收集到一个字符串中
            String errorMessage = String.join("; ", errors);
            // 抛出一个新的异常
            throw new RuntimeException(errorMessage);
        }
    }
    @Override
    public Double getMeritWage(Double completedAchievementsHoursRate, Long level) {
        //获取到当前这个级别的业绩工资
        MeritWage meritWage = meritWageRepository.findByLevelId(level);
        //根据业绩工资去查一下当前这个等级的业绩工资下分几个等级
        List<MeritLevel> meritLevelList = meritLevelRepository.findByMeritWageId(meritWage.getId());
        Double resultMoney = 0D;
        for (MeritLevel meritLevel : meritLevelList) {
            if (completedAchievementsHoursRate >= meritLevel.getMeritStandard()) {
                resultMoney = meritLevel.getMeritMoney();
            }
        }
        return resultMoney;
    }
    // 单个用户工资结算
    private void singleUserSalarySettlement(Long userId, String targetYearMonth, List<String> errors) {
        // 工资实体类
        NewSalary newSalary = new NewSalary();
        newSalary.setUserId(userId);
        Timestamp salaryYearMonth = Timestamp.valueOf(LocalDate.parse(targetYearMonth, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay());
        newSalary.setSalaryYearMonth(salaryYearMonth);
        newSalary.setPublicityStatus(Constant.PUBLICITY_STATUS_NOT);
        newSalary.setApproveStatus(Constant.APPROVE_STATUS_UNRECOGNIZED);
        try {
            // 获取出差补助
            newSalary = getUserBussSubsidy(userId, targetYearMonth, newSalary);
//            // 获取加班补助工资  旧加班暂时废止
//            newSalary = getUserOverTimeSubsidy(userId, targetYearMonth, newSalary);
            // 获取用户级别工资
            newSalary = getUserLevelWage(userId, targetYearMonth, newSalary, errors);
//            // 获取用户级别其他(旧版,新版无个人业绩比例字段)
//            newSalary = getUserLevelOther(userId, targetYearMonth, newSalary);
            // 获取工作天数
            newSalary = getWorkDays(targetYearMonth, newSalary);
            // 平日加班费(含3倍工资)
            newSalary = getNormalOverTimeWage(userId, targetYearMonth, newSalary);
            // 获取出勤小时数
            newSalary = getAttendanceHours(userId, targetYearMonth, newSalary);
//            // 获取已完成工时
//            newSalary = getCompletedWork(userId, targetYearMonth, newSalary);
            // 获取用户级别保险
            newSalary = getUserLevelInsurance(userId, targetYearMonth, newSalary);
        } catch (BadRequestException | ParseException e) {
            errors.add(e.getMessage());
            return;
        } catch (Exception e) {
            return;
        }
        List<NewSalary> oldNewSalaryList = newSalaryRepository.findByUserIdAndSalaryYearMonth(userId, salaryYearMonth);
        if (oldNewSalaryList.size() > 0) {
            for (NewSalary oldNewSalary : oldNewSalaryList) {
                oldNewSalary.copy(newSalary);
                newSalaryRepository.save(oldNewSalary);
            }
        } else {
            newSalaryRepository.save(newSalary);
        }
    }
    // 获取平日加班费
    private NewSalary getNormalOverTimeWage(Long userId, String targetYearMonth, NewSalary newSalary) throws ParseException {
        // 考勤查询类
        AttendanceQueryCriteria attendanceQueryCriteria = new AttendanceQueryCriteria();
        attendanceQueryCriteria.setUserId(userId);
        attendanceQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询某月平日加班小时数
        Double attendanceHours = attendanceService.queryAttendanceOverTimeHours(attendanceQueryCriteria);
        // 查询某月节假日加班小时数
        Double attendanceHolidayHours = attendanceService.queryAttendanceHolidaysOverTimeHours(attendanceQueryCriteria);
        UserLevelWageQueryCriteria criteria = new UserLevelWageQueryCriteria();
        criteria.setUserId(userId);
        criteria.setTargetYearMonth(targetYearMonth);
        UserLevelWageDto userLevelWageDto = userLevelWageService.queryTargetYearMonth(criteria);
        // 平日加班费
        if (userLevelWageDto.getOverTimeWage() != null) {
//            System.out.println("用户" + userId + "的级别工资中平日加班时间" + attendanceHours + "小时,配置加班费用为:" + userLevelWageDto.getOverTimeWage() + "元/小时!");
            newSalary.setOvertimeAllowance(userLevelWageDto.getOverTimeWage().multiply(BigDecimal.valueOf(attendanceHours)));
//            System.out.println(newSalary.getOvertimeAllowance() + "元");
        } else {
            newSalary.setOvertimeAllowance(newSalary.getBasicWage().multiply(BigDecimal.valueOf(attendanceHours)).divide(BigDecimal.valueOf(newSalary.getFullDays()), 2, RoundingMode.HALF_UP));
        }
        // 节假日加班费
        newSalary.setOvertimeAllowance(newSalary.getOvertimeAllowance().add(newSalary.getBasicWage().multiply(BigDecimal.valueOf(attendanceHolidayHours)).multiply(BigDecimal.valueOf(3)).divide(BigDecimal.valueOf(21.75), 2, RoundingMode.HALF_UP)));
        // 税前工资累计
        newSalary.setPreTaxAmount(newSalary.getPreTaxAmount().add(newSalary.getOvertimeAllowance()));
        // 返回
        return newSalary;
    }
    // 获取用户级别工资
    private NewSalary getUserLevelWage(Long userId, String targetYearMonth, NewSalary newSalary, List<String> errors) {
        // 用户级别工资检索类
        UserLevelWageQueryCriteria userLevelWageQueryCriteria = new UserLevelWageQueryCriteria();
        userLevelWageQueryCriteria.setUserId(userId);
        userLevelWageQueryCriteria.setTargetYearMonth(targetYearMonth);
        try {
            Double coefficient = 1.0;
            UserDto userDto = userService.findById(userId);
            LocalDate createDate = userDto.getCreateTime().toLocalDateTime().toLocalDate();
            if (userDto.getInternshipTime() != null) {
                LocalDate localDate1 = createDate.plusMonths(userDto.getInternshipTime()).withDayOfMonth(1);
                LocalDate localDate2 = LocalDate.parse(targetYearMonth, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                if (localDate1.isAfter(localDate2)) {
                    coefficient = 0.8;
                }
            }
            // 查询指定年月用户级别工资
            UserLevelWageDto userLevelWageDto = userLevelWageService.queryTargetYearMonth(userLevelWageQueryCriteria);
            // 级别基本工资
            BigDecimal basicWage = userLevelWageDto.getBasicWage().multiply(BigDecimal.valueOf(coefficient));
            // 级别等级工资
            BigDecimal rankWage = userLevelWageDto.getRankWage().multiply(BigDecimal.valueOf(coefficient));
            // 绩效工资
            BigDecimal performanceWage = userLevelWageDto.getPerformanceWage().multiply(BigDecimal.valueOf(coefficient));
            // 设置工资条的基本工资
            newSalary.setBasicWage(basicWage.add(rankWage).add(performanceWage));
            // 设置工资条的绩效工资
            newSalary.setAchievementsWage(BigDecimal.ZERO);
            // 设置工资条的业绩工资
            newSalary.setPerformanceWage(BigDecimal.ZERO);
            // 设置工资条实际业绩工资
            newSalary.setActualPerformanceWage(BigDecimal.ZERO);
            // 设置工资条的团队工资
            newSalary.setTeamWage(BigDecimal.ZERO);
        } catch (RuntimeException | ParseException e) {
            errors.add(e.getMessage());
            return null;
        }
        // 返回
        return newSalary;
    }
    // 获取出差补助
    private NewSalary getUserBussSubsidy(Long userId, String targetYearMonth, NewSalary newSalary) throws ParseException {
        // 用户级别工资检索类
        UserLevelWageQueryCriteria userLevelWageQueryCriteria = new UserLevelWageQueryCriteria();
        userLevelWageQueryCriteria.setUserId(userId);
        userLevelWageQueryCriteria.setTargetYearMonth(targetYearMonth + " 00:00:00");
        // 获取出差补助金额
        Double bussMoney = userLevelWageService.queryTravelAllowance(userLevelWageQueryCriteria);
        // 设置出差补助的金额
        newSalary.setTravelAllowance(new BigDecimal(bussMoney));
        // 税前工资累计
        newSalary.setPreTaxAmount(newSalary.getPreTaxAmount().add(newSalary.getTravelAllowance()));
        return newSalary;
    }
//    // 获取加班补助工资
//    private NewSalary getUserOverTimeSubsidy(Long userId, String targetYearMonth, NewSalary newSalary) throws ParseException {
//        // 用户级别工资检索类
//        UserLevelWageQueryCriteria userLevelWageQueryCriteria = new UserLevelWageQueryCriteria();
//        userLevelWageQueryCriteria.setUserId(userId);
//        userLevelWageQueryCriteria.setTargetYearMonth(targetYearMonth + " 00:00:00");
//        // 获取加班补助金额
//        Double overTimeMoney = userLevelWageService.queryOverTimeAllowance(userLevelWageQueryCriteria);
//        // 设置加班补助的金额
//        newSalary.setOvertimeAllowance(new BigDecimal(overTimeMoney));
//        return newSalary;
//    }
    // 获取用户级别保险
    private NewSalary getUserLevelInsurance(Long userId, String targetYearMonth, NewSalary newSalary) throws ParseException {
        UserDto userDto = userService.findById(userId);
        LocalDate createDate = userDto.getCreateTime().toLocalDateTime().toLocalDate();
        if (userDto.getInternshipTime() != null) {
            LocalDate localDate1 = createDate.plusMonths(userDto.getInternshipTime()).withDayOfMonth(1);
            LocalDate localDate2 = LocalDate.parse(targetYearMonth, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (localDate1.isAfter(localDate2)) {
                // 税前工资累计
                newSalary.setAfterTaxAmount(newSalary.getPreTaxAmount());
                return newSalary;
            }
        }
        // 用户级别保险查询类
        UserInsuranceQueryCriteria criteria = new UserInsuranceQueryCriteria();
        criteria.setUserId(userId);
        criteria.setTargetYearMonth(targetYearMonth);
        // 查询指定年月用户级别保险
        UserInsuranceDto userInsuranceDto = userInsuranceService.queryTargetYearMonth(criteria);
        // 公积金基数
        newSalary.setAccumulationFund(userInsuranceDto.getAccumulationFund());
        // 公积金个人缴纳比例
        newSalary.setAccumulationFundPersonal(userInsuranceDto.getAccumulationFundPersonal());
        // 公积金个人缴纳金额
        newSalary.setAccumulationFundPersonalAmount(userInsuranceDto.getAccumulationFund().multiply(new BigDecimal(userInsuranceDto.getAccumulationFundPersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 公积金公司缴纳比例
        newSalary.setAccumulationFundCompany(userInsuranceDto.getAccumulationFundCompany());
        // 公积金公司缴纳金额
        newSalary.setAccumulationFundCompanyAmount(userInsuranceDto.getAccumulationFund().multiply(new BigDecimal(userInsuranceDto.getAccumulationFundCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 养老险基数
        newSalary.setRetirementInsurance(userInsuranceDto.getRetirementInsurance());
        // 养老险个人缴纳比例
        newSalary.setRetirementInsurancePersonal(userInsuranceDto.getRetirementInsurancePersonal());
        // 养老险个人缴纳金额
        newSalary.setRetirementInsurancePersonalAmount(userInsuranceDto.getRetirementInsurance().multiply(new BigDecimal(userInsuranceDto.getRetirementInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 养老险公司缴纳比例
        newSalary.setRetirementInsuranceCompany(userInsuranceDto.getRetirementInsuranceCompany());
        // 养老险公司缴纳金额
        newSalary.setRetirementInsuranceCompanyAmount(userInsuranceDto.getRetirementInsurance().multiply(new BigDecimal(userInsuranceDto.getRetirementInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 医疗险基数
        newSalary.setMedicalInsurance(userInsuranceDto.getMedicalInsurance());
        // 医疗险个人缴纳比例
        newSalary.setMedicalInsurancePersonal(userInsuranceDto.getMedicalInsurancePersonal());
        // 医疗险个人缴纳金额
        newSalary.setMedicalInsurancePersonalAmount(userInsuranceDto.getMedicalInsurance().multiply(new BigDecimal(userInsuranceDto.getMedicalInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 医疗险公司缴纳比例
        newSalary.setMedicalInsuranceCompany(userInsuranceDto.getMedicalInsuranceCompany());
        // 医疗险公司缴纳金额
        newSalary.setMedicalInsuranceCompanyAmount(userInsuranceDto.getMedicalInsurance().multiply(new BigDecimal(userInsuranceDto.getMedicalInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 失业险基数
        newSalary.setUnemploymentInsurance(userInsuranceDto.getUnemploymentInsurance());
        // 失业险个人缴纳比例
        newSalary.setUnemploymentInsurancePersonal(userInsuranceDto.getUnemploymentInsurancePersonal());
        // 失业险个人缴纳金额
        newSalary.setUnemploymentInsurancePersonalAmount(userInsuranceDto.getUnemploymentInsurance().multiply(new BigDecimal(userInsuranceDto.getUnemploymentInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 失业险公司缴纳比例
        newSalary.setUnemploymentInsuranceCompany(userInsuranceDto.getUnemploymentInsuranceCompany());
        // 失业险公司缴纳金额
        newSalary.setUnemploymentInsuranceCompanyAmount(userInsuranceDto.getUnemploymentInsurance().multiply(new BigDecimal(userInsuranceDto.getUnemploymentInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 生育险基数
        newSalary.setBirthInsurance(userInsuranceDto.getBirthInsurance());
        // 生育险个人缴纳比例
        newSalary.setBirthInsurancePersonal(userInsuranceDto.getBirthInsurancePersonal());
        // 生育险个人缴纳金额
        newSalary.setBirthInsurancePersonalAmount(userInsuranceDto.getBirthInsurance().multiply(new BigDecimal(userInsuranceDto.getBirthInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 生育险公司缴纳比例
        newSalary.setBirthInsuranceCompany(userInsuranceDto.getBirthInsuranceCompany());
        // 生育险公司缴纳金额
        newSalary.setBirthInsuranceCompanyAmount(userInsuranceDto.getBirthInsurance().multiply(new BigDecimal(userInsuranceDto.getBirthInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 工伤险基数
        newSalary.setEmploymentInsurance(userInsuranceDto.getEmploymentInsurance());
        // 工伤险个人缴纳比例
        newSalary.setEmploymentInsurancePersonal(userInsuranceDto.getEmploymentInsurancePersonal());
        // 工伤险个人缴纳金额
        newSalary.setEmploymentInsurancePersonalAmount(userInsuranceDto.getEmploymentInsurance().multiply(new BigDecimal(userInsuranceDto.getEmploymentInsurancePersonal())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 工伤险公司缴纳比例
        newSalary.setEmploymentInsuranceCompany(userInsuranceDto.getEmploymentInsuranceCompany());
        // 工伤险公司缴纳金额
        newSalary.setEmploymentInsuranceCompanyAmount(userInsuranceDto.getEmploymentInsurance().multiply(new BigDecimal(userInsuranceDto.getEmploymentInsuranceCompany())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 税前工资累计
        newSalary.setAfterTaxAmount(newSalary.getPreTaxAmount()
            // 公积金个人缴纳金额
            .subtract(newSalary.getAccumulationFundPersonalAmount())
            // 养老险个人缴纳金额
            .subtract(newSalary.getRetirementInsurancePersonalAmount())
            // 医疗险个人缴纳金额
            .subtract(newSalary.getMedicalInsurancePersonalAmount())
            // 失业险个人缴纳金额
            .subtract(newSalary.getUnemploymentInsurancePersonalAmount())
            // 生育险个人缴纳金额
            .subtract(newSalary.getBirthInsurancePersonalAmount())
            // 工伤险个人缴纳金额
            .subtract(newSalary.getEmploymentInsurancePersonalAmount())
        );
        // 返回
        return newSalary;
    }
    // 获取用户级别其他
    private NewSalary getUserLevelOther(Long userId, String targetYearMonth, NewSalary newSalary) {
        // 用户级别其他查询类
        SysUserLevelOtherQueryCriteria sysUserLevelOtherQueryCriteria = new SysUserLevelOtherQueryCriteria();
        sysUserLevelOtherQueryCriteria.setUserId(userId);
        sysUserLevelOtherQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询指定年月用户级别其他(旧版,新版无个人业绩比例字段)
        SysUserLevelOtherDto sysUserLevelOtherDto = sysUserLevelOtherService.queryTargetYearMonth(sysUserLevelOtherQueryCriteria);
        // 个人业绩比例(旧版,新版无个人业绩比例字段)
//        newSalary.setPersonalPerformanceProportion(sysUserLevelOtherDto.getPersonalPerformanceProportion());
        // 返回
        return newSalary;
    }
    // 获取工作天数
    private NewSalary getWorkDays(String targetYearMonth, NewSalary newSalary) {
        // 工资查询类
        NewSalaryQueryCriteria newSalaryQueryCriteria = new NewSalaryQueryCriteria();
        newSalaryQueryCriteria.setUserId(newSalary.getUserId());
        newSalaryQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询某月工作天数
        Integer workDays = queryWorkDays(newSalaryQueryCriteria);
        // 全勤小时数
        newSalary.setFullDays(Double.valueOf(workDays * 8));
        // 应完成绩效工时
        newSalary.setNeedCompletedAchievementsHours(Double.valueOf(workDays * 8));
//        newSalary.setNeedCompletedPerformanceHours(Double.valueOf(workDays * 8 * 1.1));
        // 返回
        return newSalary;
    }
    // 获取出勤小时数
    private NewSalary getAttendanceHours(Long userId, String targetYearMonth, NewSalary newSalary) {
        // 考勤查询类
        AttendanceQueryCriteria attendanceQueryCriteria = new AttendanceQueryCriteria();
        attendanceQueryCriteria.setUserId(userId);
        attendanceQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询某月出勤小时数
        Double attendanceHours = attendanceService.queryAttendanceHours(attendanceQueryCriteria);
        // 缺勤小时数
        newSalary.setAbsenceDays(newSalary.getFullDays() > attendanceHours ? Double.valueOf(newSalary.getFullDays() - attendanceHours) : 0);
        // 缺勤小时数
        BigDecimal absenceDays = new BigDecimal(newSalary.getAbsenceDays());
        // 实际基础工资
        newSalary.setActualBasicWage(newSalary.getBasicWage().subtract(newSalary.getBasicWage().multiply(absenceDays).divide(new BigDecimal(newSalary.getFullDays()), 2, RoundingMode.HALF_UP)));
        // 税前工资累计
        newSalary.setPreTaxAmount(newSalary.getPreTaxAmount().add(newSalary.getActualBasicWage()));
        // 返回
        return newSalary;
    }
    // 获取达标工时
    private NewSalary getComplianceWork(Long userId, String targetYearMonth, NewSalary newSalary) {
        // 任务日报查询类
        ProjectPerformanceDetailQueryCriteria taskDaliyQueryCriteria = new ProjectPerformanceDetailQueryCriteria();
        taskDaliyQueryCriteria.setUserId(userId);
        taskDaliyQueryCriteria.setYearMonth(Timestamp.valueOf(targetYearMonth + " 00:00:00"));
        // 查询某月已达标工时
        Double complianceWork = projectPerformanceDetailService.queryComplianceWork(taskDaliyQueryCriteria);
        // 实达标团队工时
        newSalary.setActualComplianceTeamHours(complianceWork);
        // 返回
        return newSalary;
    }
    // 获取已完成工时
    private NewSalary getCompletedWork(Long userId, String targetYearMonth, NewSalary newSalary) {
        // 任务日报查询类
        TaskDaliyQueryCriteria taskDaliyQueryCriteria = new TaskDaliyQueryCriteria();
        taskDaliyQueryCriteria.setUserId(userId);
        taskDaliyQueryCriteria.setTargetYearMonth(targetYearMonth);
        // 查询某月已完成工时
        Double completedWork = taskDaliyService.queryCompletedWork(taskDaliyQueryCriteria, false);
        // 已完成绩效工时
        newSalary.setAlreadyCompletedAchievementsHours(completedWork);
//        // 已完成业绩工时
//        newSalary.setAlreadyCompletedPerformanceHours(completedWork);
//        // 已完成团队工时
//        newSalary.setAlreadyCompletedTeamHours(completedWork);
        Double otherWage = taskDaliyService.queryOtherWage(taskDaliyQueryCriteria);
        newSalary.setPieceRate(BigDecimal.valueOf(otherWage));
        // 绩效定时器
        while (true) {
            // 判断预计绩效工资、应完成绩效工时是否为空
            if (newSalary.getAchievementsWage() != null && newSalary.getNeedCompletedAchievementsHours() != null) {
                // 实际绩效工资
                newSalary.setActualAchievementsWage(newSalary.getAchievementsWage().multiply(new BigDecimal(completedWork)).divide(new BigDecimal(newSalary.getNeedCompletedAchievementsHours())));
                // 清空绩效定时器
                break;
            }
        }
        // 业绩定时器
        while (true) {
            // 判断预计业绩工资、应完成业绩工时是否为空
            if (newSalary.getPerformanceWage() != null && newSalary.getNeedCompletedPerformanceHours() != null) {
                // 实际业绩工资
                newSalary.setActualPerformanceWage(completedWork >= newSalary.getNeedCompletedPerformanceHours() ? newSalary.getPerformanceWage() : new BigDecimal(0));
            }
            // 清空业绩定时器
            break;
        }
//        // 团队定时器
//        while (true) {
//            // 判断预计团队工资、实达标团队工时是否为空
//            if (newSalary.getTeamWage() != null && newSalary.getActualComplianceTeamHours() != null) {
//                // 实际团队工资
//                newSalary.setActualTeamWage(newSalary.getActualComplianceTeamHours() != 0 ? newSalary.getTeamWage().multiply(new BigDecimal(newSalary.getActualComplianceTeamHours() / completedWork)) : new BigDecimal(0));
//                // 清空团队定时器
//                break;
//            }
//        }
        // 统计定时器
        while (true) {
            // 判断 实际基础工资、实际绩效工资、实际业绩工资、实际团队工资、公积金个人缴纳金额、养老险个人缴纳金额、
            // 医疗险个人缴纳金额、失业险个人缴纳金额、生育险个人缴纳金额、工伤险个人缴纳金额 是否为空
            if (
                    newSalary.getActualBasicWage() != null &&
                            newSalary.getActualAchievementsWage() != null &&
                            newSalary.getActualPerformanceWage() != null &&
                            newSalary.getActualTeamWage() != null &&
                            newSalary.getAccumulationFundPersonalAmount() != null &&
                            newSalary.getRetirementInsurancePersonalAmount() != null &&
                            newSalary.getMedicalInsurancePersonalAmount() != null &&
                            newSalary.getUnemploymentInsurancePersonalAmount() != null &&
                            newSalary.getBirthInsurancePersonalAmount() != null &&
                            newSalary.getEmploymentInsurancePersonalAmount() != null
            ) {
                // 税前金额
                newSalary.setPreTaxAmount(newSalary.getActualBasicWage().add(newSalary.getActualAchievementsWage()).add(newSalary.getActualPerformanceWage()).add(newSalary.getActualTeamWage()));
                // 查询个人所得税列表
                List<SysConfigIndividualIncomeTaxDto> sysConfigIndividualIncomeTaxDtoList = sysConfigIndividualIncomeTaxService.queryAll(new SysConfigIndividualIncomeTaxQueryCriteria());
                // 税额
                BigDecimal taxAmount = new BigDecimal(0);
                // 计税金额
                BigDecimal taxableAmount = newSalary.getPreTaxAmount().subtract(newSalary.getAccumulationFundPersonalAmount()).subtract(newSalary.getRetirementInsurancePersonalAmount())
                        .subtract(newSalary.getMedicalInsurancePersonalAmount()).subtract(newSalary.getUnemploymentInsurancePersonalAmount()).subtract(newSalary.getBirthInsurancePersonalAmount())
                        .subtract(newSalary.getEmploymentInsurancePersonalAmount());
                // 循环个人所得税列表
                for (int i = 0; i < sysConfigIndividualIncomeTaxDtoList.size(); i++) {
                    // 判断计税金额所在个人所得税范围
                    if (sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd() != null &&
                            taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd()) == 1) {
                        // 税额
                        taxAmount.add(
                                (sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd().subtract(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountStart()))
                                        .multiply(new BigDecimal(sysConfigIndividualIncomeTaxDtoList.get(i).getTaxRate()).divide(new BigDecimal(100)))
                        );
                    } else if (
                            (taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountStart()) == 1 ||
                                    taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountStart()) == 0) &&
                                    (sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd() == null ||
                                            taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd()) == -1 ||
                                            taxableAmount.compareTo(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountEnd()) == 0)
                    ) {
                        // 税额
                        taxAmount.add(
                                (taxableAmount.subtract(sysConfigIndividualIncomeTaxDtoList.get(i).getGearAmountStart()))
                                        .multiply(new BigDecimal(sysConfigIndividualIncomeTaxDtoList.get(i).getTaxRate()).divide(new BigDecimal(100)))
                        );
                    }
                    // 判断循环是否结束
                    if (i == sysConfigIndividualIncomeTaxDtoList.size() - 1) {
                        // 个人所得税
//                        newSalary.setIndividualIncomeTax(taxAmount);
                        newSalary.setIndividualIncomeTax(new BigDecimal(0));
                        // 税后金额
                        newSalary.setAfterTaxAmount(taxableAmount.subtract(taxAmount).compareTo(new BigDecimal(0)) == -1 ? new BigDecimal(0) : taxableAmount.subtract(taxAmount));
                    }
                }
                // 清空统计定时器
                break;
            }
        }
        // 返回
        return newSalary;
    }
    // ==================== 以上为定时生成工资记录主要逻辑 ====================
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/domain/Dict.java
@@ -1,54 +1,54 @@
/*
 *  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.system.domain;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import me.zhengjie.base.BaseEntity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
/**
* @author Zheng Jie
* @date 2019-04-10
*/
@Entity
@Getter
@Setter
@Table(name="sys_dict")
public class Dict extends BaseEntity implements Serializable {
    @Id
    @Column(name = "dict_id")
    @NotNull(groups = Update.class)
    @ApiModelProperty(value = "ID", hidden = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @OneToMany(mappedBy = "dict",cascade={CascadeType.PERSIST,CascadeType.REMOVE})
    private List<DictDetail> dictDetails;
    @NotBlank
    @ApiModelProperty(value = "名称")
    private String name;
    @ApiModelProperty(value = "描述")
    private String description;
/*
 *  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.system.domain;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import me.zhengjie.base.BaseEntity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
/**
* @author Zheng Jie
* @date 2019-04-10
*/
@Entity
@Getter
@Setter
@Table(name="sys_dict")
public class Dict extends BaseEntity implements Serializable {
    @Id
    @Column(name = "dict_id")
    @NotNull(groups = Update.class)
    @ApiModelProperty(value = "ID", hidden = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @OneToMany(mappedBy = "dict", fetch = FetchType.EAGER, cascade={CascadeType.PERSIST,CascadeType.REMOVE})
    private List<DictDetail> dictDetails;
    @NotBlank
    @ApiModelProperty(value = "名称")
    private String name;
    @ApiModelProperty(value = "描述")
    private String description;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/repository/DictRepository.java
@@ -1,43 +1,45 @@
/*
 *  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.system.repository;
import me.zhengjie.modules.system.domain.Dict;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
import java.util.Set;
/**
* @author Zheng Jie
* @date 2019-04-10
*/
public interface DictRepository extends JpaRepository<Dict, Long>, JpaSpecificationExecutor<Dict> {
    /**
     * 删除
     * @param ids /
     */
    void deleteByIdIn(Set<Long> ids);
    /**
     * 查询
     * @param ids /
     * @return /
     */
    List<Dict> findByIdIn(Set<Long> ids);
/*
 *  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.system.repository;
import me.zhengjie.modules.system.domain.Dict;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
import java.util.Set;
/**
* @author Zheng Jie
* @date 2019-04-10
*/
public interface DictRepository extends JpaRepository<Dict, Long>, JpaSpecificationExecutor<Dict> {
    Dict findByName(String name);
    /**
     * 删除
     * @param ids /
     */
    void deleteByIdIn(Set<Long> ids);
    /**
     * 查询
     * @param ids /
     * @return /
     */
    List<Dict> findByIdIn(Set<Long> ids);
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/UserServiceImpl.java
@@ -1,1510 +1,1514 @@
/*
 *  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.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.config.FileProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.attendance.domain.Attendance;
import me.zhengjie.modules.attendance.domain.AttendanceBusinessTravel;
import me.zhengjie.modules.attendance.domain.AttendanceGoOut;
import me.zhengjie.modules.attendance.repository.AttendanceBusinessTravelRepository;
import me.zhengjie.modules.attendance.repository.AttendanceCardreplacementRepository;
import me.zhengjie.modules.attendance.repository.AttendanceGoOutRepository;
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
import me.zhengjie.modules.attendance.service.impl.AttendanceLeaveServiceImpl;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.repository.ProjectRepository;
import me.zhengjie.modules.quartz.utils.DateTimeUtil;
import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.modules.security.service.UserCacheManager;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.vo.CalendarVo;
import me.zhengjie.modules.system.repository.*;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.UserLoginMapper;
import me.zhengjie.modules.system.service.mapstruct.UserMapper;
import me.zhengjie.modules.system.service.mapstruct.UserSmallMapper;
import me.zhengjie.modules.task.domain.TaskDaliyMongo;
import me.zhengjie.modules.task.domain.TaskMongo;
import me.zhengjie.modules.task.service.dto.TaskDaliyMongoDto;
import me.zhengjie.modules.treatment.domain.*;
import me.zhengjie.modules.treatment.repository.*;
import me.zhengjie.utils.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @author Zheng Jie
 * @date 2018-11-23
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final ProjectRepository projectRepository;
    private final UserMapper userMapper;
    private final UserSmallMapper userSmallMapper;
    private final FileProperties properties;
    private final RedisUtils redisUtils;
    private final UserCacheManager userCacheManager;
    private final OnlineUserService onlineUserService;
    private final UserLoginMapper userLoginMapper;
    private final SysLevelRepository sysLevelRepository;
    private final SysUserLevelWageRepository sysUserLevelWageRepository;
    private final SysUserLevelInsuranceRepository sysUserLevelInsuranceRepository;
    private final SysUserLevelOtherRepository sysUserLevelOtherRepository;
    private final AttendanceRepository attendanceRepository;
    private final AttendanceLeaveServiceImpl attendanceLeaveService;
    private final AttendanceCardreplacementRepository attendanceCardreplacementRepository;
    private final SysConfigProportionRepository sysConfigProportionRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final SysCompanyRepository sysCompanyRepository;
    private final DeptRepository deptRepository;
    private final MeritLevelRepository meritLevelRepository;
    private final CmnLevelRepository cmnLevelRepository;
    private final CmnLevelRankRepository cmnLevelRankRepository;
    private final CmnInsuranceRepository cmnInsuranceRepository;
    private final MongoTemplate mongoTemplate;
    private final UserLevelWageRepository userLevelWageRepository;
    private final UserInsuranceRepository userInsuranceRepository;
    @Autowired
    private CacheManager cacheManager;
    @Override
    public Object queryAll(UserQueryCriteria criteria, Pageable pageable) {
        Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(userMapper::toDto));
    }
    @Override
    public List<DeptUserNodeDto> queryDeptUserByDeptId(Long deptId) {
        List<DeptUserNodeDto> result = new ArrayList<DeptUserNodeDto>();
        Optional<Dept> deptOpt = deptRepository.findById(deptId);
        if (deptOpt.isPresent()) {
            Dept dept = deptOpt.get();
            List<Dept> subDeptList = deptRepository.findByPid(deptId);
            subDeptList.forEach(subDept -> {
                DeptUserNodeDto deptUserNodeDto = new DeptUserNodeDto();
                deptUserNodeDto.setId(subDept.getId());
                deptUserNodeDto.setLabel(subDept.getName());
                deptUserNodeDto.setLeaf(false);
                result.add(deptUserNodeDto);
            });
            List<User> userList = userRepository.findByDeptAndEnabled(dept, true);
            userList.forEach(user -> {
                DeptUserNodeDto deptUserNodeDto = new DeptUserNodeDto();
                deptUserNodeDto.setId(user.getId());
                deptUserNodeDto.setLabel(user.getNickName());
                deptUserNodeDto.setLeaf(true);
                result.add(deptUserNodeDto);
            });
        }
        return result;
    }
    @Override
    public List<UserDto> getUserByTaskId(String taskId) {
        // 日历类
        Calendar calendar = Calendar.getInstance();
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 日历字符串
        String calendarStr = sdf.format(calendar.getTime());
        TaskMongo taskMongo = mongoTemplate.findById(taskId, TaskMongo.class);
        List<Long> containUserList = taskMongo.getContainUserList();
        List<User> userList = new ArrayList<>();
        if (containUserList.size() != 0) {
            for (Long userId : containUserList) {
                userList.add(userRepository.findById(userId).get());
            }
        }
        List<UserDto> userDto = userMapper.toDto(userList);
        for (int i = 0; i < userDto.size(); i++) {
            // 根据用户ID、指定年月查询用户级别工资
            SysUserLevelWage sysUserLevelWage = sysUserLevelWageRepository.findTargetYearMonth(userDto.get(i).getId(), calendarStr);
            // 判断用户级别工资是否为空
            if (sysUserLevelWage != null) {
                // 根据ID查询用户级别
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(SysLevel::new);
                // 用户
                userDto.get(i).setLevelName(sysLevel.getName());
            } else {
                // 用户
                userDto.get(i).setLevelName(null);
            }
        }
        return userDto;
    }
    @Override
    public List<UserDto> getAllUserByTaskId(String taskId) {
        // 日历类
        Calendar calendar = Calendar.getInstance();
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 日历字符串
        String calendarStr = sdf.format(calendar.getTime());
        TaskMongo taskMongo = mongoTemplate.findById(taskId, TaskMongo.class);
        List<Long> containUserList = taskMongo.getContainUserList();
        //递归添加
        addSubTaskUserList(taskMongo, containUserList);
        containUserList = containUserList.stream().distinct().collect(Collectors.toList());
        List<User> userList = new ArrayList<>();
        if (containUserList.size() != 0) {
            for (Long userId : containUserList) {
                userList.add(userRepository.findById(userId).get());
            }
        }
        List<UserDto> userDto = userMapper.toDto(userList);
        for (int i = 0; i < userDto.size(); i++) {
            // 根据用户ID、指定年月查询用户级别工资
            SysUserLevelWage sysUserLevelWage = sysUserLevelWageRepository.findTargetYearMonth(userDto.get(i).getId(), calendarStr);
            // 判断用户级别工资是否为空
            if (sysUserLevelWage != null) {
                // 根据ID查询用户级别
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(SysLevel::new);
                // 用户
                userDto.get(i).setLevelName(sysLevel.getName());
            } else {
                // 用户
                userDto.get(i).setLevelName(null);
            }
        }
        return userDto;
    }
    /**
     * 任务下的所有子级
     *
     * @param taskMongo
     * @param containUserList
     */
    public void addSubTaskUserList(TaskMongo taskMongo, List<Long> containUserList) {
        List<TaskMongo> subTasks = mongoTemplate.find(Query.query(Criteria.where("pid").is(taskMongo.getOld_id())), TaskMongo.class);
        for (TaskMongo subTask : subTasks) {
            containUserList.addAll(subTask.getContainUserList());
            addSubTaskUserList(subTask, containUserList);
        }
    }
    @Override
    @Cacheable(key = "'AllUser'")
    public List<DeptAndUser> getUserDept() {
        List<Dept> all = deptRepository.findAll();
        List<DeptAndUser> result = new ArrayList<>();
        // 根节点
        for (Dept dept : all) {
            if (dept.getPid() == null) {
                //没有上级部门,他们就是最顶级的菜单
                DeptAndUser deptAndUser = new DeptAndUser();
                deptAndUser.setValue(dept.getId());
                deptAndUser.setLabel(dept.getName());
                result.add(deptAndUser);
            }
        }
        List<DeptAndUser> list = new ArrayList<>();
        for (Dept dept : all) {
            // 一级节点
            if (dept.getPid() != null) {
                if (dept.getPid().equals(result.get(0).getValue())) {
                    DeptAndUser deptAndUser = new DeptAndUser();
                    deptAndUser.setLabel(dept.getName());
                    deptAndUser.setValue(dept.getId());
                    list.add(deptAndUser);
                }
            }
        }
        result.get(0).setChildren(list);
        for (int i = 0; i < list.size(); i++) {
            // 二级节点
            List<DeptAndUser> list_two = new ArrayList<>();
            for (Dept dept : all) {
                if (dept.getPid() != null) {
                    if (dept.getPid().equals(result.get(0).getChildren().get(i).getValue())) {
                        DeptAndUser deptAndUser = new DeptAndUser();
                        deptAndUser.setLabel(dept.getName());
                        deptAndUser.setValue(dept.getId());
                        list_two.add(deptAndUser);
                    }
                }
            }
            result.get(0).getChildren().get(i).setChildren(list_two);
        }
        for (int i = 0; i < result.get(0).getChildren().size(); i++) {
            for (int j = 0; j < result.get(0).getChildren().get(i).getChildren().size(); j++) {
                ArrayList<DeptAndUser> list_three = new ArrayList<>();
                for (Dept dept : all) {
                    if (dept.getPid() != null) {
                        if (dept.getPid().equals(result.get(0).getChildren().get(i).getChildren().get(j).getValue())) {
                            DeptAndUser deptAndUser = new DeptAndUser();
                            deptAndUser.setLabel(dept.getName());
                            deptAndUser.setValue(dept.getId());
                            list_three.add(deptAndUser);
                        }
                    }
                }
                result.get(0).getChildren().get(i).getChildren().get(j).setChildren(list_three);
            }
        }
        for (int i = 0; i < result.get(0).getChildren().size(); i++) {
            for (int j = 0; j < result.get(0).getChildren().get(i).getChildren().size(); j++) {
                for (int r = 0; r < result.get(0).getChildren().get(i).getChildren().get(j).getChildren().size(); r++) {
                    ArrayList<DeptAndUser> list_four = new ArrayList<>();
                    if (!(deptRepository.findById(result.get(0).getChildren().get(i).getChildren().get(j).getChildren().get(r).getValue()).get().getSubCount() == 0)) {
                        // 当前节点不是叶子节点
                        for (Dept dept : all) {
                            if (dept.getPid() != null) {
                                if (dept.getPid().equals(result.get(0).getChildren().get(i).getChildren().get(j).getChildren().get(r).getValue())) {
                                    DeptAndUser deptAndUser = new DeptAndUser();
                                    deptAndUser.setValue(dept.getId());
                                    deptAndUser.setLabel(dept.getName());
                                    list_four.add(deptAndUser);
                                }
                            }
                        }
                        result.get(0).getChildren().get(i).getChildren().get(j).getChildren().get(r).setChildren(list_four);
                    }
                }
            }
        }
        //return result;
        recursionGetData(result);
        return result;
    }
    public void recursionGetData(List<DeptAndUser> list) {
        for (DeptAndUser deptAndUser : list) {
            if (deptAndUser.getChildren() == null) {
                deptAndUser.setChildren(new ArrayList<DeptAndUser>());
            }
            if (deptAndUser.getChildren().size() > 0) {
                recursionGetData(deptAndUser.getChildren());
            }
            List<User> users = userRepository.findByDeptIdInAndEnabledWithSingle(deptAndUser.getValue(), true);
            for (User user : users) {
                DeptAndUser result_deptAndUser = new DeptAndUser();
                result_deptAndUser.setValue(user.getId());
                result_deptAndUser.setLabel(user.getNickName());
                deptAndUser.getChildren().add(result_deptAndUser);
            }
        }
    }
    @Override
    public Long[] getUserPidDept(Long id) {
        ArrayList<Long> list = new ArrayList<>();
        Long deptId_leaf = userRepository.findDeptIdByUserId(id);
        list.add(id);
        list.add(0, deptId_leaf);
        list = getPidNode(list, deptId_leaf);
        return list.toArray(new Long[list.size()]);
    }
    @Override
    public List<TaskDaliyMongo> getPerformanceDetail(Long nextMonth) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String nextMonth_ = df.format(new Date(nextMonth)).substring(0,7) + "-01";
        Calendar cal = Calendar.getInstance();
        cal.setTime(df.parse(nextMonth_));
        cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        String nextMonthFirstDay = df.format(cal.getTime());
        List<TaskDaliyMongo> daliyMongoList;
        try {
            daliyMongoList = mongoTemplate.find(
                    Query.query(
                                    new Criteria("userId").is(SecurityUtils.getCurrentUserId())
                                            .and("fillDate")
                                            .gte(new SimpleDateFormat("yyyy-MM-dd").parse(nextMonth_))
                                            .lt(new SimpleDateFormat("yyyy-MM-dd").parse(nextMonthFirstDay)))
                            .with(Sort.by(Sort.Order.desc("fillDate")))
                    , TaskDaliyMongo.class);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Collection<TaskDaliyMongo> daliyMongoValues = daliyMongoList.stream().collect(
            Collectors.groupingBy(
                (TaskDaliyMongo taskDaliyMongo) -> taskDaliyMongo.getTaskUserMongo().getTask().getName(),
                Collectors.reducing(
                    null,
                    (TaskDaliyMongo prev, TaskDaliyMongo cur) -> {
                        if (prev == null) {
                            cur.getTaskProgress();
                            cur.getTaskUserMongo().getPerformanceHours();
                            cur.getTaskUserMongo().getPerformanceType();
                            if ("1".equals(cur.getTaskUserMongo().getPerformanceType())) {
                                cur.setConsumedHours(BigDecimal.valueOf(cur.getTaskUserMongo().getPerformanceHours())
                                        .multiply(BigDecimal.valueOf(cur.getTaskProgress()))
                                        .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).doubleValue());
                            }
                            return cur;
                        }
                        if ("0".equals(cur.getTaskUserMongo().getPerformanceType())) {
                            prev.setConsumedHours(prev.getConsumedHours() + cur.getConsumedHours());
                        }
                        return prev;
                    }
                )
            )
        ).values();
        return new ArrayList<>(daliyMongoValues);
    }
    @Override
    public List<User> getUserInfose() {
        List<User> userList = new ArrayList<>();
        //获取当前登入人信息
        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user1.getRoles().iterator().next();
        //超管、总经理,痛苦哦经理查看全部
        if (Long.valueOf(role.getLevel()) == Constant.ROLE_LEVEL_SUPER || Long.valueOf(role.getLevel()) == Constant.ROLE_LEVEL_GENERAL) {
            userList = userRepository.findAllByEnabled(true);
        } else {
            userList = userRepository.findByUserId(user1.getId());
        }
        return userList;
    }
    @Override
    public void findByUserIdInAndCompanyId(List<Long> userIds, Long companyId) {
        userRepository.findByUserIdInAndCompanyId(userIds, companyId);
    }
    private ArrayList<Long> getPidNode(ArrayList<Long> list, Long deptId_leaf) {
        Long pidId = deptRepository.findPidIdByDeptId(deptId_leaf);
        if (pidId != null) {
            list.add(0, pidId);
            getPidNode(list, pidId);
        }
        return list;
    }
    @Override
//    @Cacheable(key = "'total'")
//    @CacheEvict(value = "total", allEntries = true)
//    @Transactional(rollbackFor = Exception.class)
    public List<UserSmallDto> querySmallAll(UserQueryCriteria criteria) {
        // 日历类
        Calendar calendar = Calendar.getInstance();
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 日历字符串
        String calendarStr = sdf.format(calendar.getTime());
        // 只查询有效数据
        criteria.setEnabled(true);
        // 查询用户数据
        List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<UserSmallDto> usersDto = userSmallMapper.toDto(users);
        // 循环用户
        for (int i = 0; i < usersDto.size(); i++) {
            // 根据用户ID、指定年月查询用户级别工资
            SysUserLevelWage sysUserLevelWage = sysUserLevelWageRepository.findTargetYearMonth(usersDto.get(i).getId(), calendarStr);
            // 判断用户级别工资是否为空
            if (sysUserLevelWage != null) {
                // 根据ID查询用户级别
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(SysLevel::new);
                // 用户
                usersDto.get(i).setLevelName(sysLevel.getName());
            } else {
                // 用户
                usersDto.get(i).setLevelName(null);
            }
        }
        return usersDto;
    }
    @Override
//    @Cacheable(key = "'total'")
//    @CacheEvict(value = "total", allEntries = true)
//    @Transactional(rollbackFor = Exception.class)
    public List<UserDto> queryAll(UserQueryCriteria criteria) {
        // 日历类
        Calendar calendar = Calendar.getInstance();
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 日历字符串
        String calendarStr = sdf.format(calendar.getTime());
        // 只查询有效数据
        criteria.setEnabled(true);
        // 查询用户数据
        List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<UserDto> usersDto = userMapper.toDto(users);
        // 循环用户
        for (int i = 0; i < usersDto.size(); i++) {
            // 根据用户ID、指定年月查询用户级别工资
            SysUserLevelWage sysUserLevelWage = sysUserLevelWageRepository.findTargetYearMonth(usersDto.get(i).getId(), calendarStr);
            // 判断用户级别工资是否为空
            if (sysUserLevelWage != null) {
                // 根据ID查询用户级别
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(SysLevel::new);
                // 用户
                usersDto.get(i).setLevelName(sysLevel.getName());
            } else {
                // 用户
                usersDto.get(i).setLevelName(null);
            }
        }
        return usersDto;
    }
    @Override
    @Cacheable(key = "'id:' + #p0")
    @Transactional(rollbackFor = Exception.class)
    public UserDto findById(long id) {
        User user = userRepository.findById(id).orElseGet(User::new);
        ValidationUtil.isNull(user.getId(), "User", "id", id);
        return userMapper.toDto(user);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(User resources) {
        if (userRepository.findByUsername(resources.getUsername()) != null) {
            throw new EntityExistException(User.class, "username", resources.getUsername());
        }
        if (userRepository.findByEmail(resources.getEmail()) != null) {
            throw new EntityExistException(User.class, "email", resources.getEmail());
        }
        if (userRepository.findByPhone(resources.getPhone()) != null) {
            throw new EntityExistException(User.class, "phone", resources.getPhone());
        }
        redisUtils.del(CacheKey.TOTAL_USER);
        redisUtils.del("user::AllUser");
        userRepository.save(resources);
        // 判断用户级别变更
//        checkUserLevel(resources.getId(), null, resources.getLevelId());
        // 判断用户级别变更(新)
        checkUserLevelNew(resources);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User resources) throws Exception {
        User user = userRepository.findById(resources.getId()).orElseGet(User::new);
        ValidationUtil.isNull(user.getId(), "User", "id", resources.getId());
        User user1 = userRepository.findByUsername(resources.getUsername());
        User user2 = userRepository.findByEmail(resources.getEmail());
        User user3 = userRepository.findByPhone(resources.getPhone());
        if (user1 != null && !user.getId().equals(user1.getId())) {
            throw new EntityExistException(User.class, "username", resources.getUsername());
        }
        if (user2 != null && !user.getId().equals(user2.getId())) {
            throw new EntityExistException(User.class, "email", resources.getEmail());
        }
        if (user3 != null && !user.getId().equals(user3.getId())) {
            throw new EntityExistException(User.class, "phone", resources.getPhone());
        }
        // 如果用户的角色改变
        if (!resources.getRoles().equals(user.getRoles())) {
            redisUtils.del(CacheKey.DATA_USER + resources.getId());
            redisUtils.del(CacheKey.MENU_USER + resources.getId());
            redisUtils.del(CacheKey.ROLE_AUTH + resources.getId());
        }
        // 修改部门会影响 数据权限
        if (!Objects.equals(resources.getDept(), user.getDept())) {
            redisUtils.del(CacheKey.DATA_USER + resources.getId());
        }
        // 如果用户被禁用,则清除用户登录信息
        if (!resources.getEnabled()) {
            onlineUserService.kickOutForUsername(resources.getUsername());
        }
        // 临时旧用户级别ID
        Long tempOldLevelId = user.getLevelId();
        ;
        user.setUsername(resources.getUsername());
        user.setEmail(resources.getEmail());
        user.setEnabled(resources.getEnabled());
        user.setRoles(resources.getRoles());
        user.setDept(resources.getDept());
        user.setJobs(resources.getJobs());
        user.setPhone(resources.getPhone());
        user.setNickName(resources.getNickName());
        user.setCompany(resources.getCompany());
        user.setGender(resources.getGender());
        user.setBirthday(resources.getBirthday());
        user.setAddress(resources.getAddress());
        user.setDingding(resources.getDingding());
        user.setSysRostering(resources.getSysRostering());
        user.setLevelId(resources.getLevelId());
        // 临时新用户级别ID
        Long tempNewLevelId = user.getLevelId();
        redisUtils.del("user::AllUser");
        userRepository.save(user);
        // 判断用户级别变更
        checkUserLevel(user.getId(), tempOldLevelId, tempNewLevelId);
//        // 判断用户级别变更(新)
//        checkUserLevelNew(resources, tempOldLevelId, tempNewLevelId);
        // 清除缓存
        delCaches(user.getId(), user.getUsername());
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCenter(User resources) {
        User user = userRepository.findById(resources.getId()).orElseGet(User::new);
        User user1 = userRepository.findByPhone(resources.getPhone());
        if (user1 != null && !user.getId().equals(user1.getId())) {
            throw new EntityExistException(User.class, "phone", resources.getPhone());
        }
        user.setNickName(resources.getNickName());
        user.setPhone(resources.getPhone());
        user.setGender(resources.getGender());
        userRepository.save(user);
        // 清理缓存
        delCaches(user.getId(), user.getUsername());
    }
    /**
     * 获取日历信息
     *
     * @param month
     * @return
     * @throws Exception
     */
    @Override
    public List<CalendarVo> getUserCalendarInfo(String month) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<CalendarVo> calendarInfo = new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        //月份第一天,最后一天
        LocalDate startDate = LocalDate.parse(month).with(TemporalAdjusters.firstDayOfMonth());
        LocalDate endDate = LocalDate.parse(month).with(TemporalAdjusters.lastDayOfMonth());
        //当前登录人
        Long userId = SecurityUtils.getCurrentUserId();
        //查询这个范围的考勤记录
        List<Attendance> attendanceList = attendanceRepository.findAllByUserAndDate(userId, startDate.toString(), endDate.toString());
        for (Attendance attendance : attendanceList) {
            CalendarVo onDuty = new CalendarVo();
            onDuty.setDate(df.format(attendance.getAttendanceDate()));
            onDuty.setTitle(Constant.ATTENDANCE_STATE_NORMAL.equals(formateResult(attendance.getStartClockResults()).get("msg")) ? "上班打卡时间:" + attendance.getActualWorkStartTime().toString() : "上班:" + formateResult(attendance.getStartClockResults()).get("msg"));
            onDuty.setIsOk((Boolean) formateResult(attendance.getStartClockResults()).get("status"));
            onDuty.setType(1);
            CalendarVo offDuty = new CalendarVo();
            offDuty.setDate(df.format(attendance.getAttendanceDate()));
            offDuty.setTitle(Constant.ATTENDANCE_STATE_NORMAL.equals(formateResult(attendance.getEndClockResults()).get("msg")) ? "下班打卡时间:" + attendance.getActualWorkEndTime().toString() : "下班:" + formateResult(attendance.getEndClockResults()).get("msg"));
            offDuty.setIsOk((Boolean) formateResult(attendance.getEndClockResults()).get("status"));
            offDuty.setType(1);
            calendarInfo.add(onDuty);
            calendarInfo.add(offDuty);
            dateList.add(attendance.getAttendanceDate().toString());
        }
        //获取应工作时长
//        User user = userRepository.getById(userId);
//        Long duration = (Duration.between(user.getSysRostering().getWorkStartTime(), user.getSysRostering().getWorkEndTime())).toHours();
        //查询日志表
        List<TaskDaliyMongo> taskDaliyList = mongoTemplate.find(Query.query(new Criteria("userId").is(userId).and("fillDate").gte(startDate).lte(endDate)), TaskDaliyMongo.class);
        Map<String, Double> map = new HashMap<>();
        for (TaskDaliyMongo taskDaliy : taskDaliyList) {
            if (map.get(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0").format(taskDaliy.getFillDate())) != null) {
                // 如果已经有了
                Double todayHours = map.get(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0").format(taskDaliy.getFillDate()));
                todayHours += taskDaliy.getConsumedHours();
                map.put(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0").format(taskDaliy.getFillDate()), todayHours);
            } else {
                map.put(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0").format(taskDaliy.getFillDate()), taskDaliy.getConsumedHours());
            }
        }
        for (Map.Entry<String, Double> entry : map.entrySet()) {
            CalendarVo calendarVo = new CalendarVo();
            if (entry.getValue() >= 8) {
                calendarVo.setDate(entry.getKey());
                calendarVo.setIsOk(true);
                calendarVo.setTitle("工时:" + BigDecimal.valueOf(entry.getValue()).setScale(2, RoundingMode.HALF_UP));
                calendarVo.setType(2);
            } else {
                calendarVo.setDate(entry.getKey());
                calendarVo.setIsOk(false);
                calendarVo.setTitle("已填工时:" + BigDecimal.valueOf(entry.getValue()).setScale(2, RoundingMode.HALF_UP) + " 不足8小时,请补充日报");
                calendarVo.setType(2);
            }
            calendarInfo.add(calendarVo);
        }
        for (String date : dateList) {
            String type1 = "";
            String type2 = "";
            CalendarVo dailyVo = new CalendarVo();
            if (map.get(date) != null) {
                // 如果在map中找到了它的值,说明用户填写过日报
                continue;
            }
            dailyVo.setDate(date);
            for (Attendance attendanceRecord : attendanceList) {
                type1 = attendanceRecord.getStartClockResults();
                type2 = attendanceRecord.getEndClockResults();
                date = date.substring(0, 10);
                if (date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_LEAVE) && type2.equals(Constant.ATTENDANCE_STATE_LEAVE)) {
                    dailyVo.setTitle("请假");
                    dailyVo.setIsOk(true);
                } else if (date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_BUSINESS) && type2.equals(Constant.ATTENDANCE_STATE_BUSINESS)) {
                    dailyVo.setTitle("出差");
                    dailyVo.setIsOk(true);
                } else if (date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_REST) && type2.equals(Constant.ATTENDANCE_STATE_REST)) {
                    dailyVo.setTitle("休息");
                    dailyVo.setIsOk(true);
                } else if (date.equals(df.format(attendanceRecord.getAttendanceDate()))) {
                    dailyVo.setTitle("日报未填写,请补充日报");
                    dailyVo.setIsOk(false);
                }
            }
            dailyVo.setType(2);
            calendarInfo.add(dailyVo);
        }
        return calendarInfo;
    }
    /**
     * 判断状态
     *
     * @param result
     * @return
     */
    public Map formateResult(String result) {
        Map returnData = new HashMap();
        switch (result) {
            case Constant.ATTENDANCE_STATE_NOTSIGNED:
                returnData.put("msg", "缺卡");
                returnData.put("status", false);
                break;
            case Constant.ATTENDANCE_START_EARLY:
                returnData.put("msg", "早退");
                returnData.put("status", false);
                break;
            case Constant.ATTENDANCE_START_LATE:
                returnData.put("msg", "迟到");
                returnData.put("status", false);
                break;
            case Constant.ATTENDANCE_STATE_LACK_OF_TIME:
                returnData.put("msg", "缺时");
                returnData.put("status", false);
                break;
            case Constant.ATTENDANCE_STATE_LEAVE:
                returnData.put("msg", "请假");
                returnData.put("status", true);
                break;
            case Constant.ATTENDANCE_STATE_GOOUT:
                returnData.put("msg", "外出");
                returnData.put("status", true);
                break;
            case Constant.ATTENDANCE_STATE_BUSINESS:
                returnData.put("msg", "出差");
                returnData.put("status", true);
                break;
            case Constant.ATTENDANCE_STATE_WAITFOR:
                returnData.put("msg", "等待");
                returnData.put("status", true);
                break;
            case Constant.ATTENDANCE_STATE_REST:
                returnData.put("msg", "休息");
                returnData.put("status", true);
                break;
            default:
                returnData.put("msg", result);
                returnData.put("status", true);
        }
        return returnData;
    }
    /**
     * 获取用户基础信息
     *
     * @return
     * @throws ParseException
     */
    @Override
    public Map getUserBaseInfo(Date yearMonth) throws ParseException {
        // 返回集合
        Map returnData = new HashMap();
        // 当前登录用户
        Long userId = SecurityUtils.getCurrentUserId();
        // 目标年月字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sdfDate = sdf.format(yearMonth);
        // 目标年月初字符串
        String sdfFirstDate = DateUtil.getFirstDayOfMonthFull(sdfDate);
        // 目标年月末字符串
        String sdfLastDate = DateUtil.getLastDayOfMonthFull(sdfDate);
        // 出勤天数
        List<Attendance> attendanceRecordList = attendanceRepository.findAllByUserAndDate(userId, sdfFirstDate, sdfLastDate);
        int numDay = 0;
        for (Attendance attendance : attendanceRecordList) {
            if (!attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_REST) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_REST)) {
                numDay++;
            }
        }
        returnData.put("onDutyDays", numDay);
        // 剩余年假
        Double yearTimes = attendanceLeaveService.getYearTimeLength(userId);
        returnData.put("annualLeave", yearTimes);
        // 查询当月的补卡记录的条数
        Integer count = attendanceCardreplacementRepository.count(userId, sdfDate.substring(0, 7));
        // 查询配置表的每月补卡次数
        SysConfigProportion sysConfigProportion = sysConfigProportionRepository.findByTitle("每月可补卡次数");
        if (count >= sysConfigProportion.getProportion()) {
            returnData.put("cardLeft", 0);
        } else {
            returnData.put("cardLeft", (sysConfigProportion.getProportion() - count));
        }
        // 法定节假日
        List<String> holiday = new ArrayList<>();
        // 天数
        int shouldWordDays = 0;
        List<SysConfigHoliday> holidayConfigurationList = sysConfigHolidayRepository.findAll();
        for (SysConfigHoliday holidayConfiguration : holidayConfigurationList) {
            if (holidayConfiguration.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
                holiday.add(sdf.format(holidayConfiguration.getHolidayDate()));
            }
        }
        // 获取当月所有日期
        List<String> dateList = DateTimeUtil.getDayByMonth(sdfDate.substring(0, 4), sdfDate.substring(5, 7));
        Date date1 = new Date();
        String todayDay = sdf.format(date1);
        if (!todayDay.substring(0, 7).equals(sdfDate.substring(0, 7))) {
            todayDay = sdfLastDate;
        }
        // 工作日的天数
        for (String date : dateList) {
            Date isWeekEnd = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(isWeekEnd);
            if (isWeekEnd.compareTo(sdf.parse(todayDay)) <= 0) {
                if (!holiday.contains(date) && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
                    shouldWordDays += 1;
                }
            }
        }
        int num = shouldWordDays * 8;
        // 月初到今天应工作时长
        returnData.put("Time", num);
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        User user = userRepository.getById(userId);
        // 考勤上午时间
        Double attCheckOnDuration = 0.0;
        // 考勤下午时间
        Double attCheckOffDuration = 0.0;
        for (Attendance attendance : attendanceRecordList) {
            // 上班打卡时间不为空并且打卡状态不为出差外出的考勤记录
            if (ObjectUtils.isNotEmpty(attendance.getActualWorkStartTime()) && !attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_GOOUT) && !attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_BUSINESS)) {
                LocalDateTime attCheckOnTime = attendance.getActualWorkStartTime().toLocalDateTime();
                LocalDateTime scheduleStartTime = LocalDateTime.parse(attendance.getAttendanceDate().toString().substring(0, 10) + " " + user.getSysRostering().getLunchStartTime().toString() + ":00", formatter2);
                if (attCheckOnTime.compareTo(scheduleStartTime) <= 0) {
                    // 获得两个时间之间的相差值
                    Duration duration = Duration.between(attCheckOnTime, scheduleStartTime);
                    Long minutes = duration.toMinutes();
                    Double hour = Double.valueOf(String.valueOf(new BigDecimal(Double.valueOf(minutes) / 60).setScale(2, BigDecimal.ROUND_HALF_UP)));
                    attCheckOnDuration = attCheckOnDuration + hour;
                }
            }
            // 下班打卡时间不为空并且打卡状态不为出差外出的考勤记录
            if (ObjectUtils.isNotEmpty(attendance.getActualWorkEndTime()) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_GOOUT) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_BUSINESS)) {
                LocalDateTime attCheckOffTime = attendance.getActualWorkEndTime().toLocalDateTime();
                LocalDateTime scheduleEndTime = LocalDateTime.parse(attendance.getAttendanceDate().toString().substring(0, 10) + " " + user.getSysRostering().getLunchEndTime().toString() + ":00", formatter2);
                if (attCheckOffTime.compareTo(scheduleEndTime) > 0) {
                    // 获得两个时间之间的相差值
                    Duration duration = Duration.between(scheduleEndTime, attCheckOffTime);
                    Long minutes = duration.toMinutes();
                    Double hour = Double.valueOf(String.valueOf(new BigDecimal(Double.valueOf(minutes) / 60).setScale(2, BigDecimal.ROUND_HALF_UP)));
                    attCheckOffDuration = attCheckOffDuration + hour;
                }
            }
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        String startTime = sdfFirstDate.substring(0, 10) + " " + dateTimeFormatter.format(user.getSysRostering().getWorkStartTime());
        String endTime = todayDay.substring(0, 10) + " " + dateTimeFormatter.format(user.getSysRostering().getWorkEndTime());
        // 外出时长
        Double goOutTimes = 0.0;
        // 查询外出表
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(userId, Timestamp.valueOf(startTime).toLocalDateTime(), Timestamp.valueOf(endTime).toLocalDateTime());
        for (AttendanceGoOut attendanceGoOut : attendanceGoOutList) {
            goOutTimes = goOutTimes + attendanceGoOut.getOutDuration();
        }
        // 出差时长
        Double bussTimes = 0.0;
        // 查询出差表
        List<AttendanceBusinessTravel> attendanceBusinessTravelList = attendanceBusinessTravelRepository.findByUserAndSEDate(userId, Timestamp.valueOf(sdfFirstDate).toLocalDateTime(), Timestamp.valueOf(todayDay.substring(0, 10) + " " + "00:00:00").toLocalDateTime());
        for (AttendanceBusinessTravel attendanceBusinessTravel : attendanceBusinessTravelList) {
            bussTimes = bussTimes + attendanceBusinessTravel.getTravelDuration();
        }
        returnData.put("Times", attCheckOnDuration + attCheckOffDuration + goOutTimes + (bussTimes * 8));
        // 查询某月已完成工时
        DecimalFormat decimalFormat = new DecimalFormat("0.##");
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(
            Query.query(
                new Criteria("userId").is(SecurityUtils.getCurrentUserId())
                    .and("fillDate")
                    .gte(new SimpleDateFormat("yyyy-MM-dd").parse(startTime))
                    .lte(new SimpleDateFormat("yyyy-MM-dd").parse(endTime)))
                .with(Sort.by(Sort.Order.desc("fillDate")))
            , TaskDaliyMongo.class);
        List<TaskDaliyMongoDto> resultList = daliyMongoList.stream().collect(
            Collectors.groupingBy(
                (TaskDaliyMongo taskDaliyMongo) -> taskDaliyMongo.getTaskUserMongo().getId(),
                Collectors.reducing(
                    null,
                    (TaskDaliyMongo prev, TaskDaliyMongo cur) -> {
                        if (prev == null) {
                            if ("1".equals(cur.getTaskUserMongo().getPerformanceType())) {
                                cur.setConsumedHours(BigDecimal.valueOf(cur.getTaskUserMongo().getPerformanceHours())
                                    .multiply(BigDecimal.valueOf(cur.getTaskProgress()))
                                    .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).doubleValue());
                            }
                            return cur;
                        }
                        if ("0".equals(cur.getTaskUserMongo().getPerformanceType())) {
                            prev.setConsumedHours(prev.getConsumedHours() + cur.getConsumedHours());
                        }
                        return prev;
                    }
                )
            )
        ).values().stream().map(taskDaliyMongo -> {
            if ("1".equals(taskDaliyMongo.getTaskUserMongo().getPerformanceType())) {
                // 查询日报表是否存在小于当前月填写的当前任务的日报
                List<TaskDaliyMongo> taskDaliyMongoSm = null;
                try {
                    taskDaliyMongoSm = mongoTemplate.find(
                        Query.query(new Criteria("userId").is(SecurityUtils.getCurrentUserId())
                            .and("taskUserMongo").is(taskDaliyMongo.getTaskUserMongo())
                            .and("fillDate").lt(new SimpleDateFormat("yyyy-MM-dd").parse(startTime)))
                        .with(Sort.by(Sort.Direction.DESC, "fillDate")), TaskDaliyMongo.class);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                //跨月
                if (taskDaliyMongoSm.size() > 0) {
                    BigDecimal lastValue = BigDecimal.valueOf(taskDaliyMongoSm.get(0).getTaskProgress())
                            .multiply(BigDecimal.valueOf(taskDaliyMongoSm.get(0).getTaskUserMongo().getPerformanceHours()))
                            .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
                    taskDaliyMongo.setConsumedHours(BigDecimal.valueOf(taskDaliyMongo.getConsumedHours()).subtract(lastValue).doubleValue());
                }
            }
            return taskDaliyMongo;
        })
//                .collect(
//            Collectors.groupingBy(
//                (TaskDaliyMongo taskDaliyMongo) -> taskDaliyMongo.getTaskUserMongo().getTask().getId(),
//                Collectors.reducing(
//                    null,
//                    (TaskDaliyMongo prev, TaskDaliyMongo cur) -> {
//                        if (prev == null) {
//                            return cur;
//                        }
//                        prev.setConsumedHours(prev.getConsumedHours() + cur.getConsumedHours());
//                        return prev;
//                    }
//                )
//            )
//        ).values().stream()
                .map(taskDaliyMongo -> {
            TaskDaliyMongoDto dto = new TaskDaliyMongoDto();
            dto.setId(taskDaliyMongo.getId());
            dto.setFillDate(taskDaliyMongo.getFillDate());
            dto.setUserNickName(userRepository.findById(SecurityUtils.getCurrentUserId()).get().getNickName());
            dto.setProjectId(taskDaliyMongo.getTaskUserMongo().getTask().getProjectId());
            dto.setProjectName(projectRepository.findById(taskDaliyMongo.getTaskUserMongo().getTask().getProjectId()).get().getName());
            dto.setTaskName(taskDaliyMongo.getTaskUserMongo().getTask().getName());
            dto.setTaskId(taskDaliyMongo.getTaskUserMongo().getTask().getId());
            dto.setConsumedHours(BigDecimal.valueOf(taskDaliyMongo.getConsumedHours()).setScale(2, RoundingMode.HALF_UP).doubleValue());
            dto.setTaskProgress(taskDaliyMongo.getTaskProgress());
            dto.setSettlementStatus(taskDaliyMongo.getSettlementStatus());
            dto.setRemarks(taskDaliyMongo.getRemarks());
            dto.setTaskUserMongo(taskDaliyMongo.getTaskUserMongo());
            return dto;
        }).collect(Collectors.toList());
        // 月初到今天绩效时长
        returnData.put("achievementsTime", resultList.stream().mapToDouble(TaskDaliyMongoDto::getConsumedHours).sum());
        // 绩效详细
        returnData.put("achievementsList", resultList);
        // 换休时长
        Double overTime = attendanceLeaveService.getOverTimeLength(userId);
        returnData.put("overTime", overTime);
        return returnData;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            // 清理缓存
            UserDto user = findById(id);
            delCaches(user.getId(), user.getUsername());
        }
        redisUtils.del(CacheKey.TOTAL_USER);
        userRepository.deleteAllByIdIn(ids);
    }
    @Override
    public UserDto findByName(String userName) {
        User user = userRepository.findByUsername(userName);
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", userName);
        } else {
            return userMapper.toDto(user);
        }
    }
    @Override
    public UserLoginDto getLoginData(String userName) {
        User user = userRepository.findByUsername(userName);
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", userName);
        } else {
            return userLoginMapper.toDto(user);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePass(String username, String pass) {
        userRepository.updatePass(username, pass, new Date());
        flushCache(username);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> updateAvatar(MultipartFile multipartFile) {
        // 文件大小验证
        FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize());
        // 验证文件上传的格式
        String image = "gif jpg png jpeg";
        String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        if (fileType != null && !image.contains(fileType)) {
            throw new BadRequestException("文件格式错误!, 仅支持 " + image + " 格式");
        }
        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        String oldPath = user.getAvatarPath();
        File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar());
        user.setAvatarPath(Objects.requireNonNull(file).getPath());
        user.setAvatarName(file.getName());
        userRepository.save(user);
        if (StringUtils.isNotBlank(oldPath)) {
            FileUtil.del(oldPath);
        }
        @NotBlank String username = user.getUsername();
        flushCache(username);
        return new HashMap<String, String>(1) {{
            put("avatar", file.getName());
        }};
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmail(String username, String email) {
        userRepository.updateEmail(username, email);
        flushCache(username);
    }
    @Override
    public void download(List<UserDto> queryAll, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
//        for (UserSmallDto userDTO : queryAll) {
//            List<String> roles = userDTO.getRoles().stream().map(RoleSmallDto::getName).collect(Collectors.toList());
//            String levelName = userDTO.getLevelId() != null ? sysLevelRepository.findById(userDTO.getLevelId()).orElseGet(SysLevel::new).getName() : "";
//            SysCompany sysCompany = sysCompanyRepository.findById(userDTO.getCompany().getId()).orElseGet(SysCompany::new);
//            Map<String, Object> map = new LinkedHashMap<>();
//            map.put("用户名", userDTO.getUsername());
//            map.put("角色", roles);
//            map.put("部门", userDTO.getDept().getName());
//            map.put("岗位", userDTO.getJobs().stream().map(JobSmallDto::getName).collect(Collectors.toList()));
//            map.put("邮箱", userDTO.getEmail());
//            map.put("钉钉号", userDTO.getDingding());
//            map.put("排班", userDTO.getSysRostering().getName());
//            map.put("级别", levelName);
//            map.put("所属公司", sysCompany == null ? "" : sysCompany.getLabel());
//            map.put("状态", userDTO.getEnabled() ? "启用" : "禁用");
//            map.put("手机号码", userDTO.getPhone());
//            map.put("修改密码的时间", userDTO.getPwdResetTime());
//            map.put("创建日期", userDTO.getCreateTime());
//            list.add(map);
//        }
        FileUtil.downloadExcel(list, response);
    }
    /**
     * 清理缓存
     *
     * @param id /
     */
    public void delCaches(Long id, String username) {
        redisUtils.del(CacheKey.USER_ID + id);
        flushCache(username);
    }
    /**
     * 清理 登陆时 用户缓存信息
     *
     * @param username /
     */
    private void flushCache(String username) {
        userCacheManager.cleanUserCache(username);
    }
    /**
     * 判断用户级别变更
     *
     * @param userId
     * @param oldLevelId
     * @param newLevelId
     */
    private void checkUserLevel(Long userId, Long oldLevelId, Long newLevelId) {
        // 查询级别表
        SysLevel sysLevel = sysLevelRepository.findById(newLevelId).orElseGet(SysLevel::new);
        // 判断新旧用户级别ID是否相等
        if (oldLevelId == null) {
            // 创建用户级别工资(旧)
            createSysUserLevelWage(userId, newLevelId);
            // 创建用户级别保险(旧)
            createSysUserLevelInsurance(userId, newLevelId);
        } else if (oldLevelId != newLevelId) {
            // 旧用户级别工资
            SysUserLevelWage oldSysUserLevelWage = sysUserLevelWageRepository.findLastByUserId(userId);
            // 判断旧用户级别工资是否为空
            if (oldSysUserLevelWage != null && oldSysUserLevelWage.getId() != null) {
                // 旧日期字符串
                String oldDateString = oldSysUserLevelWage.getStartDate().toString().substring(0, 10);
                // 获取当前日期
                Date nowDate = new Date();
                // 创建Calendar实例
                Calendar nowCalendar = Calendar.getInstance();
                // 设置当前时间
                nowCalendar.setTime(nowDate);
                // 新日期字符串
                String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0, 10);
                // 判断新、旧日期字符串
                if (oldDateString.equals(nowDateString)) {
                    throw new BadRequestException("每天只能调整一次级别,请明日再试!");
                }
                // 设置前一天时间
                nowCalendar.add(Calendar.DATE, -1);
                // 旧用户级别工资
                oldSysUserLevelWage.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
                // 保存
                sysUserLevelWageRepository.save(oldSysUserLevelWage);
            }
            // 创建用户级别工资(旧)
            createSysUserLevelWage(userId, newLevelId);
            // 旧用户级别保险
            SysUserLevelInsurance oldSysUserLevelInsurance = sysUserLevelInsuranceRepository.findLastByUserId(userId);
            // 判断旧用户级别保险是否为空
            if (oldSysUserLevelInsurance != null && oldSysUserLevelInsurance.getId() != null) {
                // 旧日期字符串
                String oldDateString = oldSysUserLevelInsurance.getStartDate().toString().substring(0, 10);
                // 获取当前日期
                Date nowDate = new Date();
                // 创建Calendar实例
                Calendar nowCalendar = Calendar.getInstance();
                // 设置当前时间
                nowCalendar.setTime(nowDate);
                // 新日期字符串
                String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0, 10);
                // 判断新、旧日期字符串
                if (oldDateString.equals(nowDateString)) {
                    throw new BadRequestException("每天只能调整一次级别,请明日再试!");
                }
                // 设置前一天时间
                nowCalendar.add(Calendar.DATE, -1);
                // 旧用户级别保险
                oldSysUserLevelInsurance.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
                // 保存
                sysUserLevelInsuranceRepository.save(oldSysUserLevelInsurance);
            }
            // 创建用户级别保险(旧)
            createSysUserLevelInsurance(userId, newLevelId);
            // 旧用户级别其他
            SysUserLevelOther oldSysUserLevelOther = sysUserLevelOtherRepository.findLastByUserId(userId);
            // 判断旧用户级别其他是否为空
            if (oldSysUserLevelOther != null && oldSysUserLevelOther.getId() != null) {
                // 旧日期字符串
                String oldDateString = oldSysUserLevelOther.getStartDate().toString().substring(0, 10);
                // 获取当前日期
                Date nowDate = new Date();
                // 创建Calendar实例
                Calendar nowCalendar = Calendar.getInstance();
                // 设置当前时间
                nowCalendar.setTime(nowDate);
                // 新日期字符串
                String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0, 10);
                // 判断新、旧日期字符串
                if (oldDateString.equals(nowDateString)) {
                    throw new BadRequestException("每天只能调整一次级别,请明日再试!");
                }
                // 设置前一天时间
                nowCalendar.add(Calendar.DATE, -1);
                // 旧用户级别保险
                oldSysUserLevelOther.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
                // 保存
                sysUserLevelOtherRepository.save(oldSysUserLevelOther);
            }
        } else {
        }
    }
    /**
     * 判断用户级别变更
     *
     * @param resources
     */
    private void checkUserLevelNew(User resources) {
        // 查询级别管理表
        CmnLevel cmnLevel = cmnLevelRepository.findById(resources.getLevelId()).orElseGet(CmnLevel::new);
        for (int i = 0; i < 2; i++) {
            if (i == 1) {
                // 创建第二条用户级别工资(新)
                createNewSysUserLevelWage(resources, cmnLevel, EnumerationType.SECOND_ENUM);
                // 创建第二条用户级别保险 (新)
                createNewSysUserLevelInsurance(resources, EnumerationType.SECOND_ENUM);
            } else {
                // 创建第一条用户级别工资(新)
                createNewSysUserLevelWage(resources, cmnLevel, EnumerationType.FIRST_ENUM);
                // 创建第一条用户级别保险 (新)
                createNewSysUserLevelInsurance(resources, EnumerationType.FIRST_ENUM);
            }
        }
        // 创建用户级别其他(新)
        createSysUserLevelOther(resources, cmnLevel);
    }
    /**
     * 创建用户级别工资(新)
     *
     * @param resources
     * @param cmnLevel
     */
    private void createNewSysUserLevelWage(User resources, CmnLevel cmnLevel, EnumerationType enumType) {
        Calendar calendar = Calendar.getInstance();
        // 用户级别工资
        UserLevelWage userLevelWage = new UserLevelWage();
        userLevelWage.setUserId(resources.getId());
        userLevelWage.setLevel(cmnLevel.getId());
        // 获取试用期结束的月初时间
        Timestamp result1 = getConfirmationTime(resources);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String resultValue = sdf.format(result1);
        if (enumType.equals(EnumerationType.FIRST_ENUM)) {
            userLevelWage.setYearMonth(sdf.format(new Timestamp(calendar.getTimeInMillis())));
        } else {
            userLevelWage.setYearMonth(resultValue);
        }
        // 查询最小的等级
        MeritLevel meritLevel = meritLevelRepository.findMinMeritStandardByLevelId(cmnLevel.getId());
        userLevelWage.setRank(meritLevel.getId());
        userLevelWage.setBasicWage(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(cmnLevel.getBasicWage().doubleValue() * 0.8) :cmnLevel.getBasicWage());
        userLevelWage.setRankWage(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(cmnLevel.getRankWage().doubleValue() * 0.8) : cmnLevel.getRankWage());
        userLevelWage.setPerformanceWage(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(cmnLevel.getPerformanceWage().doubleValue() * 0.8) : cmnLevel.getPerformanceWage());
        // 查询绩效系数
        CmnLevelRank cmnLevelRank = cmnLevelRankRepository.findbylevelSm(cmnLevel.getId());
        userLevelWage.setPerformanceCoefficient(new BigDecimal(cmnLevelRank.getPerformanceCoefficient()));
        // 保存
        userLevelWageRepository.save(userLevelWage);
    }
    /**
     * 创建用户级别保险 (新)
     *
     * @param resources
     */
    public void createNewSysUserLevelInsurance(User resources, EnumerationType enumType) {
        Calendar calendar = Calendar.getInstance();
        // 用户级别工资
        UserInsurance userInsurance = new UserInsurance();
        userInsurance.setUserId(resources.getId());
        // 获取试用期结束的月初时间
        Timestamp result = getConfirmationTime(resources);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String resultValue = sdf.format(result);
        if (enumType.equals(EnumerationType.FIRST_ENUM)) {
            userInsurance.setYearMonth(sdf.format(new Timestamp(calendar.getTimeInMillis())));
        } else {
            userInsurance.setYearMonth(resultValue);
        }
        // 根据选择的公司查询五险一金
        CmnInsurance cmnInsurance = cmnInsuranceRepository.findByCompany(resources.getCompany()).orElseGet(CmnInsurance::new);
        userInsurance.setAccumulationFund(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getAccumulationFund());
        userInsurance.setAccumulationFundPersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getAccumulationFundPersonal());
        userInsurance.setAccumulationFundCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getAccumulationFundCompany());
        userInsurance.setRetirementInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getRetirementInsurance());
        userInsurance.setRetirementInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getRetirementInsurancePersonal());
        userInsurance.setRetirementInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getRetirementInsuranceCompany());
        userInsurance.setMedicalInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getMedicalInsurance());
        userInsurance.setMedicalInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getMedicalInsurancePersonal());
        userInsurance.setMedicalInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getMedicalInsuranceCompany());
        userInsurance.setUnemploymentInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getUnemploymentInsurance());
        userInsurance.setUnemploymentInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getUnemploymentInsurancePersonal());
        userInsurance.setUnemploymentInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getUnemploymentInsuranceCompany());
        userInsurance.setBirthInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getBirthInsurance());
        userInsurance.setBirthInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getBirthInsurancePersonal());
        userInsurance.setBirthInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getBirthInsuranceCompany());
        userInsurance.setEmploymentInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getEmploymentInsurance());
        userInsurance.setEmploymentInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getEmploymentInsurancePersonal());
        userInsurance.setEmploymentInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getEmploymentInsuranceCompany());
        // 保存
        userInsuranceRepository.save(userInsurance);
    }
    /**
     * 创建用户级别其他(新)
     * @param resources
     * @param cmnLevel
     */
    private void createSysUserLevelOther(User resources, CmnLevel cmnLevel) {
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM");
        // 获取试用期结束的月初时间
        Timestamp result = getConfirmationTime(resources);
        // 获取实习期结束的年份
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(result);
        int formalYear = calendar.get(Calendar.YEAR);
        // 获取当前年份
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
//        for (int i = 0; i < 2; i++) {
//            // 第一条记录
//            SysUserLevelOther sysUserLevelOther = new SysUserLevelOther();
//            sysUserLevelOther.setUserId(resources.getId());
//            sysUserLevelOther.setLevelId(cmnLevel.getId());
//            sysUserLevelOther.setPersonalPerformanceProportion(Double.valueOf(0));
//
//            if (i == 1) {
//                // 计算剩余年假
//                Double annualLeave = getAnnualLeave(calendar);
//                sysUserLevelOther.setAnnualLeaveDays(annualLeave);
//            } else {
//                calendar.add(Calendar.YEAR, 1);
//                // 设置月份为一月
//                calendar.set(Calendar.MONTH, Calendar.JANUARY);
//                // 设置月份为一日
//                calendar.set(Calendar.DAY_OF_MONTH, 1);
//
//                sysUserLevelOther.setAnnualLeaveDays(5.0);
//            }
//            // 年月
//            sysUserLevelOther.setYearMonth(sdf.format(calendar.getTime()));
//
//
//            sysUserLevelOtherRepository.save(sysUserLevelOther);
//        }
        // 添加两条数据
        for (int i = 0; i < 2; i++) {
            if (i == 0) {
                // 第一条记录
                SysUserLevelOther sysUserLevelOther = new SysUserLevelOther();
                sysUserLevelOther.setUserId(resources.getId());
                sysUserLevelOther.setLevelId(cmnLevel.getId());
                sysUserLevelOther.setPersonalPerformanceProportion(Double.valueOf(0));
                sysUserLevelOther.setStartDate(Timestamp.valueOf(LocalDate.now().atStartOfDay()));
                // 计算剩余年假
                Double annualLeave = getAnnualLeave(calendar);
                sysUserLevelOther.setAnnualLeaveDays(annualLeave);
                // 判断为今年设置为当前日期
                if (formalYear == currentYear) {
                    sysUserLevelOther.setYearMonth(sdf.format(new Date()));
                } else {
                    // 设置为明年转正日期
                    sysUserLevelOther.setYearMonth(sdf.format(calendar.getTime()));
                }
                sysUserLevelOtherRepository.save(sysUserLevelOther);
            } else {
                // 第二条记录
                SysUserLevelOther sysUserLevelOther1 = new SysUserLevelOther();
                sysUserLevelOther1.setUserId(resources.getId());
                sysUserLevelOther1.setLevelId(cmnLevel.getId());
                Calendar calendar1 = Calendar.getInstance();
                calendar1.add(Calendar.YEAR, 1);
                // 设置月份为一月
                calendar1.set(Calendar.MONTH, Calendar.JANUARY);
                calendar1.set(Calendar.DAY_OF_MONTH, 1);
                sysUserLevelOther1.setPersonalPerformanceProportion(Double.valueOf(0));
                sysUserLevelOther1.setAnnualLeaveDays(5.0);
                // 判断实习期结束日期的年份不是今年,年份加1
                if (formalYear != currentYear) {
                    // 在增加一年
                    calendar1.add(Calendar.YEAR, 1);
                }
                // 日期设置为 明年/后年 年初
                sysUserLevelOther1.setYearMonth(sdf.format(calendar1.getTime()));
                sysUserLevelOther1.setStartDate(new Timestamp(calendar1.getTimeInMillis()));
                sysUserLevelOtherRepository.save(sysUserLevelOther1);
            }
        }
    }
    /**
     * 获取转正的月初时间
     *
     * @return
     */
    private Timestamp getConfirmationTime(User resources) {
        Calendar calendar = Calendar.getInstance();
        // 获取 Calendar 对象所代表的时间
        calendar.setTime(new Timestamp(calendar.getTimeInMillis()));
        // 获取是一个月中的哪一天
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        // 获取这个月有多少天
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        Timestamp result;
        if (dayOfMonth <= daysInMonth / 2) {
            // 实习时间为空默认三个月,用户是在前半个月加入的,算上本月获取两个月之后的日期
            calendar.add(Calendar.MONTH, resources.getInternshipTime() == null ? 3 : resources.getInternshipTime());
        } else {
            // 用户是在后半个月加入的,不算本月获取三个月之后的日期
            calendar.add(Calendar.MONTH, resources.getInternshipTime() == null ? 4 : resources.getInternshipTime() + 1);
        }
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        result = new Timestamp(calendar.getTimeInMillis());
        return result;
    }
    /**
     * 获取年假
     * @param calendar
     * @return
     */
    private Double getAnnualLeave(Calendar calendar) {
        // 转正的月份
        int joinMonth = calendar.get(Calendar.MONTH);
        Double annualLeave = 0.0;
        int remainingMonths = 12 - joinMonth;
        // 计算年假天数
        annualLeave = (5.0 / 12) * remainingMonths;
        BigDecimal big = new BigDecimal(annualLeave);
        big = big.setScale(1, BigDecimal.ROUND_HALF_UP);
        annualLeave = big.doubleValue();
        return annualLeave;
    }
    /**
     * 创建用户级别工资(旧)
     *
     * @param userId
     * @param levelId
     */
    private void createSysUserLevelWage(Long userId, Long levelId) {
        // 级别
        SysLevel sysLevel = sysLevelRepository.findById(levelId).orElseGet(SysLevel::new);
        // 用户级别工资
        SysUserLevelWage sysUserLevelWage = new SysUserLevelWage();
        sysUserLevelWage.setUserId(userId);
        sysUserLevelWage.setLevelId(levelId);
        sysUserLevelWage.setStartDate(new Timestamp(new Date().getTime()));
        sysUserLevelWage.setLevelWage(sysLevel.getLevelWage());
        sysUserLevelWage.setBasicWageProportion(sysLevel.getBasicWageProportion());
        sysUserLevelWage.setAchievementsWageProportion(sysLevel.getAchievementsWageProportion());
        sysUserLevelWage.setPerformanceWageProportion(sysLevel.getPerformanceWageProportion());
        sysUserLevelWage.setTeamWageProportion(sysLevel.getTeamWageProportion());
        // 保存
        sysUserLevelWageRepository.save(sysUserLevelWage);
    }
    // 创建用户级别保险(旧)
    private void createSysUserLevelInsurance(Long userId, Long levelId) {
        // 级别
        SysLevel sysLevel = sysLevelRepository.findById(levelId).orElseGet(SysLevel::new);
        // 用户级别工资
        SysUserLevelInsurance sysUserLevelInsurance = new SysUserLevelInsurance();
        sysUserLevelInsurance.setUserId(userId);
        sysUserLevelInsurance.setLevelId(levelId);
        sysUserLevelInsurance.setStartDate(new Timestamp(new Date().getTime()));
        sysUserLevelInsurance.setAccumulationRadix(sysLevel.getAccumulationRadix());
        sysUserLevelInsurance.setAccumulationPersonalProportion(sysLevel.getAccumulationPersonalProportion());
        sysUserLevelInsurance.setAccumulationCompanyProportion(sysLevel.getAccumulationCompanyProportion());
        sysUserLevelInsurance.setPensionRadix(sysLevel.getPensionRadix());
        sysUserLevelInsurance.setPensionPersonalProportion(sysLevel.getPensionPersonalProportion());
        sysUserLevelInsurance.setPensionCompanyProportion(sysLevel.getPensionCompanyProportion());
        sysUserLevelInsurance.setMedicalRadix(sysLevel.getMedicalRadix());
        sysUserLevelInsurance.setMedicalPersonalProportion(sysLevel.getMedicalPersonalProportion());
        sysUserLevelInsurance.setMedicalCompanyProportion(sysLevel.getMedicalCompanyProportion());
        sysUserLevelInsurance.setUnemploymentRadix(sysLevel.getUnemploymentRadix());
        sysUserLevelInsurance.setUnemploymentPersonalProportion(sysLevel.getUnemploymentPersonalProportion());
        sysUserLevelInsurance.setUnemploymentCompanyProportion(sysLevel.getUnemploymentCompanyProportion());
        sysUserLevelInsurance.setMaternityRadix(sysLevel.getMaternityRadix());
        sysUserLevelInsurance.setMaternityPersonalProportion(sysLevel.getMaternityPersonalProportion());
        sysUserLevelInsurance.setMaternityCompanyProportion(sysLevel.getMaternityCompanyProportion());
        sysUserLevelInsurance.setIndustrialInjuryRadix(sysLevel.getIndustrialInjuryRadix());
        sysUserLevelInsurance.setIndustrialInjuryPersonalProportion(sysLevel.getIndustrialInjuryPersonalProportion());
        sysUserLevelInsurance.setIndustrialInjuryCompanyProportion(sysLevel.getIndustrialInjuryCompanyProportion());
        // 保存
        sysUserLevelInsuranceRepository.save(sysUserLevelInsurance);
    }
}
/*
 *  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.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.config.FileProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.attendance.domain.Attendance;
import me.zhengjie.modules.attendance.domain.AttendanceBusinessTravel;
import me.zhengjie.modules.attendance.domain.AttendanceGoOut;
import me.zhengjie.modules.attendance.repository.AttendanceBusinessTravelRepository;
import me.zhengjie.modules.attendance.repository.AttendanceCardreplacementRepository;
import me.zhengjie.modules.attendance.repository.AttendanceGoOutRepository;
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
import me.zhengjie.modules.attendance.service.impl.AttendanceLeaveServiceImpl;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.repository.ProjectRepository;
import me.zhengjie.modules.quartz.utils.DateTimeUtil;
import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.modules.security.service.UserCacheManager;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.vo.CalendarVo;
import me.zhengjie.modules.system.repository.*;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.UserLoginMapper;
import me.zhengjie.modules.system.service.mapstruct.UserMapper;
import me.zhengjie.modules.system.service.mapstruct.UserSmallMapper;
import me.zhengjie.modules.task.domain.TaskDaliyMongo;
import me.zhengjie.modules.task.domain.TaskMongo;
import me.zhengjie.modules.task.service.dto.TaskDaliyMongoDto;
import me.zhengjie.modules.treatment.domain.*;
import me.zhengjie.modules.treatment.repository.*;
import me.zhengjie.utils.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @author Zheng Jie
 * @date 2018-11-23
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final ProjectRepository projectRepository;
    private final UserMapper userMapper;
    private final UserSmallMapper userSmallMapper;
    private final FileProperties properties;
    private final RedisUtils redisUtils;
    private final UserCacheManager userCacheManager;
    private final OnlineUserService onlineUserService;
    private final UserLoginMapper userLoginMapper;
    private final SysLevelRepository sysLevelRepository;
    private final SysUserLevelWageRepository sysUserLevelWageRepository;
    private final SysUserLevelInsuranceRepository sysUserLevelInsuranceRepository;
    private final SysUserLevelOtherRepository sysUserLevelOtherRepository;
    private final AttendanceRepository attendanceRepository;
    private final AttendanceLeaveServiceImpl attendanceLeaveService;
    private final AttendanceCardreplacementRepository attendanceCardreplacementRepository;
    private final SysConfigProportionRepository sysConfigProportionRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final SysCompanyRepository sysCompanyRepository;
    private final DeptRepository deptRepository;
    private final MeritLevelRepository meritLevelRepository;
    private final CmnLevelRepository cmnLevelRepository;
    private final CmnLevelRankRepository cmnLevelRankRepository;
    private final CmnInsuranceRepository cmnInsuranceRepository;
    private final MongoTemplate mongoTemplate;
    private final UserLevelWageRepository userLevelWageRepository;
    private final UserInsuranceRepository userInsuranceRepository;
    @Autowired
    private CacheManager cacheManager;
    @Override
    public Object queryAll(UserQueryCriteria criteria, Pageable pageable) {
        Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(userMapper::toDto));
    }
    @Override
    public List<DeptUserNodeDto> queryDeptUserByDeptId(Long deptId) {
        List<DeptUserNodeDto> result = new ArrayList<DeptUserNodeDto>();
        Optional<Dept> deptOpt = deptRepository.findById(deptId);
        if (deptOpt.isPresent()) {
            Dept dept = deptOpt.get();
            List<Dept> subDeptList = deptRepository.findByPid(deptId);
            subDeptList.forEach(subDept -> {
                DeptUserNodeDto deptUserNodeDto = new DeptUserNodeDto();
                deptUserNodeDto.setId(subDept.getId());
                deptUserNodeDto.setLabel(subDept.getName());
                deptUserNodeDto.setLeaf(false);
                result.add(deptUserNodeDto);
            });
            List<User> userList = userRepository.findByDeptAndEnabled(dept, true);
            userList.forEach(user -> {
                DeptUserNodeDto deptUserNodeDto = new DeptUserNodeDto();
                deptUserNodeDto.setId(user.getId());
                deptUserNodeDto.setLabel(user.getNickName());
                deptUserNodeDto.setLeaf(true);
                result.add(deptUserNodeDto);
            });
        }
        return result;
    }
    @Override
    public List<UserDto> getUserByTaskId(String taskId) {
        // 日历类
        Calendar calendar = Calendar.getInstance();
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 日历字符串
        String calendarStr = sdf.format(calendar.getTime());
        TaskMongo taskMongo = mongoTemplate.findById(taskId, TaskMongo.class);
        List<Long> containUserList = taskMongo.getContainUserList();
        List<User> userList = new ArrayList<>();
        if (containUserList.size() != 0) {
            for (Long userId : containUserList) {
                userList.add(userRepository.findById(userId).get());
            }
        }
        List<UserDto> userDto = userMapper.toDto(userList);
        for (int i = 0; i < userDto.size(); i++) {
            // 根据用户ID、指定年月查询用户级别工资
            SysUserLevelWage sysUserLevelWage = sysUserLevelWageRepository.findTargetYearMonth(userDto.get(i).getId(), calendarStr);
            // 判断用户级别工资是否为空
            if (sysUserLevelWage != null) {
                // 根据ID查询用户级别
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(SysLevel::new);
                // 用户
                userDto.get(i).setLevelName(sysLevel.getName());
            } else {
                // 用户
                userDto.get(i).setLevelName(null);
            }
        }
        return userDto;
    }
    @Override
    public List<UserDto> getAllUserByTaskId(String taskId) {
        // 日历类
        Calendar calendar = Calendar.getInstance();
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 日历字符串
        String calendarStr = sdf.format(calendar.getTime());
        TaskMongo taskMongo = mongoTemplate.findById(taskId, TaskMongo.class);
        List<Long> containUserList = taskMongo.getContainUserList();
        //递归添加
        addSubTaskUserList(taskMongo, containUserList);
        containUserList = containUserList.stream().distinct().collect(Collectors.toList());
        List<User> userList = new ArrayList<>();
        if (containUserList.size() != 0) {
            for (Long userId : containUserList) {
                userList.add(userRepository.findById(userId).get());
            }
        }
        List<UserDto> userDto = userMapper.toDto(userList);
        for (int i = 0; i < userDto.size(); i++) {
            // 根据用户ID、指定年月查询用户级别工资
            SysUserLevelWage sysUserLevelWage = sysUserLevelWageRepository.findTargetYearMonth(userDto.get(i).getId(), calendarStr);
            // 判断用户级别工资是否为空
            if (sysUserLevelWage != null) {
                // 根据ID查询用户级别
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(SysLevel::new);
                // 用户
                userDto.get(i).setLevelName(sysLevel.getName());
            } else {
                // 用户
                userDto.get(i).setLevelName(null);
            }
        }
        return userDto;
    }
    /**
     * 任务下的所有子级
     *
     * @param taskMongo
     * @param containUserList
     */
    public void addSubTaskUserList(TaskMongo taskMongo, List<Long> containUserList) {
        List<TaskMongo> subTasks = mongoTemplate.find(Query.query(Criteria.where("pid").is(taskMongo.getOld_id())), TaskMongo.class);
        for (TaskMongo subTask : subTasks) {
            containUserList.addAll(subTask.getContainUserList());
            addSubTaskUserList(subTask, containUserList);
        }
    }
    @Override
    @Cacheable(key = "'AllUser'")
    public List<DeptAndUser> getUserDept() {
        List<Dept> all = deptRepository.findAll();
        List<DeptAndUser> result = new ArrayList<>();
        // 根节点
        for (Dept dept : all) {
            if (dept.getPid() == null) {
                //没有上级部门,他们就是最顶级的菜单
                DeptAndUser deptAndUser = new DeptAndUser();
                deptAndUser.setValue(dept.getId());
                deptAndUser.setLabel(dept.getName());
                result.add(deptAndUser);
            }
        }
        List<DeptAndUser> list = new ArrayList<>();
        for (Dept dept : all) {
            // 一级节点
            if (dept.getPid() != null) {
                if (dept.getPid().equals(result.get(0).getValue())) {
                    DeptAndUser deptAndUser = new DeptAndUser();
                    deptAndUser.setLabel(dept.getName());
                    deptAndUser.setValue(dept.getId());
                    list.add(deptAndUser);
                }
            }
        }
        result.get(0).setChildren(list);
        for (int i = 0; i < list.size(); i++) {
            // 二级节点
            List<DeptAndUser> list_two = new ArrayList<>();
            for (Dept dept : all) {
                if (dept.getPid() != null) {
                    if (dept.getPid().equals(result.get(0).getChildren().get(i).getValue())) {
                        DeptAndUser deptAndUser = new DeptAndUser();
                        deptAndUser.setLabel(dept.getName());
                        deptAndUser.setValue(dept.getId());
                        list_two.add(deptAndUser);
                    }
                }
            }
            result.get(0).getChildren().get(i).setChildren(list_two);
        }
        for (int i = 0; i < result.get(0).getChildren().size(); i++) {
            for (int j = 0; j < result.get(0).getChildren().get(i).getChildren().size(); j++) {
                ArrayList<DeptAndUser> list_three = new ArrayList<>();
                for (Dept dept : all) {
                    if (dept.getPid() != null) {
                        if (dept.getPid().equals(result.get(0).getChildren().get(i).getChildren().get(j).getValue())) {
                            DeptAndUser deptAndUser = new DeptAndUser();
                            deptAndUser.setLabel(dept.getName());
                            deptAndUser.setValue(dept.getId());
                            list_three.add(deptAndUser);
                        }
                    }
                }
                result.get(0).getChildren().get(i).getChildren().get(j).setChildren(list_three);
            }
        }
        for (int i = 0; i < result.get(0).getChildren().size(); i++) {
            for (int j = 0; j < result.get(0).getChildren().get(i).getChildren().size(); j++) {
                for (int r = 0; r < result.get(0).getChildren().get(i).getChildren().get(j).getChildren().size(); r++) {
                    ArrayList<DeptAndUser> list_four = new ArrayList<>();
                    if (!(deptRepository.findById(result.get(0).getChildren().get(i).getChildren().get(j).getChildren().get(r).getValue()).get().getSubCount() == 0)) {
                        // 当前节点不是叶子节点
                        for (Dept dept : all) {
                            if (dept.getPid() != null) {
                                if (dept.getPid().equals(result.get(0).getChildren().get(i).getChildren().get(j).getChildren().get(r).getValue())) {
                                    DeptAndUser deptAndUser = new DeptAndUser();
                                    deptAndUser.setValue(dept.getId());
                                    deptAndUser.setLabel(dept.getName());
                                    list_four.add(deptAndUser);
                                }
                            }
                        }
                        result.get(0).getChildren().get(i).getChildren().get(j).getChildren().get(r).setChildren(list_four);
                    }
                }
            }
        }
        //return result;
        recursionGetData(result);
        return result;
    }
    public void recursionGetData(List<DeptAndUser> list) {
        for (DeptAndUser deptAndUser : list) {
            if (deptAndUser.getChildren() == null) {
                deptAndUser.setChildren(new ArrayList<DeptAndUser>());
            }
            if (deptAndUser.getChildren().size() > 0) {
                recursionGetData(deptAndUser.getChildren());
            }
            List<User> users = userRepository.findByDeptIdInAndEnabledWithSingle(deptAndUser.getValue(), true);
            for (User user : users) {
                DeptAndUser result_deptAndUser = new DeptAndUser();
                result_deptAndUser.setValue(user.getId());
                result_deptAndUser.setLabel(user.getNickName());
                deptAndUser.getChildren().add(result_deptAndUser);
            }
        }
    }
    @Override
    public Long[] getUserPidDept(Long id) {
        ArrayList<Long> list = new ArrayList<>();
        Long deptId_leaf = userRepository.findDeptIdByUserId(id);
        list.add(id);
        list.add(0, deptId_leaf);
        list = getPidNode(list, deptId_leaf);
        return list.toArray(new Long[list.size()]);
    }
    @Override
    public List<TaskDaliyMongo> getPerformanceDetail(Long nextMonth) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String nextMonth_ = df.format(new Date(nextMonth)).substring(0,7) + "-01";
        Calendar cal = Calendar.getInstance();
        cal.setTime(df.parse(nextMonth_));
        cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        String nextMonthFirstDay = df.format(cal.getTime());
        List<TaskDaliyMongo> daliyMongoList;
        try {
            daliyMongoList = mongoTemplate.find(
                    Query.query(
                                    new Criteria("userId").is(SecurityUtils.getCurrentUserId())
                                            .and("fillDate")
                                            .gte(new SimpleDateFormat("yyyy-MM-dd").parse(nextMonth_))
                                            .lt(new SimpleDateFormat("yyyy-MM-dd").parse(nextMonthFirstDay)))
                            .with(Sort.by(Sort.Order.desc("fillDate")))
                    , TaskDaliyMongo.class);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Collection<TaskDaliyMongo> daliyMongoValues = daliyMongoList.stream().collect(
            Collectors.groupingBy(
                (TaskDaliyMongo taskDaliyMongo) -> taskDaliyMongo.getTaskUserMongo().getTask().getName(),
                Collectors.reducing(
                    null,
                    (TaskDaliyMongo prev, TaskDaliyMongo cur) -> {
                        if (prev == null) {
                            cur.getTaskProgress();
                            cur.getTaskUserMongo().getPerformanceHours();
                            cur.getTaskUserMongo().getPerformanceType();
                            if ("1".equals(cur.getTaskUserMongo().getPerformanceType())) {
                                cur.setConsumedHours(BigDecimal.valueOf(cur.getTaskUserMongo().getPerformanceHours())
                                        .multiply(BigDecimal.valueOf(cur.getTaskProgress()))
                                        .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).doubleValue());
                            }
                            return cur;
                        }
                        if ("0".equals(cur.getTaskUserMongo().getPerformanceType())) {
                            prev.setConsumedHours(prev.getConsumedHours() + cur.getConsumedHours());
                        }
                        return prev;
                    }
                )
            )
        ).values();
        return new ArrayList<>(daliyMongoValues);
    }
    @Override
    public List<User> getUserInfose() {
        List<User> userList = new ArrayList<>();
        //获取当前登入人信息
        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user1.getRoles().iterator().next();
        //超管、总经理,痛苦哦经理查看全部
        if (Long.valueOf(role.getLevel()) == Constant.ROLE_LEVEL_SUPER || Long.valueOf(role.getLevel()) == Constant.ROLE_LEVEL_GENERAL) {
            userList = userRepository.findAllByEnabled(true);
        } else {
            userList = userRepository.findByUserId(user1.getId());
        }
        return userList;
    }
    @Override
    public void findByUserIdInAndCompanyId(List<Long> userIds, Long companyId) {
        userRepository.findByUserIdInAndCompanyId(userIds, companyId);
    }
    private ArrayList<Long> getPidNode(ArrayList<Long> list, Long deptId_leaf) {
        Long pidId = deptRepository.findPidIdByDeptId(deptId_leaf);
        if (pidId != null) {
            list.add(0, pidId);
            getPidNode(list, pidId);
        }
        return list;
    }
    @Override
//    @Cacheable(key = "'total'")
//    @CacheEvict(value = "total", allEntries = true)
//    @Transactional(rollbackFor = Exception.class)
    public List<UserSmallDto> querySmallAll(UserQueryCriteria criteria) {
        // 日历类
        Calendar calendar = Calendar.getInstance();
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 日历字符串
        String calendarStr = sdf.format(calendar.getTime());
        // 只查询有效数据
        criteria.setEnabled(true);
        // 查询用户数据
        List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<UserSmallDto> usersDto = userSmallMapper.toDto(users);
        // 循环用户
        for (int i = 0; i < usersDto.size(); i++) {
            // 根据用户ID、指定年月查询用户级别工资
            SysUserLevelWage sysUserLevelWage = sysUserLevelWageRepository.findTargetYearMonth(usersDto.get(i).getId(), calendarStr);
            // 判断用户级别工资是否为空
            if (sysUserLevelWage != null) {
                // 根据ID查询用户级别
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(SysLevel::new);
                // 用户
                usersDto.get(i).setLevelName(sysLevel.getName());
            } else {
                // 用户
                usersDto.get(i).setLevelName(null);
            }
        }
        return usersDto;
    }
    @Override
//    @Cacheable(key = "'total'")
//    @CacheEvict(value = "total", allEntries = true)
//    @Transactional(rollbackFor = Exception.class)
    public List<UserDto> queryAll(UserQueryCriteria criteria) {
        // 日历类
        Calendar calendar = Calendar.getInstance();
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 日历字符串
        String calendarStr = sdf.format(calendar.getTime());
        // 只查询有效数据
        criteria.setEnabled(true);
        // 查询用户数据
        List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<UserDto> usersDto = userMapper.toDto(users);
        // 循环用户
        for (int i = 0; i < usersDto.size(); i++) {
            // 根据用户ID、指定年月查询用户级别工资
            SysUserLevelWage sysUserLevelWage = sysUserLevelWageRepository.findTargetYearMonth(usersDto.get(i).getId(), calendarStr);
            // 判断用户级别工资是否为空
            if (sysUserLevelWage != null) {
                // 根据ID查询用户级别
                SysLevel sysLevel = sysLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(SysLevel::new);
                // 用户
                usersDto.get(i).setLevelName(sysLevel.getName());
            } else {
                // 用户
                usersDto.get(i).setLevelName(null);
            }
        }
        return usersDto;
    }
    @Override
    @Cacheable(key = "'id:' + #p0")
    @Transactional(rollbackFor = Exception.class)
    public UserDto findById(long id) {
        User user = userRepository.findById(id).orElseGet(User::new);
        ValidationUtil.isNull(user.getId(), "User", "id", id);
        return userMapper.toDto(user);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(User resources) {
        if (userRepository.findByUsername(resources.getUsername()) != null) {
            throw new EntityExistException(User.class, "username", resources.getUsername());
        }
        if (userRepository.findByEmail(resources.getEmail()) != null) {
            throw new EntityExistException(User.class, "email", resources.getEmail());
        }
        if (userRepository.findByPhone(resources.getPhone()) != null) {
            throw new EntityExistException(User.class, "phone", resources.getPhone());
        }
        redisUtils.del(CacheKey.TOTAL_USER);
        redisUtils.del("user::AllUser");
        userRepository.save(resources);
        // 判断用户级别变更
//        checkUserLevel(resources.getId(), null, resources.getLevelId());
        // 判断用户级别变更(新)
        checkUserLevelNew(resources);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User resources) throws Exception {
        User user = userRepository.findById(resources.getId()).orElseGet(User::new);
        ValidationUtil.isNull(user.getId(), "User", "id", resources.getId());
        User user1 = userRepository.findByUsername(resources.getUsername());
        User user2 = userRepository.findByEmail(resources.getEmail());
        User user3 = userRepository.findByPhone(resources.getPhone());
        if (user1 != null && !user.getId().equals(user1.getId())) {
            throw new EntityExistException(User.class, "username", resources.getUsername());
        }
        if (user2 != null && !user.getId().equals(user2.getId())) {
            throw new EntityExistException(User.class, "email", resources.getEmail());
        }
        if (user3 != null && !user.getId().equals(user3.getId())) {
            throw new EntityExistException(User.class, "phone", resources.getPhone());
        }
        // 如果用户的角色改变
        if (!resources.getRoles().equals(user.getRoles())) {
            redisUtils.del(CacheKey.DATA_USER + resources.getId());
            redisUtils.del(CacheKey.MENU_USER + resources.getId());
            redisUtils.del(CacheKey.ROLE_AUTH + resources.getId());
        }
        // 修改部门会影响 数据权限
        if (!Objects.equals(resources.getDept(), user.getDept())) {
            redisUtils.del(CacheKey.DATA_USER + resources.getId());
        }
        // 如果用户被禁用,则清除用户登录信息
        if (!resources.getEnabled()) {
            onlineUserService.kickOutForUsername(resources.getUsername());
        }
        // 临时旧用户级别ID
        Long tempOldLevelId = user.getLevelId();
        user.setUsername(resources.getUsername());
        user.setEmail(resources.getEmail());
        user.setEnabled(resources.getEnabled());
        user.setRoles(resources.getRoles());
        user.setDept(resources.getDept());
        user.setJobs(resources.getJobs());
        user.setPhone(resources.getPhone());
        user.setNickName(resources.getNickName());
        user.setCompany(resources.getCompany());
        user.setGender(resources.getGender());
        user.setBirthday(resources.getBirthday());
        user.setAddress(resources.getAddress());
        user.setDingding(resources.getDingding());
        user.setSysRostering(resources.getSysRostering());
        user.setLevelId(resources.getLevelId());
        // 临时新用户级别ID
        Long tempNewLevelId = user.getLevelId();
        redisUtils.del("user::AllUser");
        userRepository.save(user);
        // 判断用户级别变更
        checkUserLevel(user.getId(), tempOldLevelId, tempNewLevelId);
//        // 判断用户级别变更(新)
//        checkUserLevelNew(resources, tempOldLevelId, tempNewLevelId);
        // 清除缓存
        delCaches(user.getId(), user.getUsername());
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCenter(User resources) {
        User user = userRepository.findById(resources.getId()).orElseGet(User::new);
        User user1 = userRepository.findByPhone(resources.getPhone());
        if (user1 != null && !user.getId().equals(user1.getId())) {
            throw new EntityExistException(User.class, "phone", resources.getPhone());
        }
        user.setNickName(resources.getNickName());
        user.setPhone(resources.getPhone());
        user.setGender(resources.getGender());
        userRepository.save(user);
        // 清理缓存
        delCaches(user.getId(), user.getUsername());
    }
    /**
     * 获取日历信息
     *
     * @param month
     * @return
     * @throws Exception
     */
    @Override
    public List<CalendarVo> getUserCalendarInfo(String month) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<CalendarVo> calendarInfo = new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        //月份第一天,最后一天
        LocalDate startDate = LocalDate.parse(month).with(TemporalAdjusters.firstDayOfMonth());
        LocalDate endDate = LocalDate.parse(month).with(TemporalAdjusters.lastDayOfMonth());
        //当前登录人
        Long userId = SecurityUtils.getCurrentUserId();
        //查询这个范围的考勤记录
        List<Attendance> attendanceList = attendanceRepository.findAllByUserAndDate(userId, startDate.toString(), endDate.toString());
        for (Attendance attendance : attendanceList) {
            CalendarVo onDuty = new CalendarVo();
            onDuty.setDate(df.format(attendance.getAttendanceDate()));
            onDuty.setTitle(Constant.ATTENDANCE_STATE_NORMAL.equals(formateResult(attendance.getStartClockResults()).get("msg")) ? "上班打卡时间:" + attendance.getActualWorkStartTime().toString() : "上班:" + formateResult(attendance.getStartClockResults()).get("msg"));
            onDuty.setIsOk((Boolean) formateResult(attendance.getStartClockResults()).get("status"));
            onDuty.setType(1);
            CalendarVo offDuty = new CalendarVo();
            offDuty.setDate(df.format(attendance.getAttendanceDate()));
            offDuty.setTitle(Constant.ATTENDANCE_STATE_NORMAL.equals(formateResult(attendance.getEndClockResults()).get("msg")) ? "下班打卡时间:" + attendance.getActualWorkEndTime().toString() : "下班:" + formateResult(attendance.getEndClockResults()).get("msg"));
            offDuty.setIsOk((Boolean) formateResult(attendance.getEndClockResults()).get("status"));
            offDuty.setType(1);
            calendarInfo.add(onDuty);
            calendarInfo.add(offDuty);
            dateList.add(attendance.getAttendanceDate().toString());
        }
        //获取应工作时长
//        User user = userRepository.getById(userId);
//        Long duration = (Duration.between(user.getSysRostering().getWorkStartTime(), user.getSysRostering().getWorkEndTime())).toHours();
        //查询日志表
        List<TaskDaliyMongo> taskDaliyList = mongoTemplate.find(Query.query(new Criteria("userId").is(userId).and("fillDate").gte(startDate).lte(endDate)), TaskDaliyMongo.class);
        Map<String, Double> map = new HashMap<>();
        for (TaskDaliyMongo taskDaliy : taskDaliyList) {
            if (map.get(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0").format(taskDaliy.getFillDate())) != null) {
                // 如果已经有了
                Double todayHours = map.get(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0").format(taskDaliy.getFillDate()));
                todayHours += taskDaliy.getConsumedHours();
                map.put(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0").format(taskDaliy.getFillDate()), todayHours);
            } else {
                map.put(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0").format(taskDaliy.getFillDate()), taskDaliy.getConsumedHours());
            }
        }
        for (Map.Entry<String, Double> entry : map.entrySet()) {
            CalendarVo calendarVo = new CalendarVo();
            if (entry.getValue() >= 8) {
                calendarVo.setDate(entry.getKey());
                calendarVo.setIsOk(true);
                calendarVo.setTitle("工时:" + BigDecimal.valueOf(entry.getValue()).setScale(2, RoundingMode.HALF_UP));
                calendarVo.setType(2);
            } else {
                calendarVo.setDate(entry.getKey());
                calendarVo.setIsOk(false);
                calendarVo.setTitle("已填工时:" + BigDecimal.valueOf(entry.getValue()).setScale(2, RoundingMode.HALF_UP) + " 不足8小时,请补充日报");
                calendarVo.setType(2);
            }
            calendarInfo.add(calendarVo);
        }
        for (String date : dateList) {
            String type1 = "";
            String type2 = "";
            CalendarVo dailyVo = new CalendarVo();
            if (map.get(date) != null) {
                // 如果在map中找到了它的值,说明用户填写过日报
                continue;
            }
            dailyVo.setDate(date);
            for (Attendance attendanceRecord : attendanceList) {
                type1 = attendanceRecord.getStartClockResults();
                type2 = attendanceRecord.getEndClockResults();
                date = date.substring(0, 10);
                if (date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_LEAVE) && type2.equals(Constant.ATTENDANCE_STATE_LEAVE)) {
                    dailyVo.setTitle("请假");
                    dailyVo.setIsOk(true);
                } else if (date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_BUSINESS) && type2.equals(Constant.ATTENDANCE_STATE_BUSINESS)) {
                    dailyVo.setTitle("出差");
                    dailyVo.setIsOk(true);
                } else if (date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_REST) && type2.equals(Constant.ATTENDANCE_STATE_REST)) {
                    dailyVo.setTitle("休息");
                    dailyVo.setIsOk(true);
                } else if (date.equals(df.format(attendanceRecord.getAttendanceDate()))) {
                    dailyVo.setTitle("日报未填写,请补充日报");
                    dailyVo.setIsOk(false);
                }
            }
            dailyVo.setType(2);
            calendarInfo.add(dailyVo);
        }
        return calendarInfo;
    }
    /**
     * 判断状态
     *
     * @param result
     * @return
     */
    public Map formateResult(String result) {
        Map returnData = new HashMap();
        switch (result) {
            case Constant.ATTENDANCE_STATE_NOTSIGNED:
                returnData.put("msg", "缺卡");
                returnData.put("status", false);
                break;
            case Constant.ATTENDANCE_START_EARLY:
                returnData.put("msg", "早退");
                returnData.put("status", false);
                break;
            case Constant.ATTENDANCE_START_LATE:
                returnData.put("msg", "迟到");
                returnData.put("status", false);
                break;
            case Constant.ATTENDANCE_STATE_LACK_OF_TIME:
                returnData.put("msg", "缺时");
                returnData.put("status", false);
                break;
            case Constant.ATTENDANCE_STATE_LEAVE:
                returnData.put("msg", "请假");
                returnData.put("status", true);
                break;
            case Constant.ATTENDANCE_STATE_GOOUT:
                returnData.put("msg", "外出");
                returnData.put("status", true);
                break;
            case Constant.ATTENDANCE_STATE_BUSINESS:
                returnData.put("msg", "出差");
                returnData.put("status", true);
                break;
            case Constant.ATTENDANCE_STATE_WAITFOR:
                returnData.put("msg", "等待");
                returnData.put("status", true);
                break;
            case Constant.ATTENDANCE_STATE_REST:
                returnData.put("msg", "休息");
                returnData.put("status", true);
                break;
            default:
                returnData.put("msg", result);
                returnData.put("status", true);
        }
        return returnData;
    }
    /**
     * 获取用户基础信息
     *
     * @return
     * @throws ParseException
     */
    @Override
    public Map getUserBaseInfo(Date yearMonth) throws ParseException {
        // 返回集合
        Map returnData = new HashMap();
        // 当前登录用户
        Long userId = SecurityUtils.getCurrentUserId();
        // 目标年月字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sdfDate = sdf.format(yearMonth);
        // 目标年月初字符串
        String sdfFirstDate = DateUtil.getFirstDayOfMonthFull(sdfDate);
        // 目标年月末字符串
        String sdfLastDate = DateUtil.getLastDayOfMonthFull(sdfDate);
        // 出勤天数
        List<Attendance> attendanceRecordList = attendanceRepository.findAllByUserAndDate(userId, sdfFirstDate, sdfLastDate);
        int numDay = 0;
        for (Attendance attendance : attendanceRecordList) {
            if (!attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_REST) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_REST)) {
                numDay++;
            }
        }
        returnData.put("onDutyDays", numDay);
        // 剩余年假
        Double yearTimes = attendanceLeaveService.getYearTimeLength(userId);
        returnData.put("annualLeave", yearTimes);
        // 查询当月的补卡记录的条数
        Integer count = attendanceCardreplacementRepository.count(userId, sdfDate.substring(0, 7));
        // 查询配置表的每月补卡次数
        SysConfigProportion sysConfigProportion = sysConfigProportionRepository.findByTitle("每月可补卡次数");
        if (count >= sysConfigProportion.getProportion()) {
            returnData.put("cardLeft", 0);
        } else {
            returnData.put("cardLeft", (sysConfigProportion.getProportion() - count));
        }
        // 法定节假日
        List<String> holiday = new ArrayList<>();
        // 天数
        int shouldWordDays = 0;
        List<SysConfigHoliday> holidayConfigurationList = sysConfigHolidayRepository.findAll();
        for (SysConfigHoliday holidayConfiguration : holidayConfigurationList) {
            if (holidayConfiguration.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)
                    || holidayConfiguration.getDateType().equals(Constant.DATE_TYPE_HOLIDAYS)) {
                holiday.add(sdf.format(holidayConfiguration.getHolidayDate()));
            }
        }
        // 获取当月所有日期
        List<String> dateList = DateTimeUtil.getDayByMonth(sdfDate.substring(0, 4), sdfDate.substring(5, 7));
        Date date1 = new Date();
        String todayDay = sdf.format(date1);
        if (!todayDay.substring(0, 7).equals(sdfDate.substring(0, 7))) {
            todayDay = sdfLastDate;
        }
        // 工作日的天数
        for (String date : dateList) {
            Date isWeekEnd = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(isWeekEnd);
            if (isWeekEnd.compareTo(sdf.parse(todayDay)) <= 0) {
                if (!holiday.contains(date) && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
                    shouldWordDays += 1;
                }
            }
        }
        int num = shouldWordDays * 8;
        // 月初到今天应工作时长
        returnData.put("Time", num);
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        User user = userRepository.getById(userId);
        // 考勤上午时间
        Double attCheckOnDuration = 0.0;
        // 考勤下午时间
        Double attCheckOffDuration = 0.0;
        for (Attendance attendance : attendanceRecordList) {
            // 上班打卡时间不为空并且打卡状态不为出差外出的考勤记录
            if (ObjectUtils.isNotEmpty(attendance.getActualWorkStartTime()) && !attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_GOOUT) && !attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_BUSINESS)) {
                LocalDateTime attCheckOnTime = attendance.getActualWorkStartTime().toLocalDateTime();
                LocalDateTime scheduleStartTime = LocalDateTime.parse(attendance.getAttendanceDate().toString().substring(0, 10) + " " + user.getSysRostering().getLunchStartTime().toString() + ":00", formatter2);
                if (attCheckOnTime.compareTo(scheduleStartTime) <= 0) {
                    // 获得两个时间之间的相差值
                    Duration duration = Duration.between(attCheckOnTime, scheduleStartTime);
                    Long minutes = duration.toMinutes();
                    Double hour = Double.valueOf(String.valueOf(new BigDecimal(Double.valueOf(minutes) / 60).setScale(2, BigDecimal.ROUND_HALF_UP)));
                    attCheckOnDuration = attCheckOnDuration + hour;
                }
            }
            // 下班打卡时间不为空并且打卡状态不为出差外出的考勤记录
            if (ObjectUtils.isNotEmpty(attendance.getActualWorkEndTime()) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_GOOUT) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_BUSINESS)) {
                LocalDateTime attCheckOffTime = attendance.getActualWorkEndTime().toLocalDateTime();
                LocalDateTime scheduleEndTime = LocalDateTime.parse(attendance.getAttendanceDate().toString().substring(0, 10) + " " + user.getSysRostering().getLunchEndTime().toString() + ":00", formatter2);
                if (attCheckOffTime.compareTo(scheduleEndTime) > 0) {
                    // 获得两个时间之间的相差值
                    Duration duration = Duration.between(scheduleEndTime, attCheckOffTime);
                    Long minutes = duration.toMinutes();
                    Double hour = Double.valueOf(String.valueOf(new BigDecimal(Double.valueOf(minutes) / 60).setScale(2, BigDecimal.ROUND_HALF_UP)));
                    attCheckOffDuration = attCheckOffDuration + hour;
                }
            }
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        String startTime = sdfFirstDate.substring(0, 10) + " " + dateTimeFormatter.format(user.getSysRostering().getWorkStartTime());
        String endTime = todayDay.substring(0, 10) + " " + dateTimeFormatter.format(user.getSysRostering().getWorkEndTime());
        // 外出时长
        Double goOutTimes = 0.0;
        // 查询外出表
        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(userId, Timestamp.valueOf(startTime).toLocalDateTime(), Timestamp.valueOf(endTime).toLocalDateTime());
        for (AttendanceGoOut attendanceGoOut : attendanceGoOutList) {
            goOutTimes = goOutTimes + attendanceGoOut.getOutDuration();
        }
        // 出差时长
        Double bussTimes = 0.0;
        // 查询出差表
        List<AttendanceBusinessTravel> attendanceBusinessTravelList = attendanceBusinessTravelRepository.findByUserAndSEDate(userId, Timestamp.valueOf(sdfFirstDate).toLocalDateTime(), Timestamp.valueOf(todayDay.substring(0, 10) + " " + "00:00:00").toLocalDateTime());
        for (AttendanceBusinessTravel attendanceBusinessTravel : attendanceBusinessTravelList) {
            bussTimes = bussTimes + attendanceBusinessTravel.getTravelDuration();
        }
        returnData.put("Times", attCheckOnDuration + attCheckOffDuration + goOutTimes + (bussTimes * 8));
        // 查询某月已完成工时
        DecimalFormat decimalFormat = new DecimalFormat("0.##");
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(
            Query.query(
                new Criteria("userId").is(userId)
                    .and("fillDate")
                    .gte(new SimpleDateFormat("yyyy-MM-dd").parse(startTime))
                    .lte(new SimpleDateFormat("yyyy-MM-dd").parse(endTime)))
                .with(Sort.by(Sort.Order.desc("fillDate")))
            , TaskDaliyMongo.class);
        List<TaskDaliyMongoDto> resultList = daliyMongoList.stream().collect(
            Collectors.groupingBy(
                (TaskDaliyMongo taskDaliyMongo) -> taskDaliyMongo.getTaskUserMongo().getId(),
                Collectors.reducing(
                    null,
                    (TaskDaliyMongo prev, TaskDaliyMongo cur) -> {
                        if (prev == null) {
                            if ("1".equals(cur.getTaskUserMongo().getPerformanceType())) {
                                cur.setConsumedHours(BigDecimal.valueOf(cur.getTaskUserMongo().getPerformanceHours())
                                    .multiply(BigDecimal.valueOf(cur.getTaskProgress()))
                                    .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).doubleValue());
                            }
                            return cur;
                        }
                        if ("0".equals(cur.getTaskUserMongo().getPerformanceType())) {
                            prev.setConsumedHours(prev.getConsumedHours() + cur.getConsumedHours());
                        }
                        return prev;
                    }
                )
            )
        ).values().stream().map(taskDaliyMongo -> {
            if ("1".equals(taskDaliyMongo.getTaskUserMongo().getPerformanceType())) {
                // 查询日报表是否存在小于当前月填写的当前任务的日报
                List<TaskDaliyMongo> taskDaliyMongoSm = null;
                try {
                    taskDaliyMongoSm = mongoTemplate.find(
                        Query.query(new Criteria("userId").is(userId)
                            .and("taskUserMongo").is(taskDaliyMongo.getTaskUserMongo())
                            .and("fillDate").lt(new SimpleDateFormat("yyyy-MM-dd").parse(startTime)))
                        .with(Sort.by(Sort.Direction.DESC, "fillDate")), TaskDaliyMongo.class);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                //跨月
                if (taskDaliyMongoSm.size() > 0) {
                    Double performanceHours = taskDaliyMongoSm.get(0).getPerformanceHours();
                    if (performanceHours == null) {
                        performanceHours = taskDaliyMongoSm.get(0).getTaskUserMongo().getPerformanceHours();
                    }
                    BigDecimal lastValue = BigDecimal.valueOf(taskDaliyMongoSm.get(0).getTaskProgress())
                            .multiply(BigDecimal.valueOf(performanceHours))
                            .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
                    taskDaliyMongo.setConsumedHours(BigDecimal.valueOf(taskDaliyMongo.getConsumedHours()).subtract(lastValue).doubleValue());
                }
            }
            return taskDaliyMongo;
        })
//                .collect(
//            Collectors.groupingBy(
//                (TaskDaliyMongo taskDaliyMongo) -> taskDaliyMongo.getTaskUserMongo().getTask().getId(),
//                Collectors.reducing(
//                    null,
//                    (TaskDaliyMongo prev, TaskDaliyMongo cur) -> {
//                        if (prev == null) {
//                            return cur;
//                        }
//                        prev.setConsumedHours(prev.getConsumedHours() + cur.getConsumedHours());
//                        return prev;
//                    }
//                )
//            )
//        ).values().stream()
                .map(taskDaliyMongo -> {
            TaskDaliyMongoDto dto = new TaskDaliyMongoDto();
            dto.setId(taskDaliyMongo.getId());
            dto.setFillDate(taskDaliyMongo.getFillDate());
            dto.setUserNickName(userRepository.findById(SecurityUtils.getCurrentUserId()).get().getNickName());
            dto.setProjectId(taskDaliyMongo.getTaskUserMongo().getTask().getProjectId());
            dto.setProjectName(projectRepository.findById(taskDaliyMongo.getTaskUserMongo().getTask().getProjectId()).get().getName());
            dto.setTaskName(taskDaliyMongo.getTaskUserMongo().getTask().getName());
            dto.setTaskId(taskDaliyMongo.getTaskUserMongo().getTask().getId());
            dto.setConsumedHours(BigDecimal.valueOf(taskDaliyMongo.getConsumedHours()).setScale(2, RoundingMode.HALF_UP).doubleValue());
            dto.setTaskProgress(taskDaliyMongo.getTaskProgress());
            dto.setSettlementStatus(taskDaliyMongo.getSettlementStatus());
            dto.setRemarks(taskDaliyMongo.getRemarks());
            dto.setTaskUserMongo(taskDaliyMongo.getTaskUserMongo());
            return dto;
        }).collect(Collectors.toList());
        // 月初到今天绩效时长
        returnData.put("achievementsTime", resultList.stream().mapToDouble(TaskDaliyMongoDto::getConsumedHours).sum());
        // 绩效详细
        returnData.put("achievementsList", resultList);
        // 换休时长
        Double overTime = attendanceLeaveService.getOverTimeLength(userId);
        returnData.put("overTime", overTime);
        return returnData;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            // 清理缓存
            UserDto user = findById(id);
            delCaches(user.getId(), user.getUsername());
        }
        redisUtils.del(CacheKey.TOTAL_USER);
        userRepository.deleteAllByIdIn(ids);
    }
    @Override
    public UserDto findByName(String userName) {
        User user = userRepository.findByUsername(userName);
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", userName);
        } else {
            return userMapper.toDto(user);
        }
    }
    @Override
    public UserLoginDto getLoginData(String userName) {
        User user = userRepository.findByUsername(userName);
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", userName);
        } else {
            return userLoginMapper.toDto(user);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePass(String username, String pass) {
        userRepository.updatePass(username, pass, new Date());
        flushCache(username);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> updateAvatar(MultipartFile multipartFile) {
        // 文件大小验证
        FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize());
        // 验证文件上传的格式
        String image = "gif jpg png jpeg";
        String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        if (fileType != null && !image.contains(fileType)) {
            throw new BadRequestException("文件格式错误!, 仅支持 " + image + " 格式");
        }
        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        String oldPath = user.getAvatarPath();
        File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar());
        user.setAvatarPath(Objects.requireNonNull(file).getPath());
        user.setAvatarName(file.getName());
        userRepository.save(user);
        if (StringUtils.isNotBlank(oldPath)) {
            FileUtil.del(oldPath);
        }
        @NotBlank String username = user.getUsername();
        flushCache(username);
        return new HashMap<String, String>(1) {{
            put("avatar", file.getName());
        }};
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmail(String username, String email) {
        userRepository.updateEmail(username, email);
        flushCache(username);
    }
    @Override
    public void download(List<UserDto> queryAll, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
//        for (UserSmallDto userDTO : queryAll) {
//            List<String> roles = userDTO.getRoles().stream().map(RoleSmallDto::getName).collect(Collectors.toList());
//            String levelName = userDTO.getLevelId() != null ? sysLevelRepository.findById(userDTO.getLevelId()).orElseGet(SysLevel::new).getName() : "";
//            SysCompany sysCompany = sysCompanyRepository.findById(userDTO.getCompany().getId()).orElseGet(SysCompany::new);
//            Map<String, Object> map = new LinkedHashMap<>();
//            map.put("用户名", userDTO.getUsername());
//            map.put("角色", roles);
//            map.put("部门", userDTO.getDept().getName());
//            map.put("岗位", userDTO.getJobs().stream().map(JobSmallDto::getName).collect(Collectors.toList()));
//            map.put("邮箱", userDTO.getEmail());
//            map.put("钉钉号", userDTO.getDingding());
//            map.put("排班", userDTO.getSysRostering().getName());
//            map.put("级别", levelName);
//            map.put("所属公司", sysCompany == null ? "" : sysCompany.getLabel());
//            map.put("状态", userDTO.getEnabled() ? "启用" : "禁用");
//            map.put("手机号码", userDTO.getPhone());
//            map.put("修改密码的时间", userDTO.getPwdResetTime());
//            map.put("创建日期", userDTO.getCreateTime());
//            list.add(map);
//        }
        FileUtil.downloadExcel(list, response);
    }
    /**
     * 清理缓存
     *
     * @param id /
     */
    public void delCaches(Long id, String username) {
        redisUtils.del(CacheKey.USER_ID + id);
        flushCache(username);
    }
    /**
     * 清理 登陆时 用户缓存信息
     *
     * @param username /
     */
    private void flushCache(String username) {
        userCacheManager.cleanUserCache(username);
    }
    /**
     * 判断用户级别变更
     *
     * @param userId
     * @param oldLevelId
     * @param newLevelId
     */
    private void checkUserLevel(Long userId, Long oldLevelId, Long newLevelId) {
        // 查询级别表
        SysLevel sysLevel = sysLevelRepository.findById(newLevelId).orElseGet(SysLevel::new);
        // 判断新旧用户级别ID是否相等
        if (oldLevelId == null) {
            // 创建用户级别工资(旧)
            createSysUserLevelWage(userId, newLevelId);
            // 创建用户级别保险(旧)
            createSysUserLevelInsurance(userId, newLevelId);
        } else if (oldLevelId != newLevelId) {
            // 旧用户级别工资
            SysUserLevelWage oldSysUserLevelWage = sysUserLevelWageRepository.findLastByUserId(userId);
            // 判断旧用户级别工资是否为空
            if (oldSysUserLevelWage != null && oldSysUserLevelWage.getId() != null) {
                // 旧日期字符串
                String oldDateString = oldSysUserLevelWage.getStartDate().toString().substring(0, 10);
                // 获取当前日期
                Date nowDate = new Date();
                // 创建Calendar实例
                Calendar nowCalendar = Calendar.getInstance();
                // 设置当前时间
                nowCalendar.setTime(nowDate);
                // 新日期字符串
                String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0, 10);
                // 判断新、旧日期字符串
                if (oldDateString.equals(nowDateString)) {
                    throw new BadRequestException("每天只能调整一次级别,请明日再试!");
                }
                // 设置前一天时间
                nowCalendar.add(Calendar.DATE, -1);
                // 旧用户级别工资
                oldSysUserLevelWage.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
                // 保存
                sysUserLevelWageRepository.save(oldSysUserLevelWage);
            }
            // 创建用户级别工资(旧)
            createSysUserLevelWage(userId, newLevelId);
            // 旧用户级别保险
            SysUserLevelInsurance oldSysUserLevelInsurance = sysUserLevelInsuranceRepository.findLastByUserId(userId);
            // 判断旧用户级别保险是否为空
            if (oldSysUserLevelInsurance != null && oldSysUserLevelInsurance.getId() != null) {
                // 旧日期字符串
                String oldDateString = oldSysUserLevelInsurance.getStartDate().toString().substring(0, 10);
                // 获取当前日期
                Date nowDate = new Date();
                // 创建Calendar实例
                Calendar nowCalendar = Calendar.getInstance();
                // 设置当前时间
                nowCalendar.setTime(nowDate);
                // 新日期字符串
                String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0, 10);
                // 判断新、旧日期字符串
                if (oldDateString.equals(nowDateString)) {
                    throw new BadRequestException("每天只能调整一次级别,请明日再试!");
                }
                // 设置前一天时间
                nowCalendar.add(Calendar.DATE, -1);
                // 旧用户级别保险
                oldSysUserLevelInsurance.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
                // 保存
                sysUserLevelInsuranceRepository.save(oldSysUserLevelInsurance);
            }
            // 创建用户级别保险(旧)
            createSysUserLevelInsurance(userId, newLevelId);
            // 旧用户级别其他
            SysUserLevelOther oldSysUserLevelOther = sysUserLevelOtherRepository.findLastByUserId(userId);
            // 判断旧用户级别其他是否为空
            if (oldSysUserLevelOther != null && oldSysUserLevelOther.getId() != null) {
                // 旧日期字符串
                String oldDateString = oldSysUserLevelOther.getStartDate().toString().substring(0, 10);
                // 获取当前日期
                Date nowDate = new Date();
                // 创建Calendar实例
                Calendar nowCalendar = Calendar.getInstance();
                // 设置当前时间
                nowCalendar.setTime(nowDate);
                // 新日期字符串
                String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0, 10);
                // 判断新、旧日期字符串
                if (oldDateString.equals(nowDateString)) {
                    throw new BadRequestException("每天只能调整一次级别,请明日再试!");
                }
                // 设置前一天时间
                nowCalendar.add(Calendar.DATE, -1);
                // 旧用户级别保险
                oldSysUserLevelOther.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
                // 保存
                sysUserLevelOtherRepository.save(oldSysUserLevelOther);
            }
        } else {
        }
    }
    /**
     * 判断用户级别变更
     *
     * @param resources
     */
    private void checkUserLevelNew(User resources) {
        // 查询级别管理表
        CmnLevel cmnLevel = cmnLevelRepository.findById(resources.getLevelId()).orElseGet(CmnLevel::new);
        for (int i = 0; i < 2; i++) {
            if (i == 1) {
                // 创建第二条用户级别工资(新)
                createNewSysUserLevelWage(resources, cmnLevel, EnumerationType.SECOND_ENUM);
                // 创建第二条用户级别保险 (新)
                createNewSysUserLevelInsurance(resources, EnumerationType.SECOND_ENUM);
            } else {
                // 创建第一条用户级别工资(新)
                createNewSysUserLevelWage(resources, cmnLevel, EnumerationType.FIRST_ENUM);
                // 创建第一条用户级别保险 (新)
                createNewSysUserLevelInsurance(resources, EnumerationType.FIRST_ENUM);
            }
        }
        // 创建用户级别其他(新)
        createSysUserLevelOther(resources, cmnLevel);
    }
    /**
     * 创建用户级别工资(新)
     *
     * @param resources
     * @param cmnLevel
     */
    private void createNewSysUserLevelWage(User resources, CmnLevel cmnLevel, EnumerationType enumType) {
        Calendar calendar = Calendar.getInstance();
        // 用户级别工资
        UserLevelWage userLevelWage = new UserLevelWage();
        userLevelWage.setUserId(resources.getId());
        userLevelWage.setLevel(cmnLevel.getId());
        // 获取试用期结束的月初时间
        Timestamp result1 = getConfirmationTime(resources);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String resultValue = sdf.format(result1);
        if (enumType.equals(EnumerationType.FIRST_ENUM)) {
            userLevelWage.setYearMonth(sdf.format(new Timestamp(calendar.getTimeInMillis())));
        } else {
            userLevelWage.setYearMonth(resultValue);
        }
        // 查询最小的等级
        MeritLevel meritLevel = meritLevelRepository.findMinMeritStandardByLevelId(cmnLevel.getId());
        userLevelWage.setRank(meritLevel.getId());
        userLevelWage.setBasicWage(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(cmnLevel.getBasicWage().doubleValue() * 0.8) :cmnLevel.getBasicWage());
        userLevelWage.setRankWage(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(cmnLevel.getRankWage().doubleValue() * 0.8) : cmnLevel.getRankWage());
        userLevelWage.setPerformanceWage(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(cmnLevel.getPerformanceWage().doubleValue() * 0.8) : cmnLevel.getPerformanceWage());
        // 查询绩效系数
        CmnLevelRank cmnLevelRank = cmnLevelRankRepository.findbylevelSm(cmnLevel.getId());
        userLevelWage.setPerformanceCoefficient(new BigDecimal(cmnLevelRank.getPerformanceCoefficient()));
        // 保存
        userLevelWageRepository.save(userLevelWage);
    }
    /**
     * 创建用户级别保险 (新)
     *
     * @param resources
     */
    public void createNewSysUserLevelInsurance(User resources, EnumerationType enumType) {
        Calendar calendar = Calendar.getInstance();
        // 用户级别工资
        UserInsurance userInsurance = new UserInsurance();
        userInsurance.setUserId(resources.getId());
        // 获取试用期结束的月初时间
        Timestamp result = getConfirmationTime(resources);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String resultValue = sdf.format(result);
        if (enumType.equals(EnumerationType.FIRST_ENUM)) {
            userInsurance.setYearMonth(sdf.format(new Timestamp(calendar.getTimeInMillis())));
        } else {
            userInsurance.setYearMonth(resultValue);
        }
        // 根据选择的公司查询五险一金
        CmnInsurance cmnInsurance = cmnInsuranceRepository.findByCompany(resources.getCompany()).orElseGet(CmnInsurance::new);
        userInsurance.setAccumulationFund(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getAccumulationFund());
        userInsurance.setAccumulationFundPersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getAccumulationFundPersonal());
        userInsurance.setAccumulationFundCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getAccumulationFundCompany());
        userInsurance.setRetirementInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getRetirementInsurance());
        userInsurance.setRetirementInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getRetirementInsurancePersonal());
        userInsurance.setRetirementInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getRetirementInsuranceCompany());
        userInsurance.setMedicalInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getMedicalInsurance());
        userInsurance.setMedicalInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getMedicalInsurancePersonal());
        userInsurance.setMedicalInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getMedicalInsuranceCompany());
        userInsurance.setUnemploymentInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getUnemploymentInsurance());
        userInsurance.setUnemploymentInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getUnemploymentInsurancePersonal());
        userInsurance.setUnemploymentInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getUnemploymentInsuranceCompany());
        userInsurance.setBirthInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getBirthInsurance());
        userInsurance.setBirthInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getBirthInsurancePersonal());
        userInsurance.setBirthInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getBirthInsuranceCompany());
        userInsurance.setEmploymentInsurance(enumType.equals(EnumerationType.FIRST_ENUM) ? new BigDecimal(0) : cmnInsurance.getEmploymentInsurance());
        userInsurance.setEmploymentInsurancePersonal(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getEmploymentInsurancePersonal());
        userInsurance.setEmploymentInsuranceCompany(enumType.equals(EnumerationType.FIRST_ENUM) ? new Double(0) : cmnInsurance.getEmploymentInsuranceCompany());
        // 保存
        userInsuranceRepository.save(userInsurance);
    }
    /**
     * 创建用户级别其他(新)
     * @param resources
     * @param cmnLevel
     */
    private void createSysUserLevelOther(User resources, CmnLevel cmnLevel) {
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM");
        // 获取试用期结束的月初时间
        Timestamp result = getConfirmationTime(resources);
        // 获取实习期结束的年份
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(result);
        int formalYear = calendar.get(Calendar.YEAR);
        // 获取当前年份
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
//        for (int i = 0; i < 2; i++) {
//            // 第一条记录
//            SysUserLevelOther sysUserLevelOther = new SysUserLevelOther();
//            sysUserLevelOther.setUserId(resources.getId());
//            sysUserLevelOther.setLevelId(cmnLevel.getId());
//            sysUserLevelOther.setPersonalPerformanceProportion(Double.valueOf(0));
//
//            if (i == 1) {
//                // 计算剩余年假
//                Double annualLeave = getAnnualLeave(calendar);
//                sysUserLevelOther.setAnnualLeaveDays(annualLeave);
//            } else {
//                calendar.add(Calendar.YEAR, 1);
//                // 设置月份为一月
//                calendar.set(Calendar.MONTH, Calendar.JANUARY);
//                // 设置月份为一日
//                calendar.set(Calendar.DAY_OF_MONTH, 1);
//
//                sysUserLevelOther.setAnnualLeaveDays(5.0);
//            }
//            // 年月
//            sysUserLevelOther.setYearMonth(sdf.format(calendar.getTime()));
//
//
//            sysUserLevelOtherRepository.save(sysUserLevelOther);
//        }
        // 添加两条数据
        for (int i = 0; i < 2; i++) {
            if (i == 0) {
                // 第一条记录
                SysUserLevelOther sysUserLevelOther = new SysUserLevelOther();
                sysUserLevelOther.setUserId(resources.getId());
                sysUserLevelOther.setLevelId(cmnLevel.getId());
                sysUserLevelOther.setPersonalPerformanceProportion(Double.valueOf(0));
                sysUserLevelOther.setStartDate(Timestamp.valueOf(LocalDate.now().atStartOfDay()));
                // 计算剩余年假
                Double annualLeave = getAnnualLeave(calendar);
                sysUserLevelOther.setAnnualLeaveDays(annualLeave);
                // 判断为今年设置为当前日期
                if (formalYear == currentYear) {
                    sysUserLevelOther.setYearMonth(sdf.format(new Date()));
                } else {
                    // 设置为明年转正日期
                    sysUserLevelOther.setYearMonth(sdf.format(calendar.getTime()));
                }
                sysUserLevelOtherRepository.save(sysUserLevelOther);
            } else {
                // 第二条记录
                SysUserLevelOther sysUserLevelOther1 = new SysUserLevelOther();
                sysUserLevelOther1.setUserId(resources.getId());
                sysUserLevelOther1.setLevelId(cmnLevel.getId());
                Calendar calendar1 = Calendar.getInstance();
                calendar1.add(Calendar.YEAR, 1);
                // 设置月份为一月
                calendar1.set(Calendar.MONTH, Calendar.JANUARY);
                calendar1.set(Calendar.DAY_OF_MONTH, 1);
                sysUserLevelOther1.setPersonalPerformanceProportion(Double.valueOf(0));
                sysUserLevelOther1.setAnnualLeaveDays(5.0);
                // 判断实习期结束日期的年份不是今年,年份加1
                if (formalYear != currentYear) {
                    // 在增加一年
                    calendar1.add(Calendar.YEAR, 1);
                }
                // 日期设置为 明年/后年 年初
                sysUserLevelOther1.setYearMonth(sdf.format(calendar1.getTime()));
                sysUserLevelOther1.setStartDate(new Timestamp(calendar1.getTimeInMillis()));
                sysUserLevelOtherRepository.save(sysUserLevelOther1);
            }
        }
    }
    /**
     * 获取转正的月初时间
     *
     * @return
     */
    private Timestamp getConfirmationTime(User resources) {
        Calendar calendar = Calendar.getInstance();
        // 获取 Calendar 对象所代表的时间
        calendar.setTime(new Timestamp(calendar.getTimeInMillis()));
        // 获取是一个月中的哪一天
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        // 获取这个月有多少天
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        Timestamp result;
        if (dayOfMonth <= daysInMonth / 2) {
            // 实习时间为空默认三个月,用户是在前半个月加入的,算上本月获取两个月之后的日期
            calendar.add(Calendar.MONTH, resources.getInternshipTime() == null ? 3 : resources.getInternshipTime());
        } else {
            // 用户是在后半个月加入的,不算本月获取三个月之后的日期
            calendar.add(Calendar.MONTH, resources.getInternshipTime() == null ? 4 : resources.getInternshipTime() + 1);
        }
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        result = new Timestamp(calendar.getTimeInMillis());
        return result;
    }
    /**
     * 获取年假
     * @param calendar
     * @return
     */
    private Double getAnnualLeave(Calendar calendar) {
        // 转正的月份
        int joinMonth = calendar.get(Calendar.MONTH);
        Double annualLeave = 0.0;
        int remainingMonths = 12 - joinMonth;
        // 计算年假天数
        annualLeave = (5.0 / 12) * remainingMonths;
        BigDecimal big = new BigDecimal(annualLeave);
        big = big.setScale(1, BigDecimal.ROUND_HALF_UP);
        annualLeave = big.doubleValue();
        return annualLeave;
    }
    /**
     * 创建用户级别工资(旧)
     *
     * @param userId
     * @param levelId
     */
    private void createSysUserLevelWage(Long userId, Long levelId) {
        // 级别
        SysLevel sysLevel = sysLevelRepository.findById(levelId).orElseGet(SysLevel::new);
        // 用户级别工资
        SysUserLevelWage sysUserLevelWage = new SysUserLevelWage();
        sysUserLevelWage.setUserId(userId);
        sysUserLevelWage.setLevelId(levelId);
        sysUserLevelWage.setStartDate(new Timestamp(new Date().getTime()));
        sysUserLevelWage.setLevelWage(sysLevel.getLevelWage());
        sysUserLevelWage.setBasicWageProportion(sysLevel.getBasicWageProportion());
        sysUserLevelWage.setAchievementsWageProportion(sysLevel.getAchievementsWageProportion());
        sysUserLevelWage.setPerformanceWageProportion(sysLevel.getPerformanceWageProportion());
        sysUserLevelWage.setTeamWageProportion(sysLevel.getTeamWageProportion());
        // 保存
        sysUserLevelWageRepository.save(sysUserLevelWage);
    }
    // 创建用户级别保险(旧)
    private void createSysUserLevelInsurance(Long userId, Long levelId) {
        // 级别
        SysLevel sysLevel = sysLevelRepository.findById(levelId).orElseGet(SysLevel::new);
        // 用户级别工资
        SysUserLevelInsurance sysUserLevelInsurance = new SysUserLevelInsurance();
        sysUserLevelInsurance.setUserId(userId);
        sysUserLevelInsurance.setLevelId(levelId);
        sysUserLevelInsurance.setStartDate(new Timestamp(new Date().getTime()));
        sysUserLevelInsurance.setAccumulationRadix(sysLevel.getAccumulationRadix());
        sysUserLevelInsurance.setAccumulationPersonalProportion(sysLevel.getAccumulationPersonalProportion());
        sysUserLevelInsurance.setAccumulationCompanyProportion(sysLevel.getAccumulationCompanyProportion());
        sysUserLevelInsurance.setPensionRadix(sysLevel.getPensionRadix());
        sysUserLevelInsurance.setPensionPersonalProportion(sysLevel.getPensionPersonalProportion());
        sysUserLevelInsurance.setPensionCompanyProportion(sysLevel.getPensionCompanyProportion());
        sysUserLevelInsurance.setMedicalRadix(sysLevel.getMedicalRadix());
        sysUserLevelInsurance.setMedicalPersonalProportion(sysLevel.getMedicalPersonalProportion());
        sysUserLevelInsurance.setMedicalCompanyProportion(sysLevel.getMedicalCompanyProportion());
        sysUserLevelInsurance.setUnemploymentRadix(sysLevel.getUnemploymentRadix());
        sysUserLevelInsurance.setUnemploymentPersonalProportion(sysLevel.getUnemploymentPersonalProportion());
        sysUserLevelInsurance.setUnemploymentCompanyProportion(sysLevel.getUnemploymentCompanyProportion());
        sysUserLevelInsurance.setMaternityRadix(sysLevel.getMaternityRadix());
        sysUserLevelInsurance.setMaternityPersonalProportion(sysLevel.getMaternityPersonalProportion());
        sysUserLevelInsurance.setMaternityCompanyProportion(sysLevel.getMaternityCompanyProportion());
        sysUserLevelInsurance.setIndustrialInjuryRadix(sysLevel.getIndustrialInjuryRadix());
        sysUserLevelInsurance.setIndustrialInjuryPersonalProportion(sysLevel.getIndustrialInjuryPersonalProportion());
        sysUserLevelInsurance.setIndustrialInjuryCompanyProportion(sysLevel.getIndustrialInjuryCompanyProportion());
        // 保存
        sysUserLevelInsuranceRepository.save(sysUserLevelInsurance);
    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/domain/TaskDaliyMongo.java
@@ -1,79 +1,81 @@
/*
*  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.task.domain;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import cn.hutool.core.date.DateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @website https://eladmin.vip
* @description /
* @author 赵士淞
* @date 2022-12-30
**/
@Data
@Document("task_daliy")
public class TaskDaliyMongo implements Serializable {
    @Id
    private String id;
//    @ApiModelProperty(value = "项目ID")
//    private Long projectId;
    @ApiModelProperty(value = "任务ID")
    private String taskId;
    @DBRef
    private TaskUserMongo taskUserMongo;
    @ApiModelProperty(value = "员工ID")
    private Long userId;
    private Long old_task_id;
    @ApiModelProperty(value = "填写日期")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date fillDate;
    @ApiModelProperty(value = "消耗工时")
    private Double consumedHours;
    @ApiModelProperty(value = "绩效工时")
    private Double performanceHours;
    @ApiModelProperty(value = "消耗工作量")
    private Double consumedWorkload;
    @ApiModelProperty(value = "任务进度")
    private Double taskProgress;
    @ApiModelProperty(value = "结算状态")
    private String settlementStatus;
    @ApiModelProperty(value = "备注")
    private String remarks;
}
/*
*  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.task.domain;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import cn.hutool.core.date.DateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @website https://eladmin.vip
* @description /
* @author 赵士淞
* @date 2022-12-30
**/
@Data
@Document("task_daliy")
public class TaskDaliyMongo implements Serializable {
    @Id
    private String id;
//    @ApiModelProperty(value = "项目ID")
//    private Long projectId;
    @ApiModelProperty(value = "任务ID")
    private String taskId;
    @DBRef
    private TaskUserMongo taskUserMongo;
    @ApiModelProperty(value = "员工ID")
    private Long userId;
    private String userName;
    private Long old_task_id;
    @ApiModelProperty(value = "填写日期")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date fillDate;
    @ApiModelProperty(value = "消耗工时")
    private Double consumedHours;
    @ApiModelProperty(value = "绩效工时")
    private Double performanceHours;
    @ApiModelProperty(value = "消耗工作量")
    private Double consumedWorkload;
    @ApiModelProperty(value = "任务进度")
    private Double taskProgress;
    @ApiModelProperty(value = "结算状态")
    private String settlementStatus;
    @ApiModelProperty(value = "备注")
    private String remarks;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/domain/TaskUserMongo.java
@@ -1,86 +1,88 @@
/*
*  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.task.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @website https://eladmin.vip
* @description /
* @author 赵士淞
* @date 2022-12-28
**/
@Data
@Document("task_user")
public class TaskUserMongo implements Serializable {
    @Id
    @ApiModelProperty(value = "ID")
    private String id;
    private Long old_id;
    @ApiModelProperty(value = "任务ID")
    @DBRef
    private TaskMongo task;
    private String name;
    @ApiModelProperty(value = "绩效类型")
    private String performanceType;
    @ApiModelProperty(value = "用户ID")
    private Long userId;
    @ApiModelProperty(value = "任务开始时间")
    private Date taskStartDate;
    @ApiModelProperty(value = "任务结束时间")
    private Date taskEndDate;
    @ApiModelProperty(value = "优先度")
    private String priority;
    //private List<TaskDaliyMongo> taskDaliyList = new LinkedList<TaskDaliyMongo>();
    @ApiModelProperty(value = "任务工时")
    private Double taskHours = 0.0;
    @ApiModelProperty(value = "绩效工时")
    private Double performanceHours = 0.0;
    @ApiModelProperty(value = "消耗工时")
    private Double costHours = 0.0;
    @ApiModelProperty(value = "任务状态")
    private String taskStatus;
    @ApiModelProperty(value = "备注")
    private String remarks;
    @ApiModelProperty(value = "进度")
    private Double newTaskProgress = 0.0;
}
/*
*  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.task.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @website https://eladmin.vip
* @description /
* @author 赵士淞
* @date 2022-12-28
**/
@Data
@Document("task_user")
public class TaskUserMongo implements Serializable {
    @Id
    @ApiModelProperty(value = "ID")
    private String id;
    private Long old_id;
    @ApiModelProperty(value = "任务ID")
    @DBRef
    private TaskMongo task;
    private String name;
    @ApiModelProperty(value = "绩效类型")
    private String performanceType;
    @ApiModelProperty(value = "用户ID")
    private Long userId;
    @ApiModelProperty(value = "任务开始时间")
    private Date taskStartDate;
    @ApiModelProperty(value = "任务结束时间")
    private Date taskEndDate;
    @ApiModelProperty(value = "优先度")
    private String priority;
    private String uid;
    //private List<TaskDaliyMongo> taskDaliyList = new LinkedList<TaskDaliyMongo>();
    @ApiModelProperty(value = "任务工时")
    private Double taskHours = 0.0;
    @ApiModelProperty(value = "绩效工时")
    private Double performanceHours = 0.0;
    @ApiModelProperty(value = "消耗工时")
    private Double costHours = 0.0;
    @ApiModelProperty(value = "任务状态")
    private String taskStatus;
    @ApiModelProperty(value = "备注")
    private String remarks;
    @ApiModelProperty(value = "进度")
    private Double newTaskProgress = 0.0;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/rest/TaskController.java
@@ -1,207 +1,207 @@
/*
*  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.task.rest;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.project.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.task.domain.TaskMongo;
import me.zhengjie.modules.task.service.TaskService;
import me.zhengjie.modules.task.service.TaskUserService;
import me.zhengjie.modules.task.service.dto.TaskQueryCriteria;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @author 赵士淞
* @date 2022-12-27
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "任务管理")
@RequestMapping("/api/task")
public class TaskController {
    private final TaskService taskService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('task:download')")
    public void exportTask(HttpServletResponse response, TaskQueryCriteria criteria) throws IOException {
//        taskService.download(taskService.queryAll(criteria), response);
    }
    @GetMapping
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryTask(TaskQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(taskService.queryAll(criteria, pageable), HttpStatus.OK);
    }
    @GetMapping(value = "/projects")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> getAllProjects(ProjectQueryCriteria criteria){
        return new ResponseEntity<>(taskService.getAllProjects(criteria),HttpStatus.OK);
    }
    @GetMapping(value = "/tags")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryAllTags(String tagName){
        return new ResponseEntity<>(taskService.getAllTags(tagName), HttpStatus.OK);
    }
    @GetMapping(value = "/names")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryAllNames(Long projectId, String name){
        return new ResponseEntity<>(taskService.getAllNames(projectId, name), HttpStatus.OK);
    }
    @GetMapping(value = "/all")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryTask(TaskQueryCriteria criteria){
        return new ResponseEntity<>(taskService.queryAll(criteria),HttpStatus.OK);
    }
    @GetMapping(value = "/getAllOfDaily")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryTaskOfDaily(Long projectId){
        return new ResponseEntity<>(taskService.allOfDaily(projectId),HttpStatus.OK);
    }
    @GetMapping(value = "/children")
    @Log("查询子级任务")
    @ApiOperation("查询子级任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryChildrenTask(TaskQueryCriteria criteria){
        return new ResponseEntity<>(taskService.queryChildren(criteria),HttpStatus.OK);
    }
    @GetMapping(value = "/ChildrenTaskAnyParent")
    public ResponseEntity<Object> queryChildrenTaskAnyParent(TaskQueryCriteria criteria){
        return new ResponseEntity<>(taskService.queryChildrenTaskAnyParent(SecurityUtils.getCurrentUserId(),criteria),HttpStatus.OK);
    }
    @PostMapping
    @Log("新增任务")
    @ApiOperation("新增任务")
    @PreAuthorize("@el.check('task:add')")
    public ResponseEntity<Object> createTask(@Validated @RequestBody TaskMongo resources){
        return new ResponseEntity<>(taskService.create(SecurityUtils.getCurrentUserId(),resources),HttpStatus.CREATED);
    }
    @PutMapping
    @Log("修改任务")
    @ApiOperation("修改任务")
    @PreAuthorize("@el.check('task:edit')")
    public ResponseEntity<Object> updateTask(@Validated @RequestBody TaskMongo resources){
        return new ResponseEntity<>(taskService.update(SecurityUtils.getCurrentUserId(),resources), HttpStatus.NO_CONTENT);
    }
    @DeleteMapping
    @Log("删除任务")
    @ApiOperation("删除任务")
    @PreAuthorize("@el.check('task:del')")
    public ResponseEntity<Object> deleteTask(@RequestBody String[] ids) {
        return new ResponseEntity<>(taskService.deleteAll(SecurityUtils.getCurrentUserId(),ids), HttpStatus.OK);
    }
    @GetMapping(value = "/total")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryTask(@RequestParam Long projectId){
        return new ResponseEntity<>(taskService.queryProjectTotal(projectId),HttpStatus.OK);
    }
//    @PostMapping(value = "/divide")
//    @Log("分配任务")
//    @ApiOperation("分配任务")
//    @PreAuthorize("@el.check('task:divide')")
//    public ResponseEntity<Object> divideTask(@Validated @RequestBody TaskUserDto resources) throws Exception {
//        taskUserService.divide(resources);
//        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
//    }
//
//    @GetMapping(value = "/partake")
//    @Log("查询参与的任务")
//    @ApiOperation("查询参与的任务")
//    @PreAuthorize("@el.check('task:list')")
//    public ResponseEntity<Object> queryPartakeTaskAll(TaskQueryCriteria criteria){
//        return new ResponseEntity<>(taskService.queryPartakeAll(criteria),HttpStatus.OK);
//    }
    @GetMapping(value = "/getRelevantTaskUser")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> getRelevantTaskUser(String taskId){
        return new ResponseEntity<>(taskService.getRelevantTaskUser(taskId),HttpStatus.OK);
    }
    @GetMapping("/changeStatus")
    public ResponseEntity<Object> changeStatus(String[] changesId){
        taskService.changeStatus(changesId);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    @GetMapping("/getTaskValidRange")
    public ResponseEntity<Object> getTaskValidRange(String taskId){
        return new ResponseEntity<>(taskService.getTaskValidRange(taskId),HttpStatus.OK);
    }
    @GetMapping("/getTaskCalendarInfo")
    public ResponseEntity<Object> getTaskCalendarInfo(String date,String taskId){
        return new ResponseEntity<>(taskService.getTaskCalendarInfo(date, taskId),HttpStatus.OK);
    }
    @GetMapping("/getTastAll")
    @Log("根据任务ID查询任务")
    public ResponseEntity<Object> getTastAll(String taskId){
        return new ResponseEntity<>(taskService.getTastAllById(taskId),HttpStatus.OK);
    }
    @GetMapping("/getTasts")
    @Log("根据任务名字查询任务")
    public ResponseEntity<Object> getTasts(String taskName){
        return new ResponseEntity<>(taskService.getTastByName(taskName),HttpStatus.OK);
    }
/*
*  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.task.rest;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.project.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.task.domain.TaskMongo;
import me.zhengjie.modules.task.service.TaskService;
import me.zhengjie.modules.task.service.TaskUserService;
import me.zhengjie.modules.task.service.dto.TaskQueryCriteria;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @author 赵士淞
* @date 2022-12-27
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "任务管理")
@RequestMapping("/api/task")
public class TaskController {
    private final TaskService taskService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('task:download')")
    public void exportTask(HttpServletResponse response, TaskQueryCriteria criteria) throws IOException {
        taskService.download(taskService.queryAll(criteria), response);
    }
    @GetMapping
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryTask(TaskQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(taskService.queryAll(criteria, pageable), HttpStatus.OK);
    }
    @GetMapping(value = "/projects")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> getAllProjects(ProjectQueryCriteria criteria){
        return new ResponseEntity<>(taskService.getAllProjects(criteria),HttpStatus.OK);
    }
    @GetMapping(value = "/tags")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryAllTags(String tagName){
        return new ResponseEntity<>(taskService.getAllTags(tagName), HttpStatus.OK);
    }
    @GetMapping(value = "/names")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryAllNames(Long projectId, String name){
        return new ResponseEntity<>(taskService.getAllNames(projectId, name), HttpStatus.OK);
    }
    @GetMapping(value = "/all")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryTask(TaskQueryCriteria criteria){
        return new ResponseEntity<>(taskService.queryAll(criteria),HttpStatus.OK);
    }
    @GetMapping(value = "/getAllOfDaily")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryTaskOfDaily(Long projectId){
        return new ResponseEntity<>(taskService.allOfDaily(projectId),HttpStatus.OK);
    }
    @GetMapping(value = "/children")
    @Log("查询子级任务")
    @ApiOperation("查询子级任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryChildrenTask(TaskQueryCriteria criteria){
        return new ResponseEntity<>(taskService.queryChildren(criteria),HttpStatus.OK);
    }
    @GetMapping(value = "/ChildrenTaskAnyParent")
    public ResponseEntity<Object> queryChildrenTaskAnyParent(TaskQueryCriteria criteria){
        return new ResponseEntity<>(taskService.queryChildrenTaskAnyParent(SecurityUtils.getCurrentUserId(),criteria),HttpStatus.OK);
    }
    @PostMapping
    @Log("新增任务")
    @ApiOperation("新增任务")
    @PreAuthorize("@el.check('task:add')")
    public ResponseEntity<Object> createTask(@Validated @RequestBody TaskMongo resources){
        return new ResponseEntity<>(taskService.create(SecurityUtils.getCurrentUserId(),resources),HttpStatus.CREATED);
    }
    @PutMapping
    @Log("修改任务")
    @ApiOperation("修改任务")
    @PreAuthorize("@el.check('task:edit')")
    public ResponseEntity<Object> updateTask(@Validated @RequestBody TaskMongo resources){
        return new ResponseEntity<>(taskService.update(SecurityUtils.getCurrentUserId(),resources), HttpStatus.NO_CONTENT);
    }
    @DeleteMapping
    @Log("删除任务")
    @ApiOperation("删除任务")
    @PreAuthorize("@el.check('task:del')")
    public ResponseEntity<Object> deleteTask(@RequestBody String[] ids) {
        return new ResponseEntity<>(taskService.deleteAll(SecurityUtils.getCurrentUserId(),ids), HttpStatus.OK);
    }
    @GetMapping(value = "/total")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> queryTask(@RequestParam Long projectId){
        return new ResponseEntity<>(taskService.queryProjectTotal(projectId),HttpStatus.OK);
    }
//    @PostMapping(value = "/divide")
//    @Log("分配任务")
//    @ApiOperation("分配任务")
//    @PreAuthorize("@el.check('task:divide')")
//    public ResponseEntity<Object> divideTask(@Validated @RequestBody TaskUserDto resources) throws Exception {
//        taskUserService.divide(resources);
//        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
//    }
//
//    @GetMapping(value = "/partake")
//    @Log("查询参与的任务")
//    @ApiOperation("查询参与的任务")
//    @PreAuthorize("@el.check('task:list')")
//    public ResponseEntity<Object> queryPartakeTaskAll(TaskQueryCriteria criteria){
//        return new ResponseEntity<>(taskService.queryPartakeAll(criteria),HttpStatus.OK);
//    }
    @GetMapping(value = "/getRelevantTaskUser")
    @Log("查询任务")
    @ApiOperation("查询任务")
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> getRelevantTaskUser(String taskId){
        return new ResponseEntity<>(taskService.getRelevantTaskUser(taskId),HttpStatus.OK);
    }
    @GetMapping("/changeStatus")
    public ResponseEntity<Object> changeStatus(String[] changesId){
        taskService.changeStatus(changesId);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    @GetMapping("/getTaskValidRange")
    public ResponseEntity<Object> getTaskValidRange(String taskId){
        return new ResponseEntity<>(taskService.getTaskValidRange(taskId),HttpStatus.OK);
    }
    @GetMapping("/getTaskCalendarInfo")
    public ResponseEntity<Object> getTaskCalendarInfo(String date,String taskId){
        return new ResponseEntity<>(taskService.getTaskCalendarInfo(date, taskId),HttpStatus.OK);
    }
    @GetMapping("/getTastAll")
    @Log("根据任务ID查询任务")
    public ResponseEntity<Object> getTastAll(String taskId){
        return new ResponseEntity<>(taskService.getTastAllById(taskId),HttpStatus.OK);
    }
//    @GetMapping("/getTasts")
//    @Log("根据任务名字查询任务")
//    public ResponseEntity<Object> getTasts(String taskName){
//        return new ResponseEntity<>(taskService.getTastByName(taskName),HttpStatus.OK);
//    }
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/TaskService.java
@@ -1,135 +1,135 @@
/*
*  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.task.service;
import me.zhengjie.modules.project.service.dto.ProjectDto;
import me.zhengjie.modules.project.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.task.domain.Task;
import me.zhengjie.modules.task.domain.TaskAggrMongo;
import me.zhengjie.modules.task.domain.TaskMongo;
import me.zhengjie.modules.task.domain.TaskUserMongo;
import me.zhengjie.modules.task.service.dto.TaskDto;
import me.zhengjie.modules.task.service.dto.TaskMongoDto;
import me.zhengjie.modules.task.service.dto.TaskQueryCriteria;
import me.zhengjie.modules.task.service.dto.TaskUserMongoDto;
import org.springframework.data.domain.Pageable;
import java.util.Date;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @description 服务接口
* @author 赵士淞
* @date 2022-12-27
**/
public interface TaskService {
    /**
    * 查询数据分页
    * @param criteria 条件
    * @param pageable 分页参数
    * @return Map<String,Object>
    */
    Map<String,Object> queryAll(TaskQueryCriteria criteria, Pageable pageable);
    /**
    * 查询所有数据不分页
    * @param criteria 条件参数
    * @return List<TaskDto>
    */
    List<TaskMongo> queryAll(TaskQueryCriteria criteria);
    /**
     * 任务二次处理
     * @param taskDto
     * @return
     */
    TaskDto customHandleMini(TaskDto taskDto);
    /**
     * 查询子级数据不分页
     * @param criteria 条件参数
     * @return List<TaskDto>
     */
    List<TaskMongoDto> queryChildren(TaskQueryCriteria criteria);
    List<TaskMongoDto> queryChildrenTaskAnyParent(Long userId,TaskQueryCriteria criteria);
    /**
     * 根据ID查询
     * @param id ID
     * @return TaskDto
     */
    TaskDto findById(Long id);
    /**
    * 创建
    * @param resources /
    * @return TaskMongo
    */
    TaskMongo create(Long userId,TaskMongo resources);
    /**
    * 编辑
    * @param resources /
    */
    TaskMongo update(Long userId,TaskMongo resources);
    /**
    * 多选删除
    * @param ids /
    */
    Boolean deleteAll(Long userId,String[] ids);
    /**
    * 导出数据
    * @param all 待导出的数据
    * @param response /
    * @throws IOException /
    */
    void download(List<TaskDto> all, HttpServletResponse response) throws IOException;
//    /**
//     * 查询所有参与的数据不分页
//     * @param criteria 条件参数
//     * @return List<ProjectDto>
//     */
//    List<TaskDto> queryPartakeAll(TaskQueryCriteria criteria);
    List getAllTags(String tagName);
    List<Map<String, String>> getAllNames(Long projectId, String name);
    List<TaskAggrMongo> queryProjectTotal(Long projectId);
    List<ProjectDto> getAllProjects(ProjectQueryCriteria criteria);
    List<TaskMongo> allOfDaily(Long projectId);
    List<TaskUserMongoDto> getRelevantTaskUser(String taskId);
    Map<String, Date> getTaskValidRange(String taskId);
    List<Map<String, Object>> getTaskCalendarInfo(String date,String taskId);
    List<TaskMongo> getTastAllById(String taskId);
    void changeStatus(String[] ids);
/*
*  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.task.service;
import me.zhengjie.modules.project.service.dto.ProjectDto;
import me.zhengjie.modules.project.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.task.domain.Task;
import me.zhengjie.modules.task.domain.TaskAggrMongo;
import me.zhengjie.modules.task.domain.TaskMongo;
import me.zhengjie.modules.task.domain.TaskUserMongo;
import me.zhengjie.modules.task.service.dto.TaskDto;
import me.zhengjie.modules.task.service.dto.TaskMongoDto;
import me.zhengjie.modules.task.service.dto.TaskQueryCriteria;
import me.zhengjie.modules.task.service.dto.TaskUserMongoDto;
import org.springframework.data.domain.Pageable;
import java.util.Date;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://eladmin.vip
* @description 服务接口
* @author 赵士淞
* @date 2022-12-27
**/
public interface TaskService {
    /**
    * 查询数据分页
    * @param criteria 条件
    * @param pageable 分页参数
    * @return Map<String,Object>
    */
    Map<String,Object> queryAll(TaskQueryCriteria criteria, Pageable pageable);
    /**
    * 查询所有数据不分页
    * @param criteria 条件参数
    * @return List<TaskDto>
    */
    List<TaskMongoDto> queryAll(TaskQueryCriteria criteria);
    /**
     * 任务二次处理
     * @param taskDto
     * @return
     */
    TaskDto customHandleMini(TaskDto taskDto);
    /**
     * 查询子级数据不分页
     * @param criteria 条件参数
     * @return List<TaskDto>
     */
    List<TaskMongoDto> queryChildren(TaskQueryCriteria criteria);
    List<TaskMongoDto> queryChildrenTaskAnyParent(Long userId,TaskQueryCriteria criteria);
    /**
     * 根据ID查询
     * @param id ID
     * @return TaskDto
     */
    TaskDto findById(Long id);
    /**
    * 创建
    * @param resources /
    * @return TaskMongo
    */
    TaskMongo create(Long userId,TaskMongo resources);
    /**
    * 编辑
    * @param resources /
    */
    TaskMongo update(Long userId,TaskMongo resources);
    /**
    * 多选删除
    * @param ids /
    */
    Boolean deleteAll(Long userId,String[] ids);
    /**
    * 导出数据
    * @param all 待导出的数据
    * @param response /
    * @throws IOException /
    */
    void download(List<TaskMongoDto> all, HttpServletResponse response) throws IOException;
//    /**
//     * 查询所有参与的数据不分页
//     * @param criteria 条件参数
//     * @return List<ProjectDto>
//     */
//    List<TaskDto> queryPartakeAll(TaskQueryCriteria criteria);
    List getAllTags(String tagName);
    List<Map<String, String>> getAllNames(Long projectId, String name);
    List<TaskAggrMongo> queryProjectTotal(Long projectId);
    List<ProjectDto> getAllProjects(ProjectQueryCriteria criteria);
    List<TaskMongo> allOfDaily(Long projectId);
    List<TaskUserMongoDto> getRelevantTaskUser(String taskId);
    Map<String, Date> getTaskValidRange(String taskId);
    List<Map<String, Object>> getTaskCalendarInfo(String date,String taskId);
    List<TaskMongo> getTastAllById(String taskId);
    void changeStatus(String[] ids);
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/dto/TaskUserMongoDto.java
@@ -1,107 +1,109 @@
/*
*  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.task.service.dto;
import lombok.Data;
import me.zhengjie.base.BaseDTO;
import me.zhengjie.modules.task.domain.TaskDaliyMongo;
import me.zhengjie.modules.task.domain.TaskMongo;
import java.sql.Timestamp;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import io.swagger.annotations.ApiModelProperty;
/**
* @website https://eladmin.vip
* @description /
* @author 赵士淞
* @date 2022-12-28
**/
@Data
public class TaskUserMongoDto implements Serializable {
    /** ID */
    private String id;
    private Long projectId;
    private String projectName;
    /** 任务ID */
    private String taskId;
    private String taskName;
    private Long old_id;
    private String name;
    /** 任务分类 */
    private String taskClassification;
    /** 绩效类型 */
    private String performanceType;
    /** 用户ID */
    private Long userId;
    private List<Long> userIds;
    /** 用户名称 */
    private String userNickName;
    /** 任务开始时间 */
    private Date taskStartDate;
    /** 任务结束时间 */
    private Date taskEndDate;
    /** 优先度 */
    private String priority;
    private List<TaskDaliyMongo> taskDaliyList = new LinkedList<TaskDaliyMongo>();
    /** 任务工时 */
    private Double taskHours;
    /** 消耗工时 */
    private Double costHours;
    /** 绩效工时 */
    private Double performanceHours;
    private Double alreadyConsumedHours;
    /** 任务状态 */
    private String taskStatus;
    /** 备注 */
    private String remarks;
    private Double MaxTaskProgress;
    private Double newTaskProgress;
    private boolean isOk;
    private boolean isStart = false;
/*
*  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.task.service.dto;
import lombok.Data;
import me.zhengjie.base.BaseDTO;
import me.zhengjie.modules.task.domain.TaskDaliyMongo;
import me.zhengjie.modules.task.domain.TaskMongo;
import java.sql.Timestamp;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import io.swagger.annotations.ApiModelProperty;
/**
* @website https://eladmin.vip
* @description /
* @author 赵士淞
* @date 2022-12-28
**/
@Data
public class TaskUserMongoDto implements Serializable {
    /** ID */
    private String id;
    private Long projectId;
    private String projectName;
    /** 任务ID */
    private String taskId;
    private String taskName;
    private Long old_id;
    private String name;
    /** 任务分类 */
    private String taskClassification;
    /** 绩效类型 */
    private String performanceType;
    /** 用户ID */
    private Long userId;
    private List<Long> userIds;
    /** 用户名称 */
    private String userNickName;
    /** 任务开始时间 */
    private Date taskStartDate;
    /** 任务结束时间 */
    private Date taskEndDate;
    /** 优先度 */
    private String priority;
    private String uid;
    private List<TaskDaliyMongo> taskDaliyList = new LinkedList<TaskDaliyMongo>();
    /** 任务工时 */
    private Double taskHours;
    /** 消耗工时 */
    private Double costHours;
    /** 绩效工时 */
    private Double performanceHours;
    private Double alreadyConsumedHours;
    /** 任务状态 */
    private String taskStatus;
    /** 备注 */
    private String remarks;
    private Double MaxTaskProgress;
    private Double newTaskProgress;
    private boolean isOk;
    private boolean isStart = false;
}
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskServiceImpl.java
@@ -1,1121 +1,1050 @@
/*
 *  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.task.service.impl;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;
import me.zhengjie.modules.task.service.dto.TaskUserMongoDto;
import me.zhengjie.modules.treatment.repository.UserLevelWageRepository;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.domain.Project;
import me.zhengjie.modules.project.repository.ProjectRepository;
import me.zhengjie.modules.project.service.ProjectService;
import me.zhengjie.modules.project.service.dto.ProjectDto;
import me.zhengjie.modules.project.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.task.domain.Task;
import me.zhengjie.modules.task.domain.TaskAggrMongo;
import me.zhengjie.modules.task.domain.TaskDaliy;
import me.zhengjie.modules.task.domain.TaskDaliyMongo;
import me.zhengjie.modules.task.domain.TaskMongo;
import me.zhengjie.modules.task.domain.TaskUser;
import me.zhengjie.modules.task.domain.TaskUserMongo;
import me.zhengjie.modules.task.repository.TaskDaliyRepository;
import me.zhengjie.modules.task.repository.TaskRepository;
import me.zhengjie.modules.task.repository.TaskUserRepository;
import me.zhengjie.modules.task.service.TaskService;
import me.zhengjie.modules.task.service.dto.TaskDto;
import me.zhengjie.modules.task.service.dto.TaskMongoDto;
import me.zhengjie.modules.task.service.dto.TaskQueryCriteria;
import me.zhengjie.modules.task.service.mapstruct.TaskMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.ValidationUtil;
/**
 * @author 赵士淞
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-12-27
 **/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "task")
public class TaskServiceImpl implements TaskService {
    private final TaskRepository taskRepository;
    private final TaskMapper taskMapper;
    private final ProjectRepository projectRepository;
    private final DictDetailRepository dictDetailRepository;
    private final TaskUserRepository taskUserRepository;
    private final TaskDaliyRepository taskDaliyRepository;
    private final RoleService roleService;
    private final UserLevelWageRepository userLevelWageRepository;
    @Autowired
    private ProjectService projectService;
    private final MongoTemplate mongoTemplate;
    private final Object lock = new Object();
    @Override
    public List getAllTags(String tagName) {
        Criteria criteria = new Criteria();
        if (tagName != null && tagName.trim().length() > 0) {
            criteria = criteria.and("tagList").regex("^.*" + tagName + ".*$");
        }
        Aggregation customerAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.project("tagList"),
                Aggregation.unwind("tagList"),
                Aggregation.group("tagList")
        );
        AggregationResults<Map> taskUserMongoList = mongoTemplate.aggregate(customerAgg, TaskMongo.class, Map.class);
//        System.out.println(taskUserMongoList.getMappedResults().stream().flatMap(map -> map.values().stream()).collect(Collectors.toList()));
        return (List) taskUserMongoList.getMappedResults().stream().flatMap(map -> map.values().stream()).collect(Collectors.toList());
    }
    @Override
    public List<ProjectDto> getAllProjects(ProjectQueryCriteria criteria) {
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
            ArrayList<Long> projectList = new ArrayList<>();
            Query query = Query.query(Criteria.where("containUserList").is(SecurityUtils.getCurrentUserId()));
            List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
            for (TaskMongo taskMongo : taskMongoList) {
                projectList.add(taskMongo.getProjectId());
            }
            // 根据用户ID查询负责的项目ID
            List<Long> projectIdList = projectRepository.findIdByLiableUserId(SecurityUtils.getCurrentUserId());
            Set<Long> projectIds = Stream.of(projectList, projectIdList).flatMap(Collection::stream).collect(Collectors.toSet());
            criteria.setApproveStatusIn(Arrays.asList(Constant.APPROVE_STATUS_MASTER_ACKNOWLEDGED, Constant.APPROVE_STATUS_ACKNOWLEDGED));
            criteria.setProjectStatusNotEqual(Constant.PROJECT_STATUS_COMPLETED);
            criteria.setIdInList(new ArrayList<Long>(projectIds));
        } else {
            // 根据用户ID查询负责的项目ID
            List<Project> projectIdList = projectRepository.findAll();
            List<Long> projectIds = new ArrayList<>();
            for (Project project : projectIdList) {
                projectIds.add(project.getId());
            }
            criteria.setApproveStatusIn(Arrays.asList(Constant.APPROVE_STATUS_MASTER_ACKNOWLEDGED, Constant.APPROVE_STATUS_ACKNOWLEDGED));
            criteria.setProjectStatusNotEqual(Constant.PROJECT_STATUS_COMPLETED);
            criteria.setIdInList(projectIds);
        }
        return projectService.queryAll2(criteria);
    }
    @Override
    //@Cacheable(key = "'projectId:' + #p0")
    public List<TaskMongo> allOfDaily(Long projectId) {
        List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(
                Query.query(new Criteria("userId").is(SecurityUtils.getCurrentUserId())
                        .and("taskStatus").in(Constant.TASK_STATUS_NOT_STARTED, Constant.TASK_STATUS_IN_HAND, Constant.TASK_STATUS_TEST, Constant.TASK_STATUS_UNRECOGNIZED)
                ), TaskUserMongo.class);
        return taskUserMongoList.stream().filter(taskUserMongo -> taskUserMongo.getTask().getProjectId().equals(projectId))
                .map(taskUserMongo -> taskUserMongo.getTask()).distinct().collect(Collectors.toList());
    }
    @Override
    public List<TaskUserMongoDto> getRelevantTaskUser(String taskId) {
        Criteria criteriaMongo = new Criteria();
        //查找出这个任务中所有的分配任务
        criteriaMongo.and("task.id").is(taskId);
        criteriaMongo.and("taskStatus").ne(Constant.TASK_STATUS_COMPLETED);
        List<TaskUserMongo> taskUserMongos = mongoTemplate.find(Query.query(criteriaMongo), TaskUserMongo.class);
        //将所有有负责人Id的人筛出来
        taskUserMongos = taskUserMongos.stream().filter(item -> item.getUserId() != null).collect(Collectors.toList());
        taskUserMongos.removeIf(taskUserMongo -> !taskUserMongo.getUserId().equals(SecurityUtils.getCurrentUserId()));
        List<TaskUserMongoDto> taskUserMongoDtoList = new ArrayList<>();
        taskUserMongos.forEach(item -> {
//            //如果有指定的任务负责人就获取这个任务负责人的绩效绩点
//            Double coefficientByUserId = userLevelWageRepository.findPerformanceCoefficientByUserId(SecurityUtils.getCurrentUserId()).get(0);
            TaskUserMongoDto dto = new TaskUserMongoDto();
//            if (item.getPerformanceType() == null) {
//                TaskMongo byId = mongoTemplate.findById(item.getTask().getId(), TaskMongo.class);
//                item.setPerformanceType(byId.getPerformanceType());
//                mongoTemplate.save(item);
//                getRelevantTaskUser(taskId);
//            }
//            if (item.getPerformanceType().equals("1")) {
//                //绩效任务
//                DecimalFormat decimalFormat = new DecimalFormat("#0");
//                String format = decimalFormat.format(item.getTaskHours() / coefficientByUserId);
//                item.setPerformanceHours(Double.valueOf(format));
//            } else {
                item.setPerformanceHours(item.getTaskHours());
//            }
            dto.setId(item.getId());
            dto.setName(item.getName());
            dto.setProjectId(item.getTask().getProjectId());
            dto.setRemarks(item.getRemarks());
            dto.setTaskHours(item.getTaskHours());
            dto.setTaskStatus(item.getTaskStatus());
            dto.setTaskId(item.getTask().getId());
            dto.setUserId(SecurityUtils.getCurrentUserId());
            dto.setPerformanceHours(item.getPerformanceHours());
            dto.setTaskStartDate(item.getTaskStartDate());
            dto.setTaskEndDate(item.getTaskEndDate());
            //List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(Query.query(new Criteria("userId").is(SecurityUtils.getCurrentUserId()).and("taskUserMongo.id").is(item.getId())), TaskDaliyMongo.class);
            AtomicReference<Double> consumptionHours = new AtomicReference<>(0D);
            //获取已消耗的工时
            List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(new Query(new Criteria("taskUserMongo.id").is(item.getId())), TaskDaliyMongo.class);
            daliyMongoList.forEach(daliy -> consumptionHours.updateAndGet(v -> v + daliy.getConsumedHours()));
            if (daliyMongoList.size() == 0) {
                //如果没有日志,统一赋值为0
                dto.setMaxTaskProgress(0D);
                dto.setAlreadyConsumedHours(consumptionHours.get());
                taskUserMongoDtoList.add(dto);
            } else {
                //如果有日志
                daliyMongoList.sort(((o1, o2) -> (int) (o2.getTaskProgress() - o1.getTaskProgress())));
                dto.setMaxTaskProgress(daliyMongoList.get(0).getTaskProgress());
                dto.setAlreadyConsumedHours(consumptionHours.get());
                taskUserMongoDtoList.add(dto);
            }
        });
        return taskUserMongoDtoList;
    }
    @Override
    public Map<String,Date> getTaskValidRange(String taskId) {
        TaskMongo byId = mongoTemplate.findById(taskId, TaskMongo.class);
        Map<String,Date> hashMap = new HashMap<>();
        assert byId != null;
        if(byId.getPlanStartTime() != null && byId.getPlanEndTime() != null){
            hashMap.put("start",byId.getPlanStartTime());
            hashMap.put("end",byId.getPlanEndTime());
        } else {
            hashMap.put("start",null);
            hashMap.put("end",null);
        }
        return hashMap;
    }
    /**
     * 查询任务列表
     * @param taskId
     * @return
     */
    @Override
    public List<TaskMongo> getTastAllById(String taskId) {
        Query query= Query.query(Criteria.where("id").in(taskId));
        List<TaskMongo> list= this.mongoTemplate.find(query, TaskMongo.class);
        return list;
    }
    @Override
    public void changeStatus(String[] ids) {
        List<TaskMongo> taskMongoList = mongoTemplate.find(Query.query(new Criteria("id").in(ids).and("taskStatus").ne(Constant.TASK_STATUS_COMPLETED)), TaskMongo.class);
        taskMongoList.stream().forEach(taskMongo -> {
            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(new Criteria("task").is(taskMongo).and("taskStatus").ne(Constant.TASK_STATUS_COMPLETED)), TaskUserMongo.class);
            taskUserMongoList.stream().forEach(taskUserMongo -> {
                taskUserMongo.setTaskStatus(Constant.TASK_STATUS_COMPLETED);
                mongoTemplate.save(taskUserMongo);
            });
            taskMongo.setTaskStatus(Constant.TASK_STATUS_COMPLETED);
            mongoTemplate.save(taskMongo);
        });
    }
    @Override
    public List<Map<String, Object>> getTaskCalendarInfo(String date,String taskId) {
        List<String> colorList = new ArrayList<>();
        Collections.addAll(colorList,"#409EFF","#67C23A","#F56C6C","#909399","#E6A23C");
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(new Criteria("task._id").is(taskId)), TaskUserMongo.class);
        for (TaskUserMongo taskUserMongo : taskUserMongoList) {
            HashMap<String,Object> map = new HashMap<>();
            map.put("start",taskUserMongo.getTaskStartDate());
            map.put("end",taskUserMongo.getTaskEndDate());
            map.put("title",taskUserMongo.getName());
            map.put("type",1);
            int index = new Random().nextInt(colorList.size());
            map.put("color",colorList.get(index));
            mapList.add(map);
        }
        return mapList;
    }
    @Override
    public List<Map<String, String>> getAllNames(Long projectId, String name) {
        if (name == null || name.trim().length() == 0) {
            return Collections.emptyList();
        }
        Criteria criteria = new Criteria();
        if (name != null && name.trim().length() > 0) {
            criteria = criteria.and("name").regex("^.*" + name + ".*$");
        }
        criteria.and("projectId").is(projectId);
        final List<Map<String, String>> result = new ArrayList<Map<String, String>>();
        List<TaskMongo> taskMongoList = mongoTemplate.find(new Query(criteria).with(Pageable.ofSize(10)), TaskMongo.class);
        taskMongoList.forEach(item -> {
            Map<String, String> itemMap = new LinkedHashMap<String, String>();
            itemMap.put("id", item.getName());
            itemMap.put("value", item.getName());
            itemMap.put("label", item.getName());
            result.add(itemMap);
        });
        return result;
    }
    @Override
    public List<TaskAggrMongo> queryProjectTotal(Long projectId) {
        Criteria criteriaMongo = new Criteria();
        criteriaMongo = criteriaMongo.and("projectId").is(projectId);
        Aggregation customerAgg = Aggregation.newAggregation(
                Aggregation.match(criteriaMongo),
                Aggregation.project("taskStatus", "planHours"),
                Aggregation.group("taskStatus").count().as("count").sum("planHours").as("planHours")
        );
        AggregationResults<TaskAggrMongo> taskUserMongoList = mongoTemplate.aggregate(customerAgg, TaskMongo.class, TaskAggrMongo.class);
        return taskUserMongoList.getMappedResults();
    }
    @Override
    public Map<String, Object> queryAll(TaskQueryCriteria criteria, Pageable pageable) {
        Criteria criteriaMongo = new Criteria();
        if (criteria.getProjectId() != null) {
            criteriaMongo = criteriaMongo.and("projectId").is(criteria.getProjectId());
        }
        if (criteria.getName() == null) {
            criteriaMongo = criteriaMongo.and("parent").exists(false);
        } else {
            criteriaMongo = criteriaMongo.and("name").regex(Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        if (criteria.getTaskStatuses() != null && criteria.getTaskStatuses().size() > 0) {
            criteriaMongo = criteriaMongo.and("taskStatus").in(criteria.getTaskStatuses());
        }
        if (criteria.getUserIds() != null && criteria.getUserIds().size() > 0) {
            criteriaMongo = criteriaMongo.and("userIdList").in(criteria.getUserIds());
        }
        if (criteria.getTagList() != null && criteria.getTagList().size() > 0) {
            criteriaMongo = criteriaMongo.and("tagList").in(criteria.getTagList());
        }
//        if(criteria.getUserIds() != null && criteria.getUserIds().size() > 0){
//            criteriaMongo = criteriaMongo.and("containUserList").in(criteria.getUserIds());
//        }
        if(criteria.getPerformanceType() != null) {
            criteriaMongo = criteriaMongo.and("performanceType").is(criteria.getPerformanceType());
        }
        Query query = new Query(criteriaMongo);
        Long totalCount = mongoTemplate.count(query, TaskMongo.class);
        if (totalCount == 0) {
            return PageUtil.toPage(Collections.emptyList(), 0);
        }
        List<TaskMongo> taskMongoList = mongoTemplate.find(query.with(pageable), TaskMongo.class);
        List<TaskMongoDto> taskMongoDtoList;
        if (criteria.getName() == null) {
            taskMongoDtoList = createTree(null, taskMongoList);
        } else {
            taskMongoDtoList = createTreeWithoutChildren(null, taskMongoList);
        }
        return PageUtil.toPage(taskMongoDtoList, totalCount);
    }
    private List<TaskMongoDto> createTreeWithoutChildren(String parentPath, List<TaskMongo> taskMongoList) {
        List<TaskMongoDto> result = new ArrayList<TaskMongoDto>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
            taskMongoDto.setOld_id(taskMongo.getOld_id());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            // 根据项目ID查询项目信息
            Project project = projectRepository.findById(taskMongo.getProjectId()).orElseGet(Project::new);
            // 项目名称
            taskMongoDto.setProjectName(project.getName());
//            TaskMongoDto parentDto = new TaskMongoDto();
//            parentDto.setId(taskMongo.getParent() == null ? null : taskMongo.getParent().getId());
//            taskMongoDto.setParent(parentDto);
            taskMongoDto.setPerformanceType(taskMongo.getPerformanceType());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
            taskMongoDto.setPlanHours(taskMongo.getPlanHours());
            taskMongoDto.setTaskStatus(taskMongo.getTaskStatus());
            taskMongoDto.setDescription(taskMongo.getDescription());
            taskMongoDto.setUserIdList(taskMongo.getUserIdList());
            taskMongoDto.setContainUserList(taskMongo.getContainUserList());
            taskMongoDto.setTagList(taskMongo.getTagList());
            taskMongoDto.setVersion(taskMongo.getVersion());
            if (taskMongo.getPlanWorkload() != null) {
                taskMongoDto.setPlanWorkload(taskMongo.getPlanWorkload());
            }
            if (taskMongo.getPlanWorkloadUnit() != null) {
                taskMongoDto.setPlanWorkloadUnit(taskMongo.getPlanWorkloadUnit());
            }
            taskMongoDto.setConsumedHours(0.0D);
            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(Criteria.where("task").is(taskMongo)), TaskUserMongo.class);
            List<TaskDaliyMongo> taskDaliyMongoList = mongoTemplate.find(Query.query(Criteria.where("taskUserMongo").in(taskUserMongoList)), TaskDaliyMongo.class);
            double consumedHours = taskDaliyMongoList.stream()
                    .map(taskDaliyMongo -> BigDecimal.valueOf(taskDaliyMongo.getConsumedHours()))
                    .reduce(BigDecimal::add).orElse(BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue();
            taskMongoDto.setConsumedHours(taskMongoDto.getConsumedHours() + consumedHours);
            Query query = new Query(Criteria.where("parent").is(taskMongo));
            List<TaskMongo> children = mongoTemplate.find(query, TaskMongo.class);
            if (children == null || children.size() == 0) {
                taskMongoDto.setSumPlanHours(taskMongo.getPlanHours());
            } else {
                List<TaskMongoDto> childrenDto = createTree(null, children);
                Double sumHours = BigDecimal.valueOf(
                        childrenDto.stream().collect(
                                Collectors.summingDouble(TaskMongoDto::getSumPlanHours))).round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue();
                taskMongoDto.setSumPlanHours(sumHours);
            }
            result.add(taskMongoDto);
        }
        return result;
    }
    private List<TaskMongoDto> createTree(String parentPath, List<TaskMongo> taskMongoList) {
        List<TaskMongoDto> result = new ArrayList<TaskMongoDto>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
            taskMongoDto.setOld_id(taskMongo.getOld_id());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            // 根据项目ID查询项目信息
            Project project = projectRepository.findById(taskMongo.getProjectId()).orElseGet(Project::new);
            // 项目名称
            taskMongoDto.setProjectName(project.getName());
            TaskMongoDto parentDto = new TaskMongoDto();
//            parentDto.setId(taskMongo.getParent() == null ? null : taskMongo.getParent().getId());
            taskMongoDto.setParent(parentDto);
            taskMongoDto.setPerformanceType(taskMongo.getPerformanceType());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
            taskMongoDto.setPlanHours(taskMongo.getPlanHours());
            taskMongoDto.setTaskStatus(taskMongo.getTaskStatus());
            taskMongoDto.setDescription(taskMongo.getDescription());
            taskMongoDto.setUserIdList(taskMongo.getUserIdList());
            taskMongoDto.setContainUserList(taskMongo.getContainUserList());
            taskMongoDto.setTagList(taskMongo.getTagList());
            taskMongoDto.setVersion(taskMongo.getVersion());
            if (taskMongo.getPlanWorkload() != null) {
                taskMongoDto.setPlanWorkload(taskMongo.getPlanWorkload());
            }
            if (taskMongo.getPlanWorkloadUnit() != null) {
                taskMongoDto.setPlanWorkloadUnit(taskMongo.getPlanWorkloadUnit());
            }
            taskMongoDto.setConsumedHours(0.0D);
//            taskMongoDto.setPerformanceHours(0.0D);
            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(Criteria.where("task").is(taskMongo)), TaskUserMongo.class);
            List<TaskDaliyMongo> taskDaliyMongoList = mongoTemplate.find(Query.query(Criteria.where("taskUserMongo").in(taskUserMongoList)), TaskDaliyMongo.class);
            double consumedHours = taskDaliyMongoList.stream()
                    .map(taskDaliyMongo -> BigDecimal.valueOf(taskDaliyMongo.getConsumedHours()))
                    .reduce(BigDecimal::add).orElse(BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue();
            taskMongoDto.setConsumedHours(taskMongoDto.getConsumedHours() + consumedHours);
//            for (TaskUserMongo taskUserMongo : taskUserMongoList) {
//                if (taskUserMongo.getTaskDaliyList().size() > 0) {
//                    Double total = taskUserMongo.getTaskDaliyList().stream().collect(Collectors.summingDouble(TaskDaliyMongo::getConsumedHours));
//                    taskMongoDto.setConsumedHours(taskMongoDto.getConsumedHours() + total);
//                    TaskDaliyMongo taskDaliyMongo = taskUserMongo.getTaskDaliyList().get(0);
//                    taskMongoDto.setPerformanceHours(taskMongoDto.getPerformanceHours() + (taskUserMongo.getTaskHours() * taskDaliyMongo.getTaskProgress()/100));
//                }
//            }
            Query query = new Query(Criteria.where("parent").is(taskMongo));
            List<TaskMongo> children = mongoTemplate.find(query, TaskMongo.class);
            if (children == null || children.size() == 0) {
                taskMongoDto.setSumPlanHours(taskMongo.getPlanHours());
            } else {
                List<TaskMongoDto> childrenDto = createTree(null, children);
                taskMongoDto.setChildren(childrenDto);
                Double sumHours = BigDecimal.valueOf(
                        childrenDto.stream().collect(
                                Collectors.summingDouble(TaskMongoDto::getSumPlanHours))).round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue();
                taskMongoDto.setSumPlanHours(sumHours);
//                Double consumedHours = BigDecimal.valueOf(
//                        childrenDto.stream().collect(
//                                Collectors.summingDouble(TaskMongoDto::getConsumedHours))).round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue();
//                taskMongoDto.setConsumedHours(consumedHours + taskMongoDto.getConsumedHours());
//
//                Double performanceHours = BigDecimal.valueOf(
//                        childrenDto.stream().collect(
//                                Collectors.summingDouble(TaskMongoDto::getPerformanceHours))).round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue();
//                taskMongoDto.setPerformanceHours(performanceHours + taskMongoDto.getPerformanceHours());
            }
            result.add(taskMongoDto);
        }
        return result;
    }
    private TaskDto customHandle(TaskDto taskDto) {
        // 根据项目ID查询项目信息
        Project project = projectRepository.findById(taskDto.getProjectId()).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", taskDto.getProjectId());
        // 项目名称
        taskDto.setProjectName(project.getName());
        if (project.getLiableUserId() != null && !"".equals(project.getLiableUserId())) {
            // 负责人ID列表
            List<Long> projectLiableUserIdList = new ArrayList<>();
            // 项目责任人ID
            String projectLiableUserId = project.getLiableUserId().replace("-", "");
            String[] projectLiableUserIds = projectLiableUserId.split(",");
            // 循环负责人ID列表
            for (String liableUserId : projectLiableUserIds) {
                // 负责人ID列表
                projectLiableUserIdList.add(Long.valueOf(liableUserId));
            }
            // 项目责任人ID
            taskDto.setProjectLiableUserIdList(projectLiableUserIdList);
        }
        // 判断父级任务ID是否为空
        if (taskDto.getPid() != null) {
            // 根据父级任务ID查询任务信息
            Task task = taskRepository.findById(taskDto.getPid()).orElseGet(Task::new);
            ValidationUtil.isNull(task.getId(), "Task", "id", taskDto.getPid());
            // 父级任务名称
            taskDto.setPidName(task.getName());
        }
        // 根据父级任务ID查询
        List<Task> childrenTaskList = taskRepository.findByPid(taskDto.getId());
        // 判断子级数量
        if (childrenTaskList.size() > 0) {
            // 是否有子级
            taskDto.setHasChildren(true);
        } else {
            // 是否有子级
            taskDto.setHasChildren(false);
        }
        // 据任务ID查询任务工时总和
        Double sumTaskHours = taskUserRepository.sumTaskHoursByTaskId(taskDto.getId());
        // 已分配工时
        taskDto.setDivideHours(sumTaskHours);
        // 据任务ID查询任务工作量总和
        Double sumTaskWorkload = taskUserRepository.sumTaskWorkloadByTaskId(taskDto.getId());
        // 已分配工作量
        taskDto.setDivideWorkload(sumTaskWorkload);
        // 已完成工时
        Double completedHours = 0D;
        if (Constant.PERFORMANCE_TYPE_ON.equals(taskDto.getPerformanceType())) {
            // 根据项目ID、任务ID查询各用户填报的最大任务进度日报信息
            //List<Map> taskDaliyMapList = taskDaliyRepository.findMaxTaskProgressByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
            // 循环最大任务进度日报
//            for (int i = 0; i < taskDaliyMapList.size(); i++) {
//                // 最大任务进度日报信息
//                Map taskDaliyMap = taskDaliyMapList.get(i);
//                // 已完成工时
//                completedHours += new BigDecimal(taskDaliyMap.get("task_hours").toString()).multiply(new BigDecimal(taskDaliyMap.get("task_progress").toString())).doubleValue() / 100;
//            }
        } else {
            List<TaskDaliy> taskDaliyList = taskDaliyRepository.findByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
            for (TaskDaliy taskDaliy : taskDaliyList) {
                completedHours += taskDaliy.getConsumedHours();
            }
        }
        // 已完成工时
        taskDto.setCompletedHours(completedHours);
        // 根据项目ID、任务ID查询总消耗工作量
        //Double completedWorkload = taskDaliyRepository.findSumConsumedWorkloadByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
        // 已完成工作量
        //taskDto.setCompletedWorkload(completedWorkload);
        // 根据任务ID查询所属用户
        List<Long> userIdList = taskUserRepository.findUserIdByTaskId(taskDto.getId());
        // 已分配用户
        taskDto.setDivideUserIds(userIdList);
        // 返回
        return taskDto;
    }
    @Override
    public TaskDto customHandleMini(TaskDto taskDto) {
        // 据任务ID查询任务工时总和
        Double sumTaskHours = taskUserRepository.sumTaskHoursByTaskId(taskDto.getId());
        // 已分配工时
        taskDto.setDivideHours(sumTaskHours);
        // 已完成工时
        Double completedHours = 0D;
        if (Constant.PERFORMANCE_TYPE_ON.equals(taskDto.getPerformanceType())) {
            // 根据项目ID、任务ID查询各用户填报的最大任务进度日报信息
            //List<Map> taskDaliyMapList = taskDaliyRepository.findMaxTaskProgressByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
            // 循环最大任务进度日报
//            for (int i = 0; i < taskDaliyMapList.size(); i++) {
//                // 最大任务进度日报信息
//                Map taskDaliyMap = taskDaliyMapList.get(i);
//                // 已完成工时
//                completedHours += new BigDecimal(taskDaliyMap.get("task_hours").toString()).multiply(new BigDecimal(taskDaliyMap.get("task_progress").toString())).doubleValue() / 100;
//            }
        } else {
            List<TaskDaliy> taskDaliyList = taskDaliyRepository.findByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
            for (TaskDaliy taskDaliy : taskDaliyList) {
                completedHours += taskDaliy.getConsumedHours();
            }
        }
        // 已完成工时
        taskDto.setCompletedHours(completedHours);
        // 返回
        return taskDto;
    }
    @Override
    public List<TaskMongo> queryAll(TaskQueryCriteria criteria) {
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        // 判断角色等级
        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
//            // 根据用户ID查询参与的项目ID
//            List<Long> taskUserProjectIdList = taskUserRepository.findProjectIdByUserId(SecurityUtils.getCurrentUserId());
            // 根据用户ID查询负责的项目ID
            List<Long> projectIdList = projectRepository.findIdByLiableUserId(SecurityUtils.getCurrentUserId());
            // 检索条件
            List<Long> totalProjectIdList = Stream.of(projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
            if (totalProjectIdList.size() == 0) {
                return Collections.emptyList();
            }
            criteria.setProjectIdInList(totalProjectIdList);
        }
        Criteria criteriaMongo = new Criteria();
        if (criteria.getProjectId() != null) {
            criteriaMongo = criteriaMongo.and("projectId").is(criteria.getProjectId());
        } else if (criteria.getProjectIdInList() != null) {
            criteriaMongo = criteriaMongo.and("projectId").in(criteria.getProjectIdInList().toArray());
        }
        if (criteria.getName() != null) {
//            criteriaMongo = criteriaMongo.and("parent").exists(false);
//        } else {
            criteriaMongo = criteriaMongo.and("name").regex(Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        Query query = new Query(criteriaMongo);
        Long totalCount = mongoTemplate.count(query, TaskMongo.class);
        if (totalCount == 0) {
            return Collections.emptyList();
        }
        List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
        return taskMongoList;
    }
    public List<TaskMongoDto> findByCompanyId(Long companyId) {
        List<TaskMongo> taskMongoList;
        if (companyId != null) {
            Query query = new Query(Criteria.where("projectId").is(companyId).and("parent").exists(false));
            taskMongoList = mongoTemplate.find(query.limit(10), TaskMongo.class);
        } else {
            Query query = new Query(Criteria.where("parent").exists(false));
            taskMongoList = mongoTemplate.find(query.limit(10), TaskMongo.class);
        }
        return change2Dto(taskMongoList);
    }
    private List<TaskMongoDto> change2Dto(List<TaskMongo> taskMongoList) {
        List<TaskMongoDto> result = new ArrayList<TaskMongoDto>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
//            taskMongoDto.setPid(taskMongo.getParent() == null ? null : taskMongo.getParent().getId());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            taskMongoDto.setPerformanceType(taskMongo.getPerformanceType());
            taskMongoDto.setPlanHours(taskMongo.getPlanHours());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
//            taskMongoDto.setPriority(taskMongo.getPriority());
//            taskMongoDto.setTaskClassification(taskMongo.getTaskClassification());
            taskMongoDto.setTaskStatus(taskMongo.getTaskStatus());
//            taskMongoDto.setRemarks(taskMongo.getRemarks());
            Query query = new Query(Criteria.where("parent").is(taskMongo));
            List<TaskMongo> children = mongoTemplate.find(query, TaskMongo.class);
//            taskMongoDto.setChildren(change2Dto(children));
            result.add(taskMongoDto);
        }
        return result;
    }
    @Transactional
    public void moveData() {
        TaskQueryCriteria criteria = new TaskQueryCriteria();
        criteria.setPidIsNull(true);
        List<Task> taskList = taskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        changeToMongo(null, taskList);
        // List<TaskMongo> taskMongoList =
//        for (TaskMongo taskMongo : taskMongoList) {
//            mongoTemplate.save(taskMongo);
//        }
    }
    public void changeToMongo(TaskMongo parent, List<Task> taskList) {
        DictDetailQueryCriteria criteria = new DictDetailQueryCriteria();
        criteria.setDictName("task_classification");
        List<DictDetail> dictDetailList = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        Map<String, String> dictDetailMap = dictDetailList.stream().collect(Collectors.toMap(DictDetail::getValue, DictDetail::getLabel));
        for (Task task : taskList) {
            TaskMongo taskMongo = new TaskMongo();
            taskMongo.setProjectId(task.getProjectId());
            taskMongo.setName(task.getName());
//            taskMongo.setParent(parent);
            taskMongo.setPlanHours(task.getPlanHours());
            taskMongo.setPlanStartTime(task.getPlanStartTime());
            taskMongo.setPlanEndTime(task.getPlanEndTime());
            String classification = task.getTaskClassification();
            taskMongo.setTagList(Collections.singletonList(dictDetailMap.get(classification)));
            taskMongo.setPerformanceType(task.getPerformanceType());
            taskMongo.setTaskStatus(task.getTaskStatus());
            String[] userIds = projectRepository.findById(task.getProjectId()).get().getLiableUserId().replaceAll("-", "").split(",");
            taskMongo.setUserIdList(Stream.of(userIds).map(userId -> Long.valueOf(userId)).collect(Collectors.toList()));
            taskMongo = mongoTemplate.save(taskMongo);
            List<Task> taskListSub = getSubList(task);
            changeToMongo(taskMongo, taskListSub);
            List<TaskUser> taskUserList = taskUserRepository.findByTaskId(task.getId());
            for (TaskUser taskUser : taskUserList) {
                if (taskUser.getEnable()) {
                    TaskUserMongo taskUserMongo = new TaskUserMongo();
                    taskUserMongo.setTask(taskMongo);
                    taskUserMongo.setUserId(taskUser.getUserId());
                    taskUserMongo.setName(task.getName());
                    //taskUserMongo.setTaskClassification(task.getTaskClassification());
                    taskUserMongo.setPerformanceType(task.getPerformanceType());
                    taskUserMongo.setPriority(task.getPriority());
                    taskUserMongo.setPerformanceHours(null); // TODO
                    taskUserMongo.setTaskHours(taskUser.getTaskHours());
                    taskUserMongo.setTaskStartDate(taskUser.getTaskStartDate());
                    taskUserMongo.setTaskEndDate(taskUser.getTaskEndDate());
                    taskUserMongo.setTaskStatus(taskUser.getTaskStatus());
                    taskUserMongo.setRemarks(taskUser.getRemarks());
                    //List<TaskDaliy> taskDaliyList = taskDaliyRepository.findByProjectIdAndTaskIdAndUserIdOrderByFillDateDesc(taskMongo.getProjectId(), taskUser.getTaskId(), taskUser.getUserId());
                    List<TaskDaliyMongo> taskDaliyMongoList = new ArrayList<TaskDaliyMongo>();
//                    for (TaskDaliy taskDaliy : taskDaliyList) {
//                        TaskDaliyMongo taskDaliyMongo = new TaskDaliyMongo();
//                        taskDaliyMongo.setFillDate(taskDaliy.getFillDate());
//                        taskDaliyMongo.setConsumedHours(taskDaliy.getConsumedHours());
//                        taskDaliyMongo.setTaskProgress(taskDaliy.getTaskProgress());
//                        taskDaliyMongo.setSettlementStatus(taskDaliy.getSettlementStatus());
//                        taskDaliyMongo.setRemarks(taskDaliy.getRemarks());
//                        taskDaliyMongoList.add(taskDaliyMongo);
//                    }
                    //taskUserMongo.setTaskDaliyList(taskDaliyMongoList);
                    mongoTemplate.save(taskUserMongo);
                }
            }
        }
//        return resultList;
    }
//    public void changeRoute(TaskMongo taskMongo) {
//        TaskMongo taskMongoDB = mongoTemplate.findById(new ObjectId(taskMongo.getId()), TaskMongo.class);
//        List<TaskMongo> newChildren = taskMongo.getChildren();
//        List<TaskMongo> oldChildren = taskMongoDB.getChildren();
//        List<TaskMongo> insertList = newChildren.stream()
//                .filter(item -> !oldChildren.contains(item)).collect(Collectors.toList());
//        List<TaskMongo> deleteList = oldChildren.stream()
//                .filter(item -> !newChildren.contains(item)).collect(Collectors.toList());
//
//
//        //        Pattern pattern = Pattern.compile("^.*" + taskMongoDB.getPath() + "/$", Pattern.CASE_INSENSITIVE);
////        Query query = new Query(Criteria.where("path").regex(pattern));
////        List<TaskMongo> children = mongoTemplate.find(query, TaskMongo.class);
////        for (TaskMongo child : children) {
////            if (child.getPath().equals("/" + child.getName())) {
////                child.setPath(taskMongo.getPath() + child.getPath());
////            } else {
////                child.setPath(child.getPath().replace(taskMongoDB.getPath(), taskMongo.getPath()));
////            }
////            mongoTemplate.save(child);
////        }
//        mongoTemplate.save(taskMongo);
//    }
    public List<Task> getSubList(Task task) {
        return taskRepository.findByPid(task.getId());
    }
    @Override
    public List<TaskMongoDto> queryChildren(TaskQueryCriteria criteria) {
        Long userId = SecurityUtils.getCurrentUserId();
        Criteria criteriaMongo = new Criteria();
        criteriaMongo = criteriaMongo.and("containUserList").is(userId);
        if (criteria.getProjectId() != null) {
            criteriaMongo = criteriaMongo.and("projectId").is(criteria.getProjectId());
        }
//        if (criteria.getPid() == null) {
//            criteriaMongo = criteriaMongo.and("parent").exists(false);
//        } else {
//            TaskMongo parent = mongoTemplate.findById(new ObjectId(criteria.getPid()), TaskMongo.class);
//            criteriaMongo = criteriaMongo.and("parent").is(parent);
//        }
        if (criteria.getName() != null) {
            criteriaMongo = criteriaMongo.and("name").regex(Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        Query query = new Query(criteriaMongo);
        Long totalCount = mongoTemplate.count(query, TaskMongo.class);
        if (totalCount == 0) {
            return Collections.emptyList();
        }
        List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
        List<TaskMongoDto> taskMongoDtoList = new ArrayList<TaskMongoDto>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
            Query childrenQuery = new Query(Criteria.where("parent").is(taskMongo));
            long children = mongoTemplate.count(childrenQuery, TaskMongo.class);
            taskMongoDto.setLeaf(children == 0);
            taskMongoDtoList.add(taskMongoDto);
        }
        return taskMongoDtoList;
    }
    // @Cacheable(cacheNames = "ChildrenTask", key = "'userId:' +#p0  + 'projectId:' + #p1.projectId")
    public List<TaskMongoDto> queryChildrenTaskAnyParent(Long userId,TaskQueryCriteria criteria) {
        List<TaskMongo> taskMongosName = new ArrayList<>();
        boolean flag = false;
        if (criteria.getName() != null) {
            Criteria criteriaTask = new Criteria();
            Pattern pattern = Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE);
            criteriaTask.and("name").is(pattern);
            criteriaTask.and("pid").is(null);
            taskMongosName = mongoTemplate.find(Query.query(criteriaTask), TaskMongo.class);
            flag = true;
        }
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
            //看看当前这个用户是不是这个项目的项目负责人,如果是项目负责人的话显示全部的任务
            List<Long> idByLiableUserId = projectRepository.findIdByLiableUserId(userId);
            for (Long aLong : idByLiableUserId) {
                if (criteria.getProjectId().equals(aLong)) {
                    Criteria criteriaAll = new Criteria();
                    criteriaAll = criteriaAll.and("projectId").is(criteria.getProjectId()).and("pid").is(null);
                    Query query = new Query(criteriaAll);
                    List<TaskMongo> taskMongos = new ArrayList<>();
                    if (flag) {
                        taskMongos = taskMongosName;
                    } else {
                        taskMongos = mongoTemplate.find(query, TaskMongo.class);
                    }
                    List<TaskMongoDto> taskMongoDtoList = new ArrayList<TaskMongoDto>();
                    for (TaskMongo taskMongo : taskMongos) {
                        TaskMongoDto taskMongoDto = new TaskMongoDto();
                        taskMongoDto.setId(taskMongo.getId());
                        taskMongoDto.setName(taskMongo.getName());
                        taskMongoDto.setProjectId(taskMongo.getProjectId());
                        taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
                        taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
                        Query childrenQuery = new Query(Criteria.where("parent").is(taskMongo));
                        long children = mongoTemplate.count(childrenQuery, TaskMongo.class);
                        taskMongoDto.setLeaf(children == 0);
                        //如果时项目负责人有最高权限
                        taskMongoDto.setFlag(true);
                        taskMongoDtoList.add(taskMongoDto);
                    }
                    return taskMongoDtoList;
                }
            }
            Criteria criteriaMongo = new Criteria();
            criteriaMongo = criteriaMongo.and("containUserList").is(userId);
            if (criteria.getProjectId() != null) {
                criteriaMongo = criteriaMongo.and("projectId").is(criteria.getProjectId()).and("pid").is(null);
            }
            if (criteria.getName() != null) {
                criteriaMongo = criteriaMongo.and("name").regex(Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE)).and("pid").is(null);
            }
            Query query = new Query(criteriaMongo);
            Long totalCount = mongoTemplate.count(query, TaskMongo.class);
            if (totalCount == 0) {
                return Collections.emptyList();
            }
            //获取包含成员
            List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
            List<TaskMongoDto> taskMongoDtoList = new ArrayList<TaskMongoDto>();
            for (TaskMongo taskMongo : taskMongoList) {
                TaskMongoDto taskMongoDto = new TaskMongoDto();
                taskMongoDto.setId(taskMongo.getId());
                taskMongoDto.setName(taskMongo.getName());
                taskMongoDto.setProjectId(taskMongo.getProjectId());
                taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
                taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
                Query childrenQuery = new Query(Criteria.where("parent").is(taskMongo));
                long children = mongoTemplate.count(childrenQuery, TaskMongo.class);
                taskMongoDto.setLeaf(children == 0);
                if (taskMongo.getUserIdList().contains(SecurityUtils.getCurrentUserId())) {
                    //如果当前用户是某个任务的任务负责人的话,也可拥有全部的分配任务的权限
                    taskMongoDto.setFlag(true);
                }
                taskMongoDtoList.add(taskMongoDto);
            }
            return taskMongoDtoList;
        } else {
            List<TaskMongoDto> taskMongoDtoList = new ArrayList<>();
            if (criteria.getName() != null) {
                Criteria criteriaTask = new Criteria();
                Pattern pattern = Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE);
                criteriaTask.and("name").is(pattern);
                criteriaTask.and("pid").is(null);
                taskMongosName = mongoTemplate.find(Query.query(criteriaTask), TaskMongo.class);
                flag = true;
            }
            List<TaskMongo> all;
            if (flag) {
                all = taskMongosName;
            } else {
                all = mongoTemplate.find(Query.query(new Criteria("projectId").is(criteria.getProjectId()).and("pid").is(null)), TaskMongo.class);
            }
            //获取所有的任务
            for (TaskMongo taskMongo : all) {
                TaskMongoDto taskMongoDto = new TaskMongoDto();
                taskMongoDto.setId(taskMongo.getId());
                taskMongoDto.setName(taskMongo.getName());
                taskMongoDto.setProjectId(taskMongo.getProjectId());
                taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
                taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
                Query childrenQuery = new Query(Criteria.where("parent").is(taskMongo));
                long children = mongoTemplate.count(childrenQuery, TaskMongo.class);
                taskMongoDto.setLeaf(children == 0);
                taskMongoDto.setFlag(true);
                taskMongoDtoList.add(taskMongoDto);
            }
            int num = taskMongoDtoList.size();
            return taskMongoDtoList;
        }
    }
    @Override
    @Transactional
    public TaskDto findById(Long id) {
        Task task = taskRepository.findById(id).orElseGet(Task::new);
        ValidationUtil.isNull(task.getId(), "Task", "id", id);
        return taskMapper.toDto(task);
    }
    @Override
    //删除已有的任务缓存
    @CacheEvict(cacheNames = "ChildrenTask", allEntries = true)
    public TaskMongo create(Long userId, TaskMongo resources) {
        resources.setTaskStatus(Constant.TASK_STATUS_NOT_STARTED);
        synchronized (lock) {
            // 查询最大的old_id值
            Query query = new Query();
            query.with(Sort.by(Sort.Direction.DESC, "old_id"));
            query.limit(1);
            TaskMongo maxObject = mongoTemplate.findOne(query, TaskMongo.class);
            resources.setOld_id(maxObject.getOld_id() + 1);
        }
        return mongoTemplate.save(resources);
    }
    @Override
    @CacheEvict(cacheNames = "ChildrenTask",allEntries = true)
    public TaskMongo update(Long userId,TaskMongo resources) {
//        //如果他不是任务的负责人但是他还可能是任务的参与人员
//        List<Long> containUserList = resources.getContainUserList();
//        List<Long> userIdList = resources.getUserIdList();
//        //如果他已经不是任务的参与人员他就一定要删除
//        List<Long> removeList = userIdList.stream().filter(o -> !containUserList.contains(o)).collect(Collectors.toList());
//        userIdList.removeAll(removeList);
//        resources.setUserIdList(userIdList);
//
//        containUserList.addAll(userIdList.stream().filter(o -> !containUserList.contains(o)).collect(Collectors.toList()));
        return mongoTemplate.save(resources);
    }
    private Boolean deleteWithChildren(List<TaskMongo> taskMongoList) {
        Boolean result = true;
        if (taskMongoList.size() == 0) {
            return result;
        }
        for (TaskMongo taskMongo : taskMongoList) {
            List<TaskMongo> children = mongoTemplate.find(Query.query(Criteria.where("parent").is(taskMongo)), TaskMongo.class);
            Boolean deleteFlg = deleteWithChildren(children);
            if (!deleteFlg) {
                result = false;
                continue;
            }
            Long count = mongoTemplate.count(Query.query(Criteria.where("task").is(taskMongo)), TaskUserMongo.class);
            if (count > 0) {
                result = false;
                continue;
            }
            mongoTemplate.remove(taskMongo);
        }
        return result;
    }
    @Override
    @CacheEvict(cacheNames = "ChildrenTask",allEntries = true)
    public Boolean deleteAll(Long userId,String[] ids) {
        List<TaskMongo> taskMongoList = mongoTemplate.find(Query.query(Criteria.where("id").in(Arrays.asList(ids))), TaskMongo.class);
        return deleteWithChildren(taskMongoList);
    }
    @Override
    public void download(List<TaskDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TaskDto task : all) {
            String projectName = task.getProjectId() != null ? projectRepository.findById(task.getProjectId()).orElseGet(Project::new).getName() : "";
            String pidName = task.getPid() != null ? taskRepository.findById(task.getPid()).orElseGet(Task::new).getName() : "";
            String priority = task.getPriority() != null ? dictDetailRepository.findByDictNameAndValue(Constant.PRIORITY, task.getPriority()).getLabel() : "";
            String taskClassification = task.getTaskClassification() != null ? dictDetailRepository.findByDictNameAndValue(Constant.TASK_CLASSIFICATION, task.getTaskClassification()).getLabel() : "";
            String planWorkloadUnit = task.getPlanWorkloadUnit() != null ? dictDetailRepository.findByDictNameAndValue(Constant.STANDARD_WORKLOAD_UNIT, task.getPlanWorkloadUnit()).getLabel() : "";
            String taskStatus = task.getTaskStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.TASK_STATUS, task.getTaskStatus()).getLabel() : "";
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("项目名称", projectName);
            map.put("父任务名称", pidName);
            map.put("名称", task.getName());
            map.put("优先度", priority);
            map.put("任务分类", taskClassification);
            map.put("描述", task.getDescription());
            map.put("计划开始时间", task.getPlanStartTime());
            map.put("计划结束时间", task.getPlanEndTime());
            map.put("计划工时", task.getPlanHours());
            map.put("计划工作量", task.getPlanWorkload());
            map.put("计划工作量单位", planWorkloadUnit);
            map.put("任务状态", taskStatus);
            map.put("备注", task.getRemarks());
            map.put("创建者", task.getCreateBy());
            map.put("创建时间", task.getCreateTime());
            map.put("更新者", task.getUpdateBy());
            map.put("更新时间", task.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
//    @Override
//    public List<TaskDto> queryPartakeAll(TaskQueryCriteria criteria){
//        // 根据用户ID、项目ID查询任务ID
//        List<Long> partakeTaskIds = taskUserRepository.findTaskIdByUserIdAndProjectId(criteria.getTaskUserId(), criteria.getProjectId());
//        // 判断长度
//        if (partakeTaskIds.size() == 0) {
//            return new ArrayList<>();
//        }
//        // 项目检索条件
//        criteria.setIdInList(partakeTaskIds);
//        criteria.setTaskStatusNotEqual(Constant.TASK_STATUS_COMPLETED);
//        return taskMapper.toDto(taskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
//    }
/*
 *  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.task.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.project.domain.Project;
import me.zhengjie.modules.project.repository.ProjectRepository;
import me.zhengjie.modules.project.service.ProjectService;
import me.zhengjie.modules.project.service.dto.ProjectDto;
import me.zhengjie.modules.project.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.task.domain.*;
import me.zhengjie.modules.task.repository.TaskDaliyRepository;
import me.zhengjie.modules.task.repository.TaskRepository;
import me.zhengjie.modules.task.repository.TaskUserRepository;
import me.zhengjie.modules.task.service.TaskService;
import me.zhengjie.modules.task.service.dto.TaskDto;
import me.zhengjie.modules.task.service.dto.TaskMongoDto;
import me.zhengjie.modules.task.service.dto.TaskQueryCriteria;
import me.zhengjie.modules.task.service.dto.TaskUserMongoDto;
import me.zhengjie.modules.task.service.mapstruct.TaskMapper;
import me.zhengjie.modules.treatment.repository.UserLevelWageRepository;
import me.zhengjie.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
 * @author 赵士淞
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-12-27
 **/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "task")
public class TaskServiceImpl implements TaskService {
    private final TaskRepository taskRepository;
    private final TaskMapper taskMapper;
    private final ProjectRepository projectRepository;
    private final DictDetailRepository dictDetailRepository;
    private final TaskUserRepository taskUserRepository;
    private final TaskDaliyRepository taskDaliyRepository;
    private final UserRepository userRepository;
    private final RoleService roleService;
    private final UserLevelWageRepository userLevelWageRepository;
    @Autowired
    private ProjectService projectService;
    private final MongoTemplate mongoTemplate;
    private final Object lock = new Object();
    @Override
    public List getAllTags(String tagName) {
        Criteria criteria = new Criteria();
        if (tagName != null && tagName.trim().length() > 0) {
            criteria = criteria.and("tagList").regex("^.*" + tagName + ".*$");
        }
        Aggregation customerAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.project("tagList"),
                Aggregation.unwind("tagList"),
                Aggregation.group("tagList")
        );
        AggregationResults<Map> taskUserMongoList = mongoTemplate.aggregate(customerAgg, TaskMongo.class, Map.class);
//        System.out.println(taskUserMongoList.getMappedResults().stream().flatMap(map -> map.values().stream()).collect(Collectors.toList()));
        return (List) taskUserMongoList.getMappedResults().stream().flatMap(map -> map.values().stream()).collect(Collectors.toList());
    }
    @Override
    public List<ProjectDto> getAllProjects(ProjectQueryCriteria criteria) {
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
            ArrayList<Long> projectList = new ArrayList<>();
            Query query = Query.query(Criteria.where("containUserList").is(SecurityUtils.getCurrentUserId()));
            List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
            for (TaskMongo taskMongo : taskMongoList) {
                projectList.add(taskMongo.getProjectId());
            }
            // 根据用户ID查询负责的项目ID
            List<Long> projectIdList = projectRepository.findIdByLiableUserId(SecurityUtils.getCurrentUserId());
            Set<Long> projectIds = Stream.of(projectList, projectIdList).flatMap(Collection::stream).collect(Collectors.toSet());
            criteria.setApproveStatusIn(Arrays.asList(Constant.APPROVE_STATUS_MASTER_ACKNOWLEDGED, Constant.APPROVE_STATUS_ACKNOWLEDGED));
            criteria.setProjectStatusNotEqual(Constant.PROJECT_STATUS_COMPLETED);
            criteria.setIdInList(new ArrayList<Long>(projectIds));
        } else {
            // 根据用户ID查询负责的项目ID
            List<Project> projectIdList = projectRepository.findAll();
            List<Long> projectIds = new ArrayList<>();
            for (Project project : projectIdList) {
                projectIds.add(project.getId());
            }
            criteria.setApproveStatusIn(Arrays.asList(Constant.APPROVE_STATUS_MASTER_ACKNOWLEDGED, Constant.APPROVE_STATUS_ACKNOWLEDGED));
            criteria.setProjectStatusNotEqual(Constant.PROJECT_STATUS_COMPLETED);
            criteria.setIdInList(projectIds);
        }
        return projectService.queryAll2(criteria);
    }
    @Override
    //@Cacheable(key = "'projectId:' + #p0")
    public List<TaskMongo> allOfDaily(Long projectId) {
        List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(
                Query.query(new Criteria("userId").is(SecurityUtils.getCurrentUserId())
                        .and("taskStatus").in(Constant.TASK_STATUS_NOT_STARTED, Constant.TASK_STATUS_IN_HAND, Constant.TASK_STATUS_TEST, Constant.TASK_STATUS_UNRECOGNIZED)
                ), TaskUserMongo.class);
        return taskUserMongoList.stream().filter(taskUserMongo -> taskUserMongo.getTask().getProjectId().equals(projectId))
                .map(taskUserMongo -> taskUserMongo.getTask()).distinct().collect(Collectors.toList());
    }
    @Override
    public List<TaskUserMongoDto> getRelevantTaskUser(String taskId) {
        Criteria criteriaMongo = new Criteria();
        //查找出这个任务中所有的分配任务
        criteriaMongo.and("task.id").is(taskId);
        criteriaMongo.and("taskStatus").ne(Constant.TASK_STATUS_COMPLETED);
        List<TaskUserMongo> taskUserMongos = mongoTemplate.find(Query.query(criteriaMongo), TaskUserMongo.class);
        //将所有有负责人Id的人筛出来
        taskUserMongos = taskUserMongos.stream().filter(item -> item.getUserId() != null).collect(Collectors.toList());
        taskUserMongos.removeIf(taskUserMongo -> !taskUserMongo.getUserId().equals(SecurityUtils.getCurrentUserId()));
        List<TaskUserMongoDto> taskUserMongoDtoList = new ArrayList<>();
        taskUserMongos.forEach(item -> {
//            //如果有指定的任务负责人就获取这个任务负责人的绩效绩点
//            Double coefficientByUserId = userLevelWageRepository.findPerformanceCoefficientByUserId(SecurityUtils.getCurrentUserId()).get(0);
            TaskUserMongoDto dto = new TaskUserMongoDto();
//            if (item.getPerformanceType() == null) {
//                TaskMongo byId = mongoTemplate.findById(item.getTask().getId(), TaskMongo.class);
//                item.setPerformanceType(byId.getPerformanceType());
//                mongoTemplate.save(item);
//                getRelevantTaskUser(taskId);
//            }
//            if (item.getPerformanceType().equals("1")) {
//                //绩效任务
//                DecimalFormat decimalFormat = new DecimalFormat("#0");
//                String format = decimalFormat.format(item.getTaskHours() / coefficientByUserId);
//                item.setPerformanceHours(Double.valueOf(format));
//            } else {
                item.setPerformanceHours(item.getTaskHours());
//            }
            dto.setId(item.getId());
            dto.setName(item.getName());
            dto.setProjectId(item.getTask().getProjectId());
            dto.setRemarks(item.getRemarks());
            dto.setTaskHours(item.getTaskHours());
            dto.setTaskStatus(item.getTaskStatus());
            dto.setTaskId(item.getTask().getId());
            dto.setUserId(SecurityUtils.getCurrentUserId());
            dto.setPerformanceHours(item.getPerformanceHours());
            dto.setTaskStartDate(item.getTaskStartDate());
            dto.setTaskEndDate(item.getTaskEndDate());
            //List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(Query.query(new Criteria("userId").is(SecurityUtils.getCurrentUserId()).and("taskUserMongo.id").is(item.getId())), TaskDaliyMongo.class);
            AtomicReference<Double> consumptionHours = new AtomicReference<>(0D);
            //获取已消耗的工时
            List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(new Query(new Criteria("taskUserMongo.id").is(item.getId())), TaskDaliyMongo.class);
            daliyMongoList.forEach(daliy -> consumptionHours.updateAndGet(v -> v + daliy.getConsumedHours()));
            if (daliyMongoList.size() == 0) {
                //如果没有日志,统一赋值为0
                dto.setMaxTaskProgress(0D);
                dto.setAlreadyConsumedHours(consumptionHours.get());
                taskUserMongoDtoList.add(dto);
            } else {
                //如果有日志
                daliyMongoList.sort(((o1, o2) -> (int) (100 * (o2.getTaskProgress() - o1.getTaskProgress()))));
                dto.setMaxTaskProgress(daliyMongoList.get(0).getTaskProgress());
                dto.setAlreadyConsumedHours(consumptionHours.get());
                taskUserMongoDtoList.add(dto);
            }
        });
        return taskUserMongoDtoList;
    }
    @Override
    public Map<String,Date> getTaskValidRange(String taskId) {
        TaskMongo byId = mongoTemplate.findById(taskId, TaskMongo.class);
        Map<String,Date> hashMap = new HashMap<>();
        assert byId != null;
        if(byId.getPlanStartTime() != null && byId.getPlanEndTime() != null){
            hashMap.put("start",byId.getPlanStartTime());
            hashMap.put("end",byId.getPlanEndTime());
        } else {
            hashMap.put("start",null);
            hashMap.put("end",null);
        }
        return hashMap;
    }
    /**
     * 查询任务列表
     * @param taskId
     * @return
     */
    @Override
    public List<TaskMongo> getTastAllById(String taskId) {
        Query query= Query.query(Criteria.where("id").in(taskId));
        List<TaskMongo> list= this.mongoTemplate.find(query, TaskMongo.class);
        return list;
    }
    @Override
    public void changeStatus(String[] ids) {
        List<TaskMongo> taskMongoList = mongoTemplate.find(Query.query(new Criteria("id").in(ids).and("taskStatus").ne(Constant.TASK_STATUS_COMPLETED)), TaskMongo.class);
        taskMongoList.stream().forEach(taskMongo -> {
            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(new Criteria("task").is(taskMongo).and("taskStatus").ne(Constant.TASK_STATUS_COMPLETED)), TaskUserMongo.class);
            taskUserMongoList.stream().forEach(taskUserMongo -> {
                taskUserMongo.setTaskStatus(Constant.TASK_STATUS_COMPLETED);
                mongoTemplate.save(taskUserMongo);
            });
            taskMongo.setTaskStatus(Constant.TASK_STATUS_COMPLETED);
            mongoTemplate.save(taskMongo);
        });
    }
    @Override
    public List<Map<String, Object>> getTaskCalendarInfo(String date,String taskId) {
        List<String> colorList = new ArrayList<>();
        Collections.addAll(colorList,"#409EFF","#67C23A","#F56C6C","#909399","#E6A23C");
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(new Criteria("task._id").is(taskId)), TaskUserMongo.class);
        for (TaskUserMongo taskUserMongo : taskUserMongoList) {
            HashMap<String,Object> map = new HashMap<>();
            map.put("start",taskUserMongo.getTaskStartDate());
            map.put("end",taskUserMongo.getTaskEndDate());
            map.put("title",taskUserMongo.getName());
            map.put("type",1);
            int index = new Random().nextInt(colorList.size());
            map.put("color",colorList.get(index));
            mapList.add(map);
        }
        return mapList;
    }
    @Override
    public List<Map<String, String>> getAllNames(Long projectId, String name) {
        if (name == null || name.trim().length() == 0) {
            return Collections.emptyList();
        }
        Criteria criteria = new Criteria();
        if (name != null && name.trim().length() > 0) {
            criteria = criteria.and("name").regex("^.*" + name + ".*$");
        }
        criteria.and("projectId").is(projectId);
        final List<Map<String, String>> result = new ArrayList<Map<String, String>>();
        List<TaskMongo> taskMongoList = mongoTemplate.find(new Query(criteria).with(Pageable.ofSize(10)), TaskMongo.class);
        taskMongoList.forEach(item -> {
            Map<String, String> itemMap = new LinkedHashMap<String, String>();
            itemMap.put("id", item.getName());
            itemMap.put("value", item.getName());
            itemMap.put("label", item.getName());
            result.add(itemMap);
        });
        return result;
    }
    @Override
    public List<TaskAggrMongo> queryProjectTotal(Long projectId) {
        Criteria criteriaMongo = new Criteria();
        criteriaMongo = criteriaMongo.and("projectId").is(projectId);
        Aggregation customerAgg = Aggregation.newAggregation(
                Aggregation.match(criteriaMongo),
                Aggregation.project("taskStatus", "planHours"),
                Aggregation.group("taskStatus").count().as("count").sum("planHours").as("planHours")
        );
        AggregationResults<TaskAggrMongo> taskUserMongoList = mongoTemplate.aggregate(customerAgg, TaskMongo.class, TaskAggrMongo.class);
        return taskUserMongoList.getMappedResults();
    }
    @Override
    public Map<String, Object> queryAll(TaskQueryCriteria criteria, Pageable pageable) {
        Criteria criteriaMongo = new Criteria();
        if (criteria.getProjectId() != null) {
            criteriaMongo = criteriaMongo.and("projectId").is(criteria.getProjectId());
        }
        if (criteria.getName() == null) {
            criteriaMongo = criteriaMongo.and("parent").exists(false);
        } else {
            criteriaMongo = criteriaMongo.and("name").regex(Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        if (criteria.getTaskStatuses() != null && criteria.getTaskStatuses().size() > 0) {
            criteriaMongo = criteriaMongo.and("taskStatus").in(criteria.getTaskStatuses());
        }
        if (criteria.getUserIds() != null && criteria.getUserIds().size() > 0) {
            criteriaMongo = criteriaMongo.and("userIdList").in(criteria.getUserIds());
        }
        if (criteria.getTagList() != null && criteria.getTagList().size() > 0) {
            criteriaMongo = criteriaMongo.and("tagList").in(criteria.getTagList());
        }
//        if(criteria.getUserIds() != null && criteria.getUserIds().size() > 0){
//            criteriaMongo = criteriaMongo.and("containUserList").in(criteria.getUserIds());
//        }
        if(criteria.getPerformanceType() != null) {
            criteriaMongo = criteriaMongo.and("performanceType").is(criteria.getPerformanceType());
        }
        Query query = new Query(criteriaMongo);
        Long totalCount = mongoTemplate.count(query, TaskMongo.class);
        if (totalCount == 0) {
            return PageUtil.toPage(Collections.emptyList(), 0);
        }
        List<TaskMongo> taskMongoList = mongoTemplate.find(query.with(pageable), TaskMongo.class);
        List<TaskMongoDto> taskMongoDtoList;
        if (criteria.getName() == null) {
            taskMongoDtoList = createTree(null, taskMongoList);
        } else {
            taskMongoDtoList = createTreeWithoutChildren(null, taskMongoList);
        }
        return PageUtil.toPage(taskMongoDtoList, totalCount);
    }
    private List<TaskMongoDto> createTreeWithoutChildren(String parentPath, List<TaskMongo> taskMongoList) {
        List<TaskMongoDto> result = new ArrayList<TaskMongoDto>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
            taskMongoDto.setOld_id(taskMongo.getOld_id());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            // 根据项目ID查询项目信息
            Project project = projectRepository.findById(taskMongo.getProjectId()).orElseGet(Project::new);
            // 项目名称
            taskMongoDto.setProjectName(project.getName());
//            TaskMongoDto parentDto = new TaskMongoDto();
//            parentDto.setId(taskMongo.getParent() == null ? null : taskMongo.getParent().getId());
//            taskMongoDto.setParent(parentDto);
            taskMongoDto.setPerformanceType(taskMongo.getPerformanceType());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
            taskMongoDto.setPlanHours(taskMongo.getPlanHours());
            taskMongoDto.setTaskStatus(taskMongo.getTaskStatus());
            taskMongoDto.setDescription(taskMongo.getDescription());
            taskMongoDto.setUserIdList(taskMongo.getUserIdList());
            taskMongoDto.setContainUserList(taskMongo.getContainUserList());
            taskMongoDto.setTagList(taskMongo.getTagList());
            taskMongoDto.setVersion(taskMongo.getVersion());
            if (taskMongo.getPlanWorkload() != null) {
                taskMongoDto.setPlanWorkload(taskMongo.getPlanWorkload());
            }
            if (taskMongo.getPlanWorkloadUnit() != null) {
                taskMongoDto.setPlanWorkloadUnit(taskMongo.getPlanWorkloadUnit());
            }
            taskMongoDto.setConsumedHours(0.0D);
            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(Criteria.where("task").is(taskMongo)), TaskUserMongo.class);
            List<TaskDaliyMongo> taskDaliyMongoList = mongoTemplate.find(Query.query(Criteria.where("taskUserMongo").in(taskUserMongoList)), TaskDaliyMongo.class);
            double consumedHours = taskDaliyMongoList.stream()
                    .map(taskDaliyMongo -> BigDecimal.valueOf(taskDaliyMongo.getConsumedHours()))
                    .reduce(BigDecimal::add).orElse(BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue();
            taskMongoDto.setConsumedHours(taskMongoDto.getConsumedHours() + consumedHours);
            Query query = new Query(Criteria.where("parent").is(taskMongo));
            List<TaskMongo> children = mongoTemplate.find(query, TaskMongo.class);
            if (children == null || children.size() == 0) {
                taskMongoDto.setSumPlanHours(taskMongo.getPlanHours());
            } else {
                List<TaskMongoDto> childrenDto = createTree(null, children);
                Double sumHours = BigDecimal.valueOf(
                        childrenDto.stream().collect(
                                Collectors.summingDouble(TaskMongoDto::getSumPlanHours))).round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue();
                taskMongoDto.setSumPlanHours(sumHours);
            }
            result.add(taskMongoDto);
        }
        return result;
    }
    private List<TaskMongoDto> createTree(String parentPath, List<TaskMongo> taskMongoList) {
        List<TaskMongoDto> result = new ArrayList<TaskMongoDto>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
            taskMongoDto.setOld_id(taskMongo.getOld_id());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            // 根据项目ID查询项目信息
            Project project = projectRepository.findById(taskMongo.getProjectId()).orElseGet(Project::new);
            // 项目名称
            taskMongoDto.setProjectName(project.getName());
            TaskMongoDto parentDto = new TaskMongoDto();
//            parentDto.setId(taskMongo.getParent() == null ? null : taskMongo.getParent().getId());
            taskMongoDto.setParent(parentDto);
            taskMongoDto.setPerformanceType(taskMongo.getPerformanceType());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
            taskMongoDto.setPlanHours(taskMongo.getPlanHours());
            taskMongoDto.setTaskStatus(taskMongo.getTaskStatus());
            taskMongoDto.setDescription(taskMongo.getDescription());
            taskMongoDto.setUserIdList(taskMongo.getUserIdList());
            taskMongoDto.setContainUserList(taskMongo.getContainUserList());
            taskMongoDto.setTagList(taskMongo.getTagList());
            taskMongoDto.setVersion(taskMongo.getVersion());
            if (taskMongo.getPlanWorkload() != null) {
                taskMongoDto.setPlanWorkload(taskMongo.getPlanWorkload());
            }
            if (taskMongo.getPlanWorkloadUnit() != null) {
                taskMongoDto.setPlanWorkloadUnit(taskMongo.getPlanWorkloadUnit());
            }
            taskMongoDto.setConsumedHours(0.0D);
//            taskMongoDto.setPerformanceHours(0.0D);
            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(Criteria.where("task").is(taskMongo)), TaskUserMongo.class);
            List<TaskDaliyMongo> taskDaliyMongoList = mongoTemplate.find(Query.query(Criteria.where("taskUserMongo").in(taskUserMongoList)), TaskDaliyMongo.class);
            double consumedHours = taskDaliyMongoList.stream()
                    .map(taskDaliyMongo -> BigDecimal.valueOf(taskDaliyMongo.getConsumedHours()))
                    .reduce(BigDecimal::add).orElse(BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue();
            taskMongoDto.setConsumedHours(taskMongoDto.getConsumedHours() + consumedHours);
//            for (TaskUserMongo taskUserMongo : taskUserMongoList) {
//                if (taskUserMongo.getTaskDaliyList().size() > 0) {
//                    Double total = taskUserMongo.getTaskDaliyList().stream().collect(Collectors.summingDouble(TaskDaliyMongo::getConsumedHours));
//                    taskMongoDto.setConsumedHours(taskMongoDto.getConsumedHours() + total);
//                    TaskDaliyMongo taskDaliyMongo = taskUserMongo.getTaskDaliyList().get(0);
//                    taskMongoDto.setPerformanceHours(taskMongoDto.getPerformanceHours() + (taskUserMongo.getTaskHours() * taskDaliyMongo.getTaskProgress()/100));
//                }
//            }
            Query query = new Query(Criteria.where("parent").is(taskMongo));
            List<TaskMongo> children = mongoTemplate.find(query, TaskMongo.class);
            if (children == null || children.size() == 0) {
                taskMongoDto.setSumPlanHours(taskMongo.getPlanHours());
            } else {
                List<TaskMongoDto> childrenDto = createTree(null, children);
                taskMongoDto.setChildren(childrenDto);
                Double sumHours = BigDecimal.valueOf(
                        childrenDto.stream().collect(
                                Collectors.summingDouble(TaskMongoDto::getSumPlanHours))).round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue();
                taskMongoDto.setSumPlanHours(sumHours);
//                Double consumedHours = BigDecimal.valueOf(
//                        childrenDto.stream().collect(
//                                Collectors.summingDouble(TaskMongoDto::getConsumedHours))).round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue();
//                taskMongoDto.setConsumedHours(consumedHours + taskMongoDto.getConsumedHours());
//
//                Double performanceHours = BigDecimal.valueOf(
//                        childrenDto.stream().collect(
//                                Collectors.summingDouble(TaskMongoDto::getPerformanceHours))).round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue();
//                taskMongoDto.setPerformanceHours(performanceHours + taskMongoDto.getPerformanceHours());
            }
            result.add(taskMongoDto);
        }
        return result;
    }
    private TaskDto customHandle(TaskDto taskDto) {
        // 根据项目ID查询项目信息
        Project project = projectRepository.findById(taskDto.getProjectId()).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", taskDto.getProjectId());
        // 项目名称
        taskDto.setProjectName(project.getName());
        if (project.getLiableUserId() != null && !"".equals(project.getLiableUserId())) {
            // 负责人ID列表
            List<Long> projectLiableUserIdList = new ArrayList<>();
            // 项目责任人ID
            String projectLiableUserId = project.getLiableUserId().replace("-", "");
            String[] projectLiableUserIds = projectLiableUserId.split(",");
            // 循环负责人ID列表
            for (String liableUserId : projectLiableUserIds) {
                // 负责人ID列表
                projectLiableUserIdList.add(Long.valueOf(liableUserId));
            }
            // 项目责任人ID
            taskDto.setProjectLiableUserIdList(projectLiableUserIdList);
        }
        // 判断父级任务ID是否为空
        if (taskDto.getPid() != null) {
            // 根据父级任务ID查询任务信息
            Task task = taskRepository.findById(taskDto.getPid()).orElseGet(Task::new);
            ValidationUtil.isNull(task.getId(), "Task", "id", taskDto.getPid());
            // 父级任务名称
            taskDto.setPidName(task.getName());
        }
        // 根据父级任务ID查询
        List<Task> childrenTaskList = taskRepository.findByPid(taskDto.getId());
        // 判断子级数量
        if (childrenTaskList.size() > 0) {
            // 是否有子级
            taskDto.setHasChildren(true);
        } else {
            // 是否有子级
            taskDto.setHasChildren(false);
        }
        // 据任务ID查询任务工时总和
        Double sumTaskHours = taskUserRepository.sumTaskHoursByTaskId(taskDto.getId());
        // 已分配工时
        taskDto.setDivideHours(sumTaskHours);
        // 据任务ID查询任务工作量总和
        Double sumTaskWorkload = taskUserRepository.sumTaskWorkloadByTaskId(taskDto.getId());
        // 已分配工作量
        taskDto.setDivideWorkload(sumTaskWorkload);
        // 已完成工时
        Double completedHours = 0D;
        if (Constant.PERFORMANCE_TYPE_ON.equals(taskDto.getPerformanceType())) {
            // 根据项目ID、任务ID查询各用户填报的最大任务进度日报信息
            //List<Map> taskDaliyMapList = taskDaliyRepository.findMaxTaskProgressByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
            // 循环最大任务进度日报
//            for (int i = 0; i < taskDaliyMapList.size(); i++) {
//                // 最大任务进度日报信息
//                Map taskDaliyMap = taskDaliyMapList.get(i);
//                // 已完成工时
//                completedHours += new BigDecimal(taskDaliyMap.get("task_hours").toString()).multiply(new BigDecimal(taskDaliyMap.get("task_progress").toString())).doubleValue() / 100;
//            }
        } else {
            List<TaskDaliy> taskDaliyList = taskDaliyRepository.findByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
            for (TaskDaliy taskDaliy : taskDaliyList) {
                completedHours += taskDaliy.getConsumedHours();
            }
        }
        // 已完成工时
        taskDto.setCompletedHours(completedHours);
        // 根据项目ID、任务ID查询总消耗工作量
        //Double completedWorkload = taskDaliyRepository.findSumConsumedWorkloadByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
        // 已完成工作量
        //taskDto.setCompletedWorkload(completedWorkload);
        // 根据任务ID查询所属用户
        List<Long> userIdList = taskUserRepository.findUserIdByTaskId(taskDto.getId());
        // 已分配用户
        taskDto.setDivideUserIds(userIdList);
        // 返回
        return taskDto;
    }
    @Override
    public TaskDto customHandleMini(TaskDto taskDto) {
        // 据任务ID查询任务工时总和
        Double sumTaskHours = taskUserRepository.sumTaskHoursByTaskId(taskDto.getId());
        // 已分配工时
        taskDto.setDivideHours(sumTaskHours);
        // 已完成工时
        Double completedHours = 0D;
        if (Constant.PERFORMANCE_TYPE_ON.equals(taskDto.getPerformanceType())) {
            // 根据项目ID、任务ID查询各用户填报的最大任务进度日报信息
            //List<Map> taskDaliyMapList = taskDaliyRepository.findMaxTaskProgressByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
            // 循环最大任务进度日报
//            for (int i = 0; i < taskDaliyMapList.size(); i++) {
//                // 最大任务进度日报信息
//                Map taskDaliyMap = taskDaliyMapList.get(i);
//                // 已完成工时
//                completedHours += new BigDecimal(taskDaliyMap.get("task_hours").toString()).multiply(new BigDecimal(taskDaliyMap.get("task_progress").toString())).doubleValue() / 100;
//            }
        } else {
            List<TaskDaliy> taskDaliyList = taskDaliyRepository.findByProjectIdAndTaskId(taskDto.getProjectId(), taskDto.getId());
            for (TaskDaliy taskDaliy : taskDaliyList) {
                completedHours += taskDaliy.getConsumedHours();
            }
        }
        // 已完成工时
        taskDto.setCompletedHours(completedHours);
        // 返回
        return taskDto;
    }
    @Override
    public List<TaskMongoDto> queryAll(TaskQueryCriteria criteria) {
//        // 获取登录用户角色等级
//        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
//        // 登录用户最大角色等级
//        int min = Collections.min(levels);
//        // 判断角色等级
//        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
////            // 根据用户ID查询参与的项目ID
////            List<Long> taskUserProjectIdList = taskUserRepository.findProjectIdByUserId(SecurityUtils.getCurrentUserId());
//            // 根据用户ID查询负责的项目ID
//            List<Long> projectIdList = projectRepository.findIdByLiableUserId(SecurityUtils.getCurrentUserId());
//            // 检索条件
//            List<Long> totalProjectIdList = Stream.of(projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
//            if (totalProjectIdList.size() == 0) {
//                return Collections.emptyList();
//            }
//            criteria.setProjectIdInList(totalProjectIdList);
//        }
//
//        Criteria criteriaMongo = new Criteria();
//        if (criteria.getProjectId() != null) {
//            criteriaMongo = criteriaMongo.and("projectId").is(criteria.getProjectId());
//        } else if (criteria.getProjectIdInList() != null) {
//            criteriaMongo = criteriaMongo.and("projectId").in(criteria.getProjectIdInList().toArray());
//        }
//        if (criteria.getName() != null) {
////            criteriaMongo = criteriaMongo.and("parent").exists(false);
////        } else {
//            criteriaMongo = criteriaMongo.and("name").regex(Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE));
//        }
//        Query query = new Query(criteriaMongo);
//        Long totalCount = mongoTemplate.count(query, TaskMongo.class);
//        if (totalCount == 0) {
//            return Collections.emptyList();
//        }
//        List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
//        return taskMongoList;
        Criteria criteriaMongo = new Criteria();
        if (criteria.getProjectId() != null) {
            criteriaMongo = criteriaMongo.and("projectId").is(criteria.getProjectId());
        }
        if (criteria.getName() == null) {
            criteriaMongo = criteriaMongo.and("parent").exists(false);
        } else {
            criteriaMongo = criteriaMongo.and("name").regex(Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        if (criteria.getTaskStatuses() != null && criteria.getTaskStatuses().size() > 0) {
            criteriaMongo = criteriaMongo.and("taskStatus").in(criteria.getTaskStatuses());
        }
        if (criteria.getUserIds() != null && criteria.getUserIds().size() > 0) {
            criteriaMongo = criteriaMongo.and("userIdList").in(criteria.getUserIds());
        }
        if (criteria.getTagList() != null && criteria.getTagList().size() > 0) {
            criteriaMongo = criteriaMongo.and("tagList").in(criteria.getTagList());
        }
        if(criteria.getPerformanceType() != null) {
            criteriaMongo = criteriaMongo.and("performanceType").is(criteria.getPerformanceType());
        }
        Query query = new Query(criteriaMongo);
        List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
        List<TaskMongoDto> taskMongoDtoList = createTreeWithoutChildren(null, taskMongoList);
        return taskMongoDtoList;
    }
    public List<TaskMongoDto> findByCompanyId(Long companyId) {
        List<TaskMongo> taskMongoList;
        if (companyId != null) {
            Query query = new Query(Criteria.where("projectId").is(companyId).and("parent").exists(false));
            taskMongoList = mongoTemplate.find(query.limit(10), TaskMongo.class);
        } else {
            Query query = new Query(Criteria.where("parent").exists(false));
            taskMongoList = mongoTemplate.find(query.limit(10), TaskMongo.class);
        }
        return change2Dto(taskMongoList);
    }
    private List<TaskMongoDto> change2Dto(List<TaskMongo> taskMongoList) {
        List<TaskMongoDto> result = new ArrayList<TaskMongoDto>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
//            taskMongoDto.setPid(taskMongo.getParent() == null ? null : taskMongo.getParent().getId());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            taskMongoDto.setPerformanceType(taskMongo.getPerformanceType());
            taskMongoDto.setPlanHours(taskMongo.getPlanHours());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
//            taskMongoDto.setPriority(taskMongo.getPriority());
//            taskMongoDto.setTaskClassification(taskMongo.getTaskClassification());
            taskMongoDto.setTaskStatus(taskMongo.getTaskStatus());
//            taskMongoDto.setRemarks(taskMongo.getRemarks());
            Query query = new Query(Criteria.where("parent").is(taskMongo));
            List<TaskMongo> children = mongoTemplate.find(query, TaskMongo.class);
//            taskMongoDto.setChildren(change2Dto(children));
            result.add(taskMongoDto);
        }
        return result;
    }
    @Transactional
    public void moveData() {
        TaskQueryCriteria criteria = new TaskQueryCriteria();
        criteria.setPidIsNull(true);
        List<Task> taskList = taskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        changeToMongo(null, taskList);
        // List<TaskMongo> taskMongoList =
//        for (TaskMongo taskMongo : taskMongoList) {
//            mongoTemplate.save(taskMongo);
//        }
    }
    public void changeToMongo(TaskMongo parent, List<Task> taskList) {
        DictDetailQueryCriteria criteria = new DictDetailQueryCriteria();
        criteria.setDictName("task_classification");
        List<DictDetail> dictDetailList = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        Map<String, String> dictDetailMap = dictDetailList.stream().collect(Collectors.toMap(DictDetail::getValue, DictDetail::getLabel));
        for (Task task : taskList) {
            TaskMongo taskMongo = new TaskMongo();
            taskMongo.setProjectId(task.getProjectId());
            taskMongo.setName(task.getName());
//            taskMongo.setParent(parent);
            taskMongo.setPlanHours(task.getPlanHours());
            taskMongo.setPlanStartTime(task.getPlanStartTime());
            taskMongo.setPlanEndTime(task.getPlanEndTime());
            String classification = task.getTaskClassification();
            taskMongo.setTagList(Collections.singletonList(dictDetailMap.get(classification)));
            taskMongo.setPerformanceType(task.getPerformanceType());
            taskMongo.setTaskStatus(task.getTaskStatus());
            String[] userIds = projectRepository.findById(task.getProjectId()).get().getLiableUserId().replaceAll("-", "").split(",");
            taskMongo.setUserIdList(Stream.of(userIds).map(userId -> Long.valueOf(userId)).collect(Collectors.toList()));
            taskMongo = mongoTemplate.save(taskMongo);
            List<Task> taskListSub = getSubList(task);
            changeToMongo(taskMongo, taskListSub);
            List<TaskUser> taskUserList = taskUserRepository.findByTaskId(task.getId());
            for (TaskUser taskUser : taskUserList) {
                if (taskUser.getEnable()) {
                    TaskUserMongo taskUserMongo = new TaskUserMongo();
                    taskUserMongo.setTask(taskMongo);
                    taskUserMongo.setUserId(taskUser.getUserId());
                    taskUserMongo.setName(task.getName());
                    //taskUserMongo.setTaskClassification(task.getTaskClassification());
                    taskUserMongo.setPerformanceType(task.getPerformanceType());
                    taskUserMongo.setPriority(task.getPriority());
                    taskUserMongo.setPerformanceHours(null); // TODO
                    taskUserMongo.setTaskHours(taskUser.getTaskHours());
                    taskUserMongo.setTaskStartDate(taskUser.getTaskStartDate());
                    taskUserMongo.setTaskEndDate(taskUser.getTaskEndDate());
                    taskUserMongo.setTaskStatus(taskUser.getTaskStatus());
                    taskUserMongo.setRemarks(taskUser.getRemarks());
                    //List<TaskDaliy> taskDaliyList = taskDaliyRepository.findByProjectIdAndTaskIdAndUserIdOrderByFillDateDesc(taskMongo.getProjectId(), taskUser.getTaskId(), taskUser.getUserId());
                    List<TaskDaliyMongo> taskDaliyMongoList = new ArrayList<TaskDaliyMongo>();
//                    for (TaskDaliy taskDaliy : taskDaliyList) {
//                        TaskDaliyMongo taskDaliyMongo = new TaskDaliyMongo();
//                        taskDaliyMongo.setFillDate(taskDaliy.getFillDate());
//                        taskDaliyMongo.setConsumedHours(taskDaliy.getConsumedHours());
//                        taskDaliyMongo.setTaskProgress(taskDaliy.getTaskProgress());
//                        taskDaliyMongo.setSettlementStatus(taskDaliy.getSettlementStatus());
//                        taskDaliyMongo.setRemarks(taskDaliy.getRemarks());
//                        taskDaliyMongoList.add(taskDaliyMongo);
//                    }
                    //taskUserMongo.setTaskDaliyList(taskDaliyMongoList);
                    mongoTemplate.save(taskUserMongo);
                }
            }
        }
//        return resultList;
    }
//    public void changeRoute(TaskMongo taskMongo) {
//        TaskMongo taskMongoDB = mongoTemplate.findById(new ObjectId(taskMongo.getId()), TaskMongo.class);
//        List<TaskMongo> newChildren = taskMongo.getChildren();
//        List<TaskMongo> oldChildren = taskMongoDB.getChildren();
//        List<TaskMongo> insertList = newChildren.stream()
//                .filter(item -> !oldChildren.contains(item)).collect(Collectors.toList());
//        List<TaskMongo> deleteList = oldChildren.stream()
//                .filter(item -> !newChildren.contains(item)).collect(Collectors.toList());
//
//
//        //        Pattern pattern = Pattern.compile("^.*" + taskMongoDB.getPath() + "/$", Pattern.CASE_INSENSITIVE);
////        Query query = new Query(Criteria.where("path").regex(pattern));
////        List<TaskMongo> children = mongoTemplate.find(query, TaskMongo.class);
////        for (TaskMongo child : children) {
////            if (child.getPath().equals("/" + child.getName())) {
////                child.setPath(taskMongo.getPath() + child.getPath());
////            } else {
////                child.setPath(child.getPath().replace(taskMongoDB.getPath(), taskMongo.getPath()));
////            }
////            mongoTemplate.save(child);
////        }
//        mongoTemplate.save(taskMongo);
//    }
    public List<Task> getSubList(Task task) {
        return taskRepository.findByPid(task.getId());
    }
    @Override
    public List<TaskMongoDto> queryChildren(TaskQueryCriteria criteria) {
        Long userId = SecurityUtils.getCurrentUserId();
        Criteria criteriaMongo = new Criteria();
        criteriaMongo = criteriaMongo.and("containUserList").is(userId);
        if (criteria.getProjectId() != null) {
            criteriaMongo = criteriaMongo.and("projectId").is(criteria.getProjectId());
        }
//        if (criteria.getPid() == null) {
//            criteriaMongo = criteriaMongo.and("parent").exists(false);
//        } else {
//            TaskMongo parent = mongoTemplate.findById(new ObjectId(criteria.getPid()), TaskMongo.class);
//            criteriaMongo = criteriaMongo.and("parent").is(parent);
//        }
        if (criteria.getName() != null) {
            criteriaMongo = criteriaMongo.and("name").regex(Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        Query query = new Query(criteriaMongo);
        Long totalCount = mongoTemplate.count(query, TaskMongo.class);
        if (totalCount == 0) {
            return Collections.emptyList();
        }
        List<TaskMongo> taskMongoList = mongoTemplate.find(query, TaskMongo.class);
        List<TaskMongoDto> taskMongoDtoList = new ArrayList<TaskMongoDto>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
            Query childrenQuery = new Query(Criteria.where("parent").is(taskMongo));
            long children = mongoTemplate.count(childrenQuery, TaskMongo.class);
            taskMongoDto.setLeaf(children == 0);
            taskMongoDtoList.add(taskMongoDto);
        }
        return taskMongoDtoList;
    }
    // @Cacheable(cacheNames = "ChildrenTask", key = "'userId:' +#p0  + 'projectId:' + #p1.projectId")
    public List<TaskMongoDto> queryChildrenTaskAnyParent(Long userId,TaskQueryCriteria criteria) {
        // 获取登录用户角色等级
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        // 登录用户最大角色等级
        int min = Collections.min(levels);
        List<TaskMongo> taskMongoList = null;
        Criteria criteriaTask = new Criteria();
        criteriaTask.and("pid").is(null);
        criteriaTask.and("taskStatus").nin(Constant.TASK_STATUS_COMPLETED);
        if (criteria.getName() != null) {
            Pattern pattern = Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE);
            criteriaTask.and("name").is(pattern);
        }
        if (criteria.getProjectId() != null) {
            criteriaTask.and("projectId").is(criteria.getProjectId());
            if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
                //看看当前这个用户是不是这个项目的项目负责人,如果是项目负责人的话显示全部的任务
                List<Long> projectIds = projectRepository.findIdByLiableUserId(userId);
                if (!projectIds.contains(criteria.getProjectId())) {
                    criteriaTask.and("containUserList").is(userId);
                }
            }
        }
        Query query = new Query(criteriaTask);
        Long totalCount = mongoTemplate.count(query, TaskMongo.class);
        if (totalCount == 0) {
            return Collections.emptyList();
        }
        taskMongoList = mongoTemplate.find(query, TaskMongo.class);
        // 结果集
        List<TaskMongoDto> taskMongoDtoList = new ArrayList<>();
        for (TaskMongo taskMongo : taskMongoList) {
            TaskMongoDto taskMongoDto = new TaskMongoDto();
            taskMongoDto.setId(taskMongo.getId());
            taskMongoDto.setName(taskMongo.getName());
            taskMongoDto.setProjectId(taskMongo.getProjectId());
            taskMongoDto.setPlanStartTime(taskMongo.getPlanStartTime());
            taskMongoDto.setPlanEndTime(taskMongo.getPlanEndTime());
            Query childrenQuery = new Query(Criteria.where("parent").is(taskMongo));
            long children = mongoTemplate.count(childrenQuery, TaskMongo.class);
            taskMongoDto.setLeaf(children == 0);
            if (taskMongo.getUserIdList().contains(SecurityUtils.getCurrentUserId())) {
                //如果当前用户是某个任务的任务负责人的话,也可拥有全部的分配任务的权限
                taskMongoDto.setFlag(true);
            }
            taskMongoDtoList.add(taskMongoDto);
        }
        return taskMongoDtoList;
    }
    @Override
    @Transactional
    public TaskDto findById(Long id) {
        Task task = taskRepository.findById(id).orElseGet(Task::new);
        ValidationUtil.isNull(task.getId(), "Task", "id", id);
        return taskMapper.toDto(task);
    }
    @Override
    //删除已有的任务缓存
    @CacheEvict(cacheNames = "ChildrenTask", allEntries = true)
    public TaskMongo create(Long userId, TaskMongo resources) {
        resources.setTaskStatus(Constant.TASK_STATUS_NOT_STARTED);
        synchronized (lock) {
            // 查询最大的old_id值
            Query query = new Query();
            query.with(Sort.by(Sort.Direction.DESC, "old_id"));
            query.limit(1);
            TaskMongo maxObject = mongoTemplate.findOne(query, TaskMongo.class);
            resources.setOld_id(maxObject.getOld_id() + 1);
        }
        return mongoTemplate.save(resources);
    }
    @Override
    @CacheEvict(cacheNames = "ChildrenTask",allEntries = true)
    public TaskMongo update(Long userId,TaskMongo resources) {
//        //如果他不是任务的负责人但是他还可能是任务的参与人员
//        List<Long> containUserList = resources.getContainUserList();
//        List<Long> userIdList = resources.getUserIdList();
//        //如果他已经不是任务的参与人员他就一定要删除
//        List<Long> removeList = userIdList.stream().filter(o -> !containUserList.contains(o)).collect(Collectors.toList());
//        userIdList.removeAll(removeList);
//        resources.setUserIdList(userIdList);
//
//        containUserList.addAll(userIdList.stream().filter(o -> !containUserList.contains(o)).collect(Collectors.toList()));
        return mongoTemplate.save(resources);
    }
    private Boolean deleteWithChildren(List<TaskMongo> taskMongoList) {
        Boolean result = true;
        if (taskMongoList.size() == 0) {
            return result;
        }
        for (TaskMongo taskMongo : taskMongoList) {
            List<TaskMongo> children = mongoTemplate.find(Query.query(Criteria.where("parent").is(taskMongo)), TaskMongo.class);
            Boolean deleteFlg = deleteWithChildren(children);
            if (!deleteFlg) {
                result = false;
                continue;
            }
            Long count = mongoTemplate.count(Query.query(Criteria.where("task").is(taskMongo)), TaskUserMongo.class);
            if (count > 0) {
                result = false;
                continue;
            }
            mongoTemplate.remove(taskMongo);
        }
        return result;
    }
    @Override
    @CacheEvict(cacheNames = "ChildrenTask",allEntries = true)
    public Boolean deleteAll(Long userId,String[] ids) {
        List<TaskMongo> taskMongoList = mongoTemplate.find(Query.query(Criteria.where("id").in(Arrays.asList(ids))), TaskMongo.class);
        return deleteWithChildren(taskMongoList);
    }
    @Override
    public void download(List<TaskMongoDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TaskMongoDto task : all) {
            String projectName = task.getProjectId() != null ? projectRepository.findById(task.getProjectId()).orElseGet(Project::new).getName() : "";
            String taskStatus = task.getTaskStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.TASK_STATUS, task.getTaskStatus()).getLabel() : "";
            List<String> userNameList = new ArrayList<>();
            userRepository.findAllById(task.getUserIdList()).forEach(user -> userNameList.add(user.getNickName()));
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("项目", projectName);
            map.put("名称", task.getName());
            map.put("计划工时", task.getPlanHours());
            map.put("计划开始时间", task.getPlanStartTime());
            map.put("计划结束时间", task.getPlanEndTime());
            map.put("任务状态", taskStatus);
            map.put("消耗工时", task.getConsumedHours());
            map.put("绩效类型", task.getPerformanceType().equals("1") ? "绩效" : "非绩效");
            map.put("任务分类", String.join(",", task.getTagList()));
            map.put("任务负责人", String.join(",", userNameList));
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
//    @Override
//    public List<TaskDto> queryPartakeAll(TaskQueryCriteria criteria){
//        // 根据用户ID、项目ID查询任务ID
//        List<Long> partakeTaskIds = taskUserRepository.findTaskIdByUserIdAndProjectId(criteria.getTaskUserId(), criteria.getProjectId());
//        // 判断长度
//        if (partakeTaskIds.size() == 0) {
//            return new ArrayList<>();
//        }
//        // 项目检索条件
//        criteria.setIdInList(partakeTaskIds);
//        criteria.setTaskStatusNotEqual(Constant.TASK_STATUS_COMPLETED);
//        return taskMapper.toDto(taskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
//    }
}
Diff truncated after the above file
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskUserServiceImpl.java eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/domain/UserLevelWage.java eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/repository/UserInsuranceRepository.java eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/repository/UserLevelWageRepository.java eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/service/dto/UserLevelWageDto.java eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/service/impl/UserInsuranceServiceImpl.java eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/service/impl/UserLevelWageServiceImpl.java eladmin-master/eladmin-system/src/main/resources/config/application-dev.yml eladmin-master/eladmin-system/src/main/resources/config/application.yml eladmin-master/eladmin-system/src/test/java/me/zhengjie/AttendanceTest.java eladmin-master/eladmin-system/src/test/java/me/zhengjie/ProjectTest.java eladmin-master/eladmin-system/src/test/java/me/zhengjie/UserTest.java eladmin-master/pom.xml eladmin-web-master/src/api/attendance/attendanceGoOut.js eladmin-web-master/src/router/index.js eladmin-web-master/src/views/attendance/attendanceGoOut/index.vue eladmin-web-master/src/views/project/project/index.vue eladmin-web-master/src/views/project/projectProgress/index.vue eladmin-web-master/src/views/salary/newSalary/index.vue eladmin-web-master/src/views/system/configProportion/index.vue eladmin-web-master/src/views/task/task/index.vue eladmin-web-master/src/views/task/taskDaliy/index.vue eladmin-web-master/src/views/task/taskUser/index.vue eladmin-web-master/src/views/treatment/userLevelWage/index.vue