BAOLH
2026-11-10 4d730af0447c686133130d0116a0fa3dd82c2dca
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/treatment/service/impl/UserLevelWageServiceImpl.java
@@ -1,193 +1,324 @@
/*
 *  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.treatment.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.treatment.domain.UserInsurance;
import me.zhengjie.modules.treatment.domain.UserLevelWage;
import me.zhengjie.modules.treatment.repository.CmnInsuranceRepository;
import me.zhengjie.modules.treatment.repository.UserInsuranceRepository;
import me.zhengjie.modules.treatment.repository.UserLevelWageRepository;
import me.zhengjie.modules.treatment.service.UserLevelWageService;
import me.zhengjie.modules.treatment.service.dto.UserLevelWageDto;
import me.zhengjie.modules.treatment.service.dto.UserLevelWageQueryCriteria;
import me.zhengjie.modules.treatment.service.mapstruct.UserLevelWageMapper;
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.util.*;
import java.util.function.Function;
/**
 * @author 姚增春
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-05-07
 **/
@Service
@RequiredArgsConstructor
public class UserLevelWageServiceImpl implements UserLevelWageService {
    private final UserLevelWageRepository userLevelWageRepository;
    private final UserLevelWageMapper userLevelWageMapper;
    private final UserRepository userRepository;
    private final UserInsuranceRepository userInsuranceRepository;
    private final CmnInsuranceRepository cmnInsuranceRepository;
    @Override
    public Map<String, Object> queryAll(UserLevelWageQueryCriteria criteria, Pageable pageable) {
        Page<UserLevelWage> page = userLevelWageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        // 将实体类转换为DTO(重写)
        Function<UserLevelWage, UserLevelWageDto> func = new Function<UserLevelWage, UserLevelWageDto>() {
            @Override
            public UserLevelWageDto apply(UserLevelWage userLevelWage) {
                // 将实体类转换成DTO
                UserLevelWageDto userLevelWageDto = userLevelWageMapper.toDto(userLevelWage);
                User user = userRepository.findById(userLevelWageDto.getUserId()).orElseGet(User::new);
                ValidationUtil.isNull(userLevelWageDto.getId(), "User", "id", userLevelWageDto.getUserId());
                userLevelWageDto.setNickName(user.getNickName());
                return userLevelWageDto;
            }
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<UserLevelWageDto> queryAll(UserLevelWageQueryCriteria criteria) {
        return userLevelWageMapper.toDto(userLevelWageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    @Override
    public UserLevelWageDto queryTargetYearMonth(UserLevelWageQueryCriteria criteria) {
        // 国际时间转中国时间
        String targetYearMonth = criteria.getTargetYearMonth();
        // 获取某年某月最后一天
        String yearMonth = targetYearMonth.substring(0,7);
        // 根据用户ID、指定年月查询
        UserLevelWage userLevelWage = userLevelWageRepository.findByUserIdAndYearMonth(criteria.getUserId(), yearMonth);
        // 判断查询结果
        if (userLevelWage == null) {
            throw new BadRequestException("没有获取到当前员工的级别信息!");
        }
        // 返回
        return userLevelWageMapper.toDto(userLevelWage);
    }
    @Override
    @Transactional
    public UserLevelWageDto findById(Long id) {
        UserLevelWage userLevelWage = userLevelWageRepository.findById(id).orElseGet(UserLevelWage::new);
        ValidationUtil.isNull(userLevelWage.getId(), "UserLevelWage", "id", id);
        return userLevelWageMapper.toDto(userLevelWage);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLevelWageDto create(UserLevelWage resources) {
        resources.setPerformanceCoefficient(calculatePerformanceCoefficient(resources));
        return userLevelWageMapper.toDto(userLevelWageRepository.save(resources));
    }
    private BigDecimal calculatePerformanceCoefficient(UserLevelWage resources) {
        BigDecimal total = resources.getBasicWage().add(resources.getRankWage()).add(resources.getPerformanceWage());
        Optional<UserInsurance> userInsuranceOpt = userInsuranceRepository.findByUserIdAndYearMonth(resources.getUserId(), resources.getYearMonth());
        if (userInsuranceOpt.isPresent()) {
            UserInsurance userInsurance = userInsuranceOpt.get();
            total = total.add(userInsurance.getAccumulationFund().multiply(BigDecimal.valueOf(userInsurance.getAccumulationFundCompany() / 100)))
                    .add(userInsurance.getBirthInsurance().multiply(BigDecimal.valueOf(userInsurance.getBirthInsuranceCompany() / 100)))
                    .add(userInsurance.getEmploymentInsurance().multiply(BigDecimal.valueOf(userInsurance.getEmploymentInsuranceCompany() / 100)))
                    .add(userInsurance.getMedicalInsurance().multiply(BigDecimal.valueOf(userInsurance.getMedicalInsuranceCompany() / 100)))
                    .add(userInsurance.getRetirementInsurance().multiply(BigDecimal.valueOf(userInsurance.getRetirementInsuranceCompany() / 100)))
                    .add(userInsurance.getUnemploymentInsurance().multiply(BigDecimal.valueOf(userInsurance.getUnemploymentInsuranceCompany() / 100)));
        }
        return total.divide(BigDecimal.valueOf(11250), 2, RoundingMode.UP);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upload(List<UserLevelWage> resources) {
        for (UserLevelWage userLevelWage : resources) {
            UserLevelWage userLevelWageDB = userLevelWageRepository.findByUserIdAndYearMonth(userLevelWage.getUserId(), userLevelWage.getYearMonth());
            if (userLevelWageDB == null) {
                userLevelWageRepository.save(userLevelWage);
            } else {
                userLevelWageDB.copy(userLevelWage);
                userLevelWageRepository.save(userLevelWageDB);
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserLevelWage resources) {
        UserLevelWage userLevelWage = userLevelWageRepository.findById(resources.getId()).orElseGet(UserLevelWage::new);
        ValidationUtil.isNull(userLevelWage.getId(), "UserLevelWage", "id", resources.getId());
        userLevelWage.copy(resources);
        userLevelWage.setPerformanceCoefficient(calculatePerformanceCoefficient(userLevelWage));
        userLevelWageRepository.save(userLevelWage);
    }
    @Override
    public void flushAll(Long[] ids) {
        for (Long id : ids) {
            UserLevelWage userLevelWage = userLevelWageRepository.findById(id).orElseGet(UserLevelWage::new);
            userLevelWage.setPerformanceCoefficient(calculatePerformanceCoefficient(userLevelWage));
            userLevelWageRepository.save(userLevelWage);
        }
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            userLevelWageRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<UserLevelWageDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (UserLevelWageDto userLevelWage : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户ID", userLevelWage.getUserId());
            map.put("年月", userLevelWage.getYearMonth());
            map.put("级别", userLevelWage.getLevel());
            map.put("等级", userLevelWage.getRank());
            map.put("级别基本工资", userLevelWage.getBasicWage());
            map.put("级别等级工资", userLevelWage.getRankWage());
            map.put("绩效工资", userLevelWage.getPerformanceWage());
            map.put("团队工资比例", userLevelWage.getPerformanceCoefficient());
            map.put("锁定状态", userLevelWage.getLocked());
            map.put("备注", userLevelWage.getRemarks());
            map.put("创建者", userLevelWage.getCreateBy());
            map.put("创建时间", userLevelWage.getCreateTime());
            map.put("更新者", userLevelWage.getUpdateBy());
            map.put("更新时间", userLevelWage.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.treatment.service.impl;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.attendance.domain.AttendanceBusinessTravel;
import me.zhengjie.modules.attendance.domain.AttendanceOvertime;
import me.zhengjie.modules.attendance.repository.AttendanceBusinessTravelRepository;
import me.zhengjie.modules.attendance.repository.AttendanceOvertimeRepository;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.system.domain.SysConfigProportion;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.SysConfigProportionRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.treatment.domain.UserInsurance;
import me.zhengjie.modules.treatment.domain.UserLevelWage;
import me.zhengjie.modules.treatment.repository.CmnInsuranceRepository;
import me.zhengjie.modules.treatment.repository.UserInsuranceRepository;
import me.zhengjie.modules.treatment.repository.UserLevelWageRepository;
import me.zhengjie.modules.treatment.service.UserLevelWageService;
import me.zhengjie.modules.treatment.service.dto.UserLevelWageDto;
import me.zhengjie.modules.treatment.service.dto.UserLevelWageQueryCriteria;
import me.zhengjie.modules.treatment.service.mapstruct.UserLevelWageMapper;
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 姚增春
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-05-07
 **/
@Service
@RequiredArgsConstructor
public class UserLevelWageServiceImpl implements UserLevelWageService {
    private final UserLevelWageRepository userLevelWageRepository;
    private final UserLevelWageMapper userLevelWageMapper;
    private final UserRepository userRepository;
    private final UserInsuranceRepository userInsuranceRepository;
    private final CmnInsuranceRepository cmnInsuranceRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final SysConfigProportionRepository sysConfigProportionRepository;
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    @Override
    public Map<String, Object> queryAll(UserLevelWageQueryCriteria criteria, Pageable pageable) {
        Page<UserLevelWage> page = userLevelWageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        // 将实体类转换为DTO(重写)
        Function<UserLevelWage, UserLevelWageDto> func = userLevelWage -> {
            // 将实体类转换成DTO
            UserLevelWageDto userLevelWageDto = userLevelWageMapper.toDto(userLevelWage);
            User user = userRepository.findById(userLevelWageDto.getUserId()).orElseGet(User::new);
            ValidationUtil.isNull(userLevelWageDto.getId(), "User", "id", userLevelWageDto.getUserId());
            userLevelWageDto.setNickName(user.getNickName());
            return userLevelWageDto;
        };
        return PageUtil.toPage(page.map(func));
    }
    @Override
    public List<UserLevelWageDto> queryAll(UserLevelWageQueryCriteria criteria) {
        return userLevelWageMapper.toDto(userLevelWageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    @Override
    public UserLevelWageDto queryTargetYearMonth(UserLevelWageQueryCriteria criteria) throws ParseException {
        String targetYearMonth = criteria.getTargetYearMonth();
        String yearMonth = targetYearMonth.substring(0,7);
        // 查询用户
        User user = userRepository.findById(criteria.getUserId()).orElseGet(User::new);
        Calendar calendar = Calendar.getInstance();
        // 获取员工的添加时间
        calendar.setTime(user.getCreateTime());
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        if (dayOfMonth <= daysInMonth / 2) {
            calendar.add(Calendar.MONTH, user.getInternshipTime() == null ? 3 : user.getInternshipTime());
        } else {
            calendar.add(Calendar.MONTH, user.getInternshipTime() == null ? 4 : user.getInternshipTime() + 1);
        }
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        // 获取转正时间
        String confirmationTime = new Timestamp(calendar.getTimeInMillis()).toString().substring(0, 7);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Date date1 = format.parse(yearMonth);
        Date date2 = format.parse(confirmationTime);
        UserLevelWage userLevelWage = null;
        // 如果传递进来的日期在转正日期之前
//        if(date1.before(date2)) {
//            // 查询没转正且年月最大的数据
//            userLevelWage = userLevelWageRepository.findByUserIdAndNoWorker(criteria.getUserId(), confirmationTime);
//        } else {
//            // 查询第二条转正且日期最大的数据
//            userLevelWage = userLevelWageRepository.findByUserIdAndYesWorker(criteria.getUserId(), confirmationTime);
//        }
        // 获取小于等于当前月份且日期最大的数据。
        userLevelWage = userLevelWageRepository.findByUserCurrentLevelWage(criteria.getUserId(), yearMonth);
//        UserLevelWage userLevelWage = userLevelWageRepository.findbyUserIdAndDate(criteria.getUserId(), yearMonth);
        // 判断查询结果
        if (userLevelWage == null) {
            throw new RuntimeException("当月没有获取到该员工【" + user.getNickName() + "】的级别工资!");
        }
        // 返回
        return userLevelWageMapper.toDto(userLevelWage);
    }
    @Override
    public Double queryOverTimeAllowance(UserLevelWageQueryCriteria criteria) throws ParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(criteria.getTargetYearMonth(), formatter);
        // 获取月初日期
        LocalDateTime firstDayOfMonth = dateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        // 获取下月初日期
        LocalDateTime lastDayOfMonth = firstDayOfMonth.plusMonths(1).minusDays(1).withHour(23).withMinute(59).withSecond(59).withNano(0);
        // 查询指定员工的加班补助金额工资
        Double overTimeSalary = attendanceOvertimeRepository.findByUserIdAndYearMonth(criteria.getUserId(), DateUtil.parseAttStartTime(firstDayOfMonth), DateUtil.parseAttEndTime(lastDayOfMonth));
        // 查询配置表
        SysConfigProportion sysConfigProportion = sysConfigProportionRepository.findByTitle("加班补助金额");
        // 出差补助金
        Double travelSubsidy = (overTimeSalary == null ? 0.0 : overTimeSalary) * sysConfigProportion.getProportion();
        return travelSubsidy;
    }
    @Override
    public Double queryTravelAllowance(UserLevelWageQueryCriteria criteria, JSONObject jsonObject) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(criteria.getTargetYearMonth(), formatter);
        // 获取月初日期
        LocalDateTime firstDayOfMonth = dateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        // 获取月末最后一天日期
        LocalDateTime lastDayOfMonth = firstDayOfMonth.plusMonths(1).minusDays(1).withHour(23).withMinute(59).withSecond(59).withNano(0);
        // 查询出差表的记录
        List<AttendanceBusinessTravel> attendanceBusinessTravelList = attendanceBusinessTravelRepository.findByUserAndSEDate(criteria.getUserId(), firstDayOfMonth, lastDayOfMonth);
        // TODO:因一天可填多条出差记录,每条最小的时长是0.5天,导致可能会有当天总时长超出1天的情况。(每天出差类型只会有一种,不考虑多种的情况)
        List<AttendanceBusinessTravel> calcAttendanceBusinessTravelList = attendanceBusinessTravelList.stream().collect(Collectors.groupingBy(
                (AttendanceBusinessTravel businessTravel) -> businessTravel.getTravelStartTime().toLocalDateTime().toLocalDate().toString(),
                Collectors.reducing(null, (AttendanceBusinessTravel prev, AttendanceBusinessTravel cur) -> {
                    if (prev == null) {
                        return cur;
                    }
                    // 计算工时
                    prev.setTravelDuration(new BigDecimal(prev.getTravelDuration()).add(new BigDecimal(cur.getTravelDuration())).min(BigDecimal.ONE).doubleValue());
                    return prev;
                })
        )).values().stream().collect(Collectors.toList());
        Map<String, Double> attendanceBusinessTravelMap = calcAttendanceBusinessTravelList.stream().collect(Collectors.groupingBy(AttendanceBusinessTravel::getCategory, Collectors.summingDouble(AttendanceBusinessTravel::getTravelDuration)));
        // 出差时长
        Double travelHours = attendanceBusinessTravelMap.entrySet().stream().filter(entry -> entry.getKey().equals(Constant.ATTENDANCE_BUSINESS_TRAVEL_CATEGORY_TRAVEL))
                .map(Map.Entry::getValue).collect(Collectors.summingDouble(Double::doubleValue));
        // 客户现场时长
        Double customerSiteHours = attendanceBusinessTravelMap.entrySet().stream().filter(entry -> entry.getKey().equals(Constant.ATTENDANCE_BUSINESS_TRAVEL_CATEGORY_SAME_PLACE))
                .map(Map.Entry::getValue).collect(Collectors.summingDouble(Double::doubleValue));
        // 合计
        BigDecimal travelMoney = new BigDecimal(sysConfigProportionRepository.findByTitle("出差补助金额").getProportion());
        BigDecimal customerSiteMoney = new BigDecimal(30);
        BigDecimal travelSubsidy = BigDecimal.valueOf(travelHours).multiply(travelMoney).add(BigDecimal.valueOf(customerSiteHours).multiply(customerSiteMoney));
        // 记录计算公式
        if (jsonObject != null) {
            jsonObject.put("travelWage", String.format("【(出差时长H * 出差补助) + (客户现场时长H * 客户现场补助)】:(%.2f * %.2f) + (%.2f * %.2f)", BigDecimal.valueOf(travelHours), travelMoney, BigDecimal.valueOf(customerSiteHours), customerSiteMoney));
        }
//        // 出差补助金
//        attendanceBusinessTravelMap.forEach((key, value) -> {
//            if (key.equals(Constant.ATTENDANCE_BUSINESS_TRAVEL_CATEGORY_TRAVEL)) {
//                // 出差补助金
//                SysConfigProportion sysConfigProportion = sysConfigProportionRepository.findByTitle("出差补助金额");
//                travelSubsidy = travelSubsidy.add(BigDecimal.valueOf(value * sysConfigProportion.getProportion()));
//            } else if (key.equals(Constant.ATTENDANCE_BUSINESS_TRAVEL_CATEGORY_SAME_PLACE)) {
//                // 客户现场补助金
////                SysConfigProportion sysConfigProportion = sysConfigProportionRepository.findByTitle("客户现场补助金额");
//                travelSubsidy = travelSubsidy.add(BigDecimal.valueOf(value * 30)); // 按30元/天计算 TODO 待调整
//            }
//        });
        return travelSubsidy.doubleValue();
    }
    @Override
    @Transactional
    public UserLevelWageDto findById(Long id) {
        UserLevelWage userLevelWage = userLevelWageRepository.findById(id).orElseGet(UserLevelWage::new);
        ValidationUtil.isNull(userLevelWage.getId(), "UserLevelWage", "id", id);
        return userLevelWageMapper.toDto(userLevelWage);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLevelWageDto create(UserLevelWage resources) {
        // 根据日期查询个人级别工资表
        UserLevelWage userLevelWage = userLevelWageRepository.findByUserAndDate(resources.getUserId(), resources.getYearMonth());
        if (userLevelWage != null) {
            throw new BadRequestException("级别日期重复!");
        }
        resources.setPerformanceCoefficient(calculatePerformanceCoefficient(resources));
        return userLevelWageMapper.toDto(userLevelWageRepository.save(resources));
    }
    private BigDecimal calculatePerformanceCoefficient(UserLevelWage resources) {
        BigDecimal total = resources.getBasicWage().add(resources.getRankWage()).add(resources.getPerformanceWage());
        Optional<UserInsurance> userInsuranceOpt = userInsuranceRepository.findByUserIdAndYearMonth(resources.getUserId(), resources.getYearMonth());
        if (userInsuranceOpt.isPresent()) {
            UserInsurance userInsurance = userInsuranceOpt.get();
            total = total.add(userInsurance.getAccumulationFund().multiply(BigDecimal.valueOf(userInsurance.getAccumulationFundCompany() / 100)))
                    .add(userInsurance.getBirthInsurance().multiply(BigDecimal.valueOf(userInsurance.getBirthInsuranceCompany() / 100)))
                    .add(userInsurance.getEmploymentInsurance().multiply(BigDecimal.valueOf(userInsurance.getEmploymentInsuranceCompany() / 100)))
                    .add(userInsurance.getMedicalInsurance().multiply(BigDecimal.valueOf(userInsurance.getMedicalInsuranceCompany() / 100)))
                    .add(userInsurance.getRetirementInsurance().multiply(BigDecimal.valueOf(userInsurance.getRetirementInsuranceCompany() / 100)))
                    .add(userInsurance.getUnemploymentInsurance().multiply(BigDecimal.valueOf(userInsurance.getUnemploymentInsuranceCompany() / 100)));
        }
        return total.divide(BigDecimal.valueOf(11250), 2, RoundingMode.UP);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upload(List<UserLevelWage> resources) {
        for (UserLevelWage userLevelWage : resources) {
            UserLevelWage userLevelWageDB = userLevelWageRepository.findByUserIdAndYearMonth(userLevelWage.getUserId(), userLevelWage.getYearMonth());
            if (userLevelWageDB == null) {
                userLevelWageRepository.save(userLevelWage);
            } else {
                userLevelWageDB.copy(userLevelWage);
                userLevelWageRepository.save(userLevelWageDB);
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserLevelWage resources) {
        UserLevelWage userLevelWage = userLevelWageRepository.findById(resources.getId()).orElseGet(UserLevelWage::new);
        ValidationUtil.isNull(userLevelWage.getId(), "UserLevelWage", "id", resources.getId());
//        // 根据日期查询个人级别工资表
//        UserLevelWage userLevelWage1 = userLevelWageRepository.findByUserAndDate(resources.getUserId(), resources.getYearMonth());
//        if (userLevelWage1 != null) {
//            throw new BadRequestException("级别日期重复!");
//        }
        userLevelWage.copy(resources);
        userLevelWage.setPerformanceCoefficient(calculatePerformanceCoefficient(userLevelWage));
        userLevelWageRepository.save(userLevelWage);
    }
    @Override
    public void flushAll(Long[] ids) {
        for (Long id : ids) {
            UserLevelWage userLevelWage = userLevelWageRepository.findById(id).orElseGet(UserLevelWage::new);
            userLevelWage.setPerformanceCoefficient(calculatePerformanceCoefficient(userLevelWage));
            userLevelWageRepository.save(userLevelWage);
        }
    }
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            userLevelWageRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<UserLevelWageDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (UserLevelWageDto userLevelWage : all) {
            // 将实体类转换成DTO
            User user = userRepository.findById(userLevelWage.getUserId()).orElseGet(User::new);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("员工姓名", user.getNickName());
            map.put("所属公司", user.getCompany().getLabel());
            map.put("年月", userLevelWage.getYearMonth());
            map.put("总工资", userLevelWage.getBasicWage().add(userLevelWage.getRankWage()).add(userLevelWage.getPerformanceWage()));
            map.put("基本工资", userLevelWage.getBasicWage());
            map.put("调整工资", userLevelWage.getRankWage());
            map.put("岗位工资", userLevelWage.getPerformanceWage());
            map.put("在职状态", user.getEnabled() ? "在职" : "离职");
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}