BAOLH
2026-11-10 c5dfc09145e4e10f99dbf388a4a1433b5c2973e5
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/UserServiceImpl.java
@@ -1,468 +1,1350 @@
/*
 *  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.modules.security.service.OnlineUserService;
import me.zhengjie.modules.security.service.UserCacheManager;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException;
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.SysUserLevelWageMapper;
import me.zhengjie.modules.system.service.mapstruct.UserLoginMapper;
import me.zhengjie.modules.system.service.mapstruct.UserMapper;
import me.zhengjie.utils.*;
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.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.sql.Timestamp;
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 UserMapper userMapper;
    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;
    @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<UserDto> queryAll(UserQueryCriteria criteria) {
        List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        return userMapper.toDto(users);
    }
    @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());
        }
        userRepository.save(resources);
        // 判断用户级别变更
        checkUserLevel(resources.getId(), null, resources.getLevelId());
    }
    @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.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();
        userRepository.save(user);
        // 判断用户级别变更
        checkUserLevel(user.getId(), 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());
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            // 清理缓存
            UserDto user = findById(id);
            delCaches(user.getId(), user.getUsername());
        }
        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 (UserDto 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() : "";
            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("状态", 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) {
        // 判断新旧用户级别ID是否相等
        if (oldLevelId == null) {
            // 创建用户级别工资
            createSysUserLevelWage(userId, newLevelId);
            // 创建用户级别保险
            createSysUserLevelInsurance(userId, newLevelId);
            // 创建用户级别其他
            createSysUserLevelOther(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);
            }
            // 创建用户级别其他
            createSysUserLevelOther(userId, newLevelId);
        } else {
        }
    }
    /**
     * 创建用户级别工资
     * @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);
    }
    /**
     * 创建用户级别其他
     * @param userId
     * @param levelId
     */
    private void createSysUserLevelOther(Long userId, Long levelId) {
        // 级别
        SysLevel sysLevel = sysLevelRepository.findById(levelId).orElseGet(SysLevel::new);
        // 用户级别其他
        SysUserLevelOther sysUserLevelOther = new SysUserLevelOther();
        sysUserLevelOther.setUserId(userId);
        sysUserLevelOther.setLevelId(levelId);
        sysUserLevelOther.setStartDate(new Timestamp(new Date().getTime()));
        sysUserLevelOther.setPersonalPerformanceProportion(sysLevel.getPersonalPerformanceProportion());
        sysUserLevelOther.setAnnualLeaveDays(sysLevel.getAnnualLeaveDays());
        // 保存
        sysUserLevelOtherRepository.save(sysUserLevelOther);
    }
}
/*
 *  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.domain.Calculate;
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.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveQueryCriteria;
import me.zhengjie.modules.attendance.service.dto.AttendanceQueryCriteria;
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.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
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 SysUserLevelWageRepository sysUserLevelWageRepository;
    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 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;
    private final AttendanceService attendanceService;
    @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查询用户级别
                CmnLevel cmnLevel = cmnLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(CmnLevel::new);
                // 用户
                userDto.get(i).setLevelName(cmnLevel.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查询用户级别
                CmnLevel cmnLevel = cmnLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(CmnLevel::new);
                // 用户
                userDto.get(i).setLevelName(cmnLevel.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 (Constant.HIGH_LEVEL_LIST.contains(Long.valueOf(role.getLevel()))) {
            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查询用户级别
                CmnLevel cmnLevel = cmnLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(CmnLevel::new);
                // 用户
                usersDto.get(i).setLevelName(cmnLevel.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查询用户级别
                CmnLevel cmnLevel = cmnLevelRepository.findById(sysUserLevelWage.getLevelId()).orElseGet(CmnLevel::new);
                // 用户
                usersDto.get(i).setLevelName(cmnLevel.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);
        // 判断用户级别变更(新)
        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());
        }
        // 如果用户被登录禁用,则清除用户登录信息
        if (!resources.getLoginEnabled()) {
            onlineUserService.kickOutForUsername(resources.getUsername());
        }
        // 填充数据
        user.setUsername(resources.getUsername());
        user.setEmail(resources.getEmail());
        user.setEnabled(resources.getEnabled());
        user.setLoginEnabled(resources.getLoginEnabled());
        user.setRoles(resources.getRoles());
        user.setDept(resources.getDept());
        user.setJobs(resources.getJobs());
        user.setJobSecond(resources.getJobSecond());
        user.setCompanys(resources.getCompanys());
        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.setWeComId(resources.getWeComId());
        user.setSysRostering(resources.getSysRostering());
        // 处理数据
        redisUtils.del("user::AllUser");
        userRepository.save(user);
        // 清除缓存
        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() == null ? "" : 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() == null ? "" : 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) && !attendance.getDateType().equals(Constant.DATE_TYPE_WEEKEND) && !attendance.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
                numDay++;
            }
        }
        returnData.put("onDutyDays", numDay);
        // 剩余年假
        Double yearTimes = attendanceLeaveService.getYearTimeLength(userId, sdfDate.substring(0, 4));
        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<>();
        // 调休的工作日
        List<String> workingHoliday = 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)
                    || holidayConfiguration.getDateType().equals(Constant.DATE_TYPE_WEEKEND)) {
                holiday.add(sdf.format(holidayConfiguration.getHolidayDate()));
            } else if (holidayConfiguration.getDateType().equals(Constant.DATE_TYPE_WEEKDAY)) {
                workingHoliday.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) || workingHoliday.contains(date)) {
                    shouldWordDays += 1;
                }
            }
        }
        int num = shouldWordDays * 8;
        // 月初到今天应工作时长
        returnData.put("Time", num);
        User user = userRepository.getById(userId);
        List<Calculate> resultParts = new ArrayList<>();
        List<Calculate> calculateList = new ArrayList<>();
        List<Calculate> breakParts = new ArrayList<>();
        for (Attendance attendance : attendanceRecordList) {
            // 上班打卡时间不为空并且打卡状态不为出差外出的考勤记录
            if (ObjectUtils.isNotEmpty(attendance.getActualWorkStartTime()) &&
                    !attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_GOOUT) &&
                    !attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_BUSINESS) &&
                    attendance.getActualWorkStartTime().toLocalDateTime().compareTo(attendance.getRosteringLunchStartTime().toLocalDateTime()) <= 0
            ) {
                calculateList.add(new Calculate(attendance.getActualWorkStartTime().toLocalDateTime(), attendance.getRosteringLunchStartTime().toLocalDateTime()));
            }
            // 下班打卡时间不为空并且打卡状态不为出差外出的考勤记录
            if (ObjectUtils.isNotEmpty(attendance.getActualWorkEndTime()) &&
                    !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_GOOUT) &&
                    !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_BUSINESS) &&
                    attendance.getActualWorkEndTime().toLocalDateTime().compareTo(attendance.getRosteringLunchEndTime().toLocalDateTime()) > 0
            ) {
                calculateList.add(new Calculate(attendance.getRosteringLunchEndTime().toLocalDateTime(), attendance.getActualWorkEndTime().toLocalDateTime()));
            }
            // 休息时间管理(午休和下班后30分钟)
            breakParts.add(new Calculate(attendance.getRosteringLunchStartTime().toLocalDateTime(), attendance.getRosteringLunchEndTime().toLocalDateTime()));
            breakParts.add(new Calculate(attendance.getRosteringWorkEndTime().toLocalDateTime(), attendance.getRosteringWorkEndTime().toLocalDateTime().plusMinutes(30L)));
        }
        calculateList.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 -> {
            List<Calculate> currentParts = new ArrayList<>();
            currentParts.add(calculate);
            // 去除休息时间:午休、下班后30分钟
            for (Calculate breakPart : breakParts) {
                List<Calculate> tempParts = new ArrayList<>();
                for (Calculate current : currentParts) {
                    if ((current.getStart().isBefore(breakPart.getStart()) && current.getEnd().isAfter(breakPart.getStart()))
                            || (current.getStart().isBefore(breakPart.getEnd()) && current.getEnd().isAfter(breakPart.getEnd()))) {
                        Calculate calculate1 = new Calculate(current.getStart(), breakPart.getStart());
                        Calculate calculate2 = new Calculate(breakPart.getEnd(), current.getEnd());
                        if (calculate1.getStart().isBefore(calculate1.getEnd())) {
                            tempParts.add(calculate1);
                        }
                        if (calculate2.getStart().isBefore(calculate2.getEnd())) {
                            tempParts.add(calculate2);
                        }
                    } else {
                        tempParts.add(current);
                    }
                }
                currentParts = tempParts;
            }
            // 将处理完所有休息区间后的结果添加到最终结果
            resultParts.addAll(currentParts);
        });
        BigDecimal resultTime = resultParts.stream()
                .map(calculate -> ChronoUnit.SECONDS.between(calculate.getStart(), calculate.getEnd()))
                .reduce(new BigDecimal(0),
                        (total, current) -> total.add(BigDecimal.valueOf(current)),
                        BigDecimal::add)
                .divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP
                );
        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, DateUtil.parseAttStartTime(Timestamp.valueOf(startTime).toLocalDateTime()), DateUtil.parseAttEndTime(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(sdfLastDate.substring(0, 10) + " 23:59:59").toLocalDateTime());
        for (AttendanceBusinessTravel attendanceBusinessTravel : attendanceBusinessTravelList) {
            bussTimes = bussTimes + attendanceBusinessTravel.getTravelDuration();
        }
        // 实际工作时长
        returnData.put("Times",  (resultTime.max(BigDecimal.ZERO).doubleValue()) + 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;
        }).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);
        // 加班时长
        AttendanceQueryCriteria attendanceQueryCriteria = new AttendanceQueryCriteria();
        attendanceQueryCriteria.setUserId(userId);
        attendanceQueryCriteria.setTargetYearMonth(sdfDate.substring(0, 7) + "-01");
        attendanceQueryCriteria.setDateType(Constant.DATE_TYPE_WEEKDAY);
        Double attendanceOverTimeHours = attendanceService.queryAttendanceOverTimeHours(attendanceQueryCriteria, null);
        returnData.put("attendanceOverTimeHours", attendanceOverTimeHours);
        Double attendanceHolidayOverTimeHours = attendanceService.queryAttendanceOverTimeHours(attendanceQueryCriteria, Constant.DATE_TYPE_HOLIDAYS);
        Double attendanceLegalHolidayOverTimeHours = attendanceService.queryAttendanceOverTimeHours(attendanceQueryCriteria, Constant.DATE_TYPE_LEGAL_HOLIDAYS);
        Double attendanceWeekendHolidayOverTimeHours = attendanceService.queryAttendanceOverTimeHours(attendanceQueryCriteria, Constant.DATE_TYPE_WEEKEND);
        returnData.put("attendanceHolidayOverTimeHours", attendanceHolidayOverTimeHours + attendanceLegalHolidayOverTimeHours + attendanceWeekendHolidayOverTimeHours);
        // 请假时长
        AttendanceLeaveQueryCriteria attendanceLeaveQueryCriteria = new AttendanceLeaveQueryCriteria();
        attendanceLeaveQueryCriteria.setUserId(userId);
        attendanceLeaveQueryCriteria.setLeaveStartTimeLike(sdfDate.substring(0, 7) + "%");
        attendanceLeaveQueryCriteria.setApprovalStatus(Constant.APPROVAL_STATUS_PASSED);
        List<AttendanceLeaveDto> attendanceLeaveDtos = attendanceLeaveService.queryAll(attendanceLeaveQueryCriteria);
        double leaveTimeHours = attendanceLeaveDtos.stream().mapToDouble(a -> {
            if (a.getLeaveDurationUnit().equals(Constant.LEAVE_TIME_TYPE_HOUR)) {
                return a.getLeaveDuration();
            } else if (a.getLeaveDurationUnit().equals(Constant.LEAVE_TIME_TYPE_DAY)) {
                return a.getLeaveDuration() * 8;
            }
            return 0.0;
        }).sum();
        returnData.put("leaveTimeHours", BigDecimal.valueOf(leaveTimeHours).setScale(2, RoundingMode.HALF_UP).doubleValue());
        LocalDateTime targetDateTime = yearMonth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().withDayOfMonth(1).atStartOfDay();
        // 换休剩余时长
        Double overTime = attendanceLeaveService.getOverTimeLength(userId, targetDateTime);
        returnData.put("overTime", overTime);
        // 待结算(下月即将结算)换休时长
        Double overTimeClose = attendanceLeaveService.getOverTimeCloseLength(userId, targetDateTime);
        returnData.put("overTimeClose", overTimeClose);
        // 本月结算换休时长
        Double overTimeCurrentClose = attendanceLeaveService.getOverTimeCurrentCloseLength(userId, targetDateTime);
        returnData.put("overTimeCurrentClose", overTimeCurrentClose);
        // 出差天数
        returnData.put("businessDays", attendanceBusinessTravelList.stream().filter(attendanceBusinessTravel -> attendanceBusinessTravel.getCategory().equals(Constant.ATTENDANCE_BUSINESS_TRAVEL_CATEGORY_TRAVEL) && attendanceBusinessTravel.getApprovalStatus().equals(Constant.BUSSINESS_APPROVE_STATUS_AGREE)).collect(Collectors.toList()).stream().map(AttendanceBusinessTravel::getTravelDuration).reduce(0.0, Double::sum));
        returnData.put("localDays", attendanceBusinessTravelList.stream().filter(attendanceBusinessTravel -> attendanceBusinessTravel.getCategory().equals(Constant.ATTENDANCE_BUSINESS_TRAVEL_CATEGORY_SAME_PLACE) && attendanceBusinessTravel.getApprovalStatus().equals(Constant.BUSSINESS_APPROVE_STATUS_AGREE)).collect(Collectors.toList()).stream().map(AttendanceBusinessTravel::getTravelDuration).reduce(0.0, Double::sum));
        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 ? cmnLevelRepository.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 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) {
        LocalDate nowLocalDate = LocalDate.now();
        SysUserLevelOther sysUserLevelOther = new SysUserLevelOther();
        sysUserLevelOther.setUserId(resources.getId());
        sysUserLevelOther.setLevelId(cmnLevel.getId());
        sysUserLevelOther.setYearMonth(nowLocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM")));
        sysUserLevelOther.setStartDate(Timestamp.valueOf(nowLocalDate.atStartOfDay()));
        sysUserLevelOther.setPersonalPerformanceProportion(Double.valueOf(0));
        sysUserLevelOther.setAnnualLeaveDays(5.0);
        sysUserLevelOtherRepository.save(sysUserLevelOther);
    }
    /**
     * 获取转正的月初时间
     *
     * @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;
    }
}