# SvaEmployeeParseServiceByOther.java

    package cloud.wconnect.workperformance.service.sva.employees.employee;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.workperformance.cons.S3BucketFunctionCons;
    import cloud.wconnect.workperformance.pojo.bo.sva.employees.EmployeesListBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.sva.employees.IAttendanceEmpImportLogService;
    import cloud.wconnect.workperformance.service.sva.employees.IAttendanceEmployeeService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.IOException;
    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeParseException;
    import java.util.List;
    import java.util.Locale;
    import java.util.Map;
    import java.util.Objects;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 服务实现类：Other 员工报告处理
     *
     * @author zc
     * @date 2024/08/19
     */
    @Slf4j
    @Component
    @DS("work_performance")
    public class SvaEmployeeParseServiceByOther implements ISvaEmployeeParseService {
        @Resource
        private IAttendanceEmployeeService employeeService;
        @Resource
        private IAttendanceEmpImportLogService employeeImportLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

        @Value("${aws-s3.third-party.key.schedule-vs-actual.employees}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.sva}")
        private long fileMaxSize;

        /**
         * 判断是否支持
         *
         * @param source 数据源
         * @return boolean
         * @author zc
         * @date 2024/7/29
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OTHER.getDesc().equals(source);
        }

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTOList 资产集合
         * @param file            文件
         * @author zc
         * @date 2024/8/16
         */
        @Override
        public void checkFile(List<PropertyDTO> propertyDTOList, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xls", "xlsx"));
            Map<String, PropertyDTO> name2PropertyDTO = propertyDTOList.stream()
                    .collect(Collectors.toMap(item -> item.getName().toLowerCase(), Function.identity()));
            try (InputStream in = file.getInputStream(); Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                // 获取最大行数
                int lastRowNum = sheet.getLastRowNum();
                // 若只包含标题，直接返回
                if (lastRowNum < 1) {
                    return;
                }

                // 提取标题
                List<String> titleList = Lists.newArrayList();
                Row titleRow = sheet.getRow(0);
                for (int i = 0; i <= 9; i++) {
                    titleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);

                    // Property Name
                    String propertyNameStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(propertyNameStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Property Name cannot be blank");
                    }
                    // 若资产不存在，则跳过校验
                    PropertyDTO propertyDTO = name2PropertyDTO.get(propertyNameStr.toLowerCase());
                    if (Objects.isNull(propertyDTO)) {
                        continue;
                    }

                    // Position ID
                    String positionIdStr = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isBlank(positionIdStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Position ID cannot be blank");
                    } else {
                        if (positionIdStr.length() > 20) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1), 20),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Position ID cannot be more than 20 characters");
                        }
                    }
                    // Payroll Name
                    String payrollNameStr = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isBlank(payrollNameStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Payroll Name cannot be blank");
                    } else {
                        if (payrollNameStr.length() > 60) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2), 60),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Payroll Name cannot be more than 60 characters");
                        }
                    }
                    // Department Code
                    String departmentCode = CellUtils.convertCellStr(row.getCell(3));
                    if (StringUtils.isBlank(departmentCode)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Department Code cannot be blank");
                    } else {
                        if (departmentCode.length() > 20) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3), 20),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Department Code cannot be more than 20 characters");
                        }
                    }
                    // Department Description
                    String departmentDescription = CellUtils.convertCellStr(row.getCell(4));
                    if (StringUtils.isBlank(departmentDescription)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Department Description cannot be blank");
                    } else {
                        if (departmentDescription.length() > 60) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4), 60),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Department Description cannot be more than 60 characters");
                        }
                    }
                    // Hire Date
                    String hireDateStr = CellUtils.convertCellStr(row.getCell(5));
                    if (StringUtils.isBlank(hireDateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Hire Date cannot be blank");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(hireDateStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Hire Date format is incorrect, Hire Date = " + hireDateStr);
                        }
                    }
                    // Hire/Rehire Date
                    String rehireDateStr = CellUtils.convertCellStr(row.getCell(6));
                    if (StringUtils.isBlank(rehireDateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Hire/Rehire Date cannot be blank");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(rehireDateStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Hire/Rehire Date format is incorrect, Hire/Rehire Date = " + rehireDateStr);
                        }
                    }
                    // Pay Class
                    String payClassStr = CellUtils.convertCellStr(row.getCell(7));
                    if (StringUtils.isBlank(payClassStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(7)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Pay Class cannot be blank");
                    } else {
                        if (payClassStr.length() > 30) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(7), 30),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Pay Class cannot be more than 30 characters");
                        }
                    }
                    // Worker Category Code
                    String workerCategoryCodeStr = CellUtils.convertCellStr(row.getCell(8));
                    if (StringUtils.isNotBlank(workerCategoryCodeStr)) {
                        if (workerCategoryCodeStr.length() > 5) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(8), 5),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Worker Category Code cannot be more than 5 characters");
                        }
                    }
                    // Hourly Rates
                    String hourlyRatesStr = CellUtils.convertCellStr(row.getCell(9));
                    if (StringUtils.isNotBlank(hourlyRatesStr)) {
                        BigDecimal hourlyRates;
                        try {
                            hourlyRates = new BigDecimal(hourlyRatesStr);
                            if (hourlyRates.compareTo(BigDecimal.ZERO) < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(9)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Hourly Rates cannot be less than 0, Hourly Rates = " + hourlyRatesStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(9)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Hourly Rates format is incorrect, Hourly Rates = " + hourlyRatesStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = hourlyRates.abs().toBigInteger().toString().length();
                        if (intLength > 8) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(9), 8),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Hourly Rates exceeds the limit, Hourly Rates = " + hourlyRates);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check Sva Employees Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTOList 资产集合
         * @param file            文件
         * @param logIds          日志 id 集合
         * @param operatorId      操作人 id
         * @author zc
         * @date 2024/8/16
         */
        @Override
        public void handleData(List<PropertyDTO> propertyDTOList, MultipartFile file, List<Long> logIds, int operatorId) {
            // 处理是否成功
            boolean handleResult = true;
            String tenantSymbol = propertyDTOList.get(0).getTenantSymbol();
            List<String> propertyAbbrList = propertyDTOList.stream().map(PropertyDTO::getAbbr).toList();
            String s3Key = tenantSymbol + "/" + StringUtils.join(propertyAbbrList, "_") + "/" + s3FilePath
                    + UploadUtils.getRandomFileName(file.getOriginalFilename());

            try (InputStream in = file.getInputStream()) {
                // 上传报告文件到 S3 服务器，用于导入日志下载报告
                amazonS3Service.uploadFile(S3BucketFunctionCons.SVA_EMPLOYEES_IMPORT_RECORD, file, s3Key);

                // 解析报告
                List<EmployeesListBO> employeesListBOList = parse(propertyDTOList, in);
                // 处理报告数据
                employeeService.handleEmployees(propertyDTOList, employeesListBOList, operatorId);
            } catch (Exception e) {
                handleResult = false;
                log.error("Handle import Sva Employees Other report error.", e);
            } finally {
                employeeImportLogService.updateBatch(logIds, handleResult, operatorId, s3Key);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTOList 资产集合
         * @param in              文件流
         * @return EmployeesListBO 集合
         * @author zc
         * @date 2024/7/29
         */
        @Override
        public List<EmployeesListBO> parse(List<PropertyDTO> propertyDTOList, InputStream in) throws ParseReportException {
            Map<String, PropertyDTO> name2PropertyDTO = propertyDTOList.stream()
                    .collect(Collectors.toMap(item -> item.getName().toLowerCase(), Function.identity()));
            try (Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);

                List<EmployeesListBO> employeesListBOList = Lists.newArrayList();
                // 跳过第 0 行标题
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);

                    String propertyNameStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(propertyNameStr)) {
                        continue;
                    }
                    PropertyDTO propertyDTO = name2PropertyDTO.get(propertyNameStr.toLowerCase());
                    if (Objects.isNull(propertyDTO)) {
                        continue;
                    }

                    // Department Code 为空的不保存
                    String departmentCode = CellUtils.convertCellStr(row.getCell(3));
                    if (StringUtils.isBlank(departmentCode)) {
                        continue;
                    }

                    // 将报告中的员工信息转换为实体类
                    EmployeesListBO employeesListBO = convert2AttendanceEmployee(propertyDTO, row);

                    employeesListBOList.add(employeesListBO);
                }
                return employeesListBOList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Sva Employees Other report error.", e);
            }
        }

        /**
         * 报告数据转换为 BO
         *
         * @param propertyDTO 资产
         * @param row         Row
         * @return EmployeesListBO
         * @author zc
         * @date 2024/7/29
         */
        private static EmployeesListBO convert2AttendanceEmployee(PropertyDTO propertyDTO, Row row) {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());

            EmployeesListBO employeesListBO = new EmployeesListBO();
            employeesListBO.setProperty(propertyDTO.getAbbr());

            // Position ID
            String positionId = CellUtils.convertCellStr(row.getCell(1));
            employeesListBO.setPositionId(positionId);

            // Payroll Name
            String payrollName = CellUtils.convertCellStr(row.getCell(2));
            employeesListBO.setEmpName(payrollName);

            // Department Code
            String departmentCode = CellUtils.convertCellStr(row.getCell(3));
            employeesListBO.setDepartmentCode(departmentCode);

            // Department Desc.
            String departmentDesc = CellUtils.convertCellStr(row.getCell(4));
            employeesListBO.setDepartmentDesc(departmentDesc);

            // Hire Date
            String hireDateStr = CellUtils.convertCellStr(row.getCell(5));
            employeesListBO.setHireDay(hireDateStr);

            // Rehire Date
            String reHireDateStr = CellUtils.convertCellStr(row.getCell(6));
            employeesListBO.setRehireDay(reHireDateStr);

            // Pay Class
            String payClass = CellUtils.convertCellStr(row.getCell(7));
            employeesListBO.setPayClass(payClass);

            // Worker Category Code
            String workerCategoryCode = CellUtils.convertCellStr(row.getCell(8));
            employeesListBO.setWorkerCategoryCode(workerCategoryCode);

            // Hourly Rate
            String hourlyRate = CellUtils.convertCellStr(row.getCell(9));
            employeesListBO.setHourlyRate(StringUtils.isBlank(hourlyRate) ?
                    null : new BigDecimal(hourlyRate).setScale(BaseConstant.DATA_PRECISION, roundingMode));

            return employeesListBO;
        }
    }