# MorOvertimeParseServiceByOther.java

    package cloud.wconnect.workperformance.service.mor.overtime;

    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.mor.overtime.OvertimeDailyBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.mor.IMorOvertimeDailyService;
    import cloud.wconnect.workperformance.service.mor.IOvertimeImportLogService;
    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.collections.CollectionUtils;
    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.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeParseException;
    import java.util.*;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 服务实现类：Other 加班时间报告处理
     *
     * @author zc
     * @date 2024/08/19
     */
    @Slf4j
    @Component
    @DS("work_performance")
    public class MorOvertimeParseServiceByOther implements IMorOvertimeParseService {
        @Resource
        private IMorOvertimeDailyService overtimeDailyService;
        @Resource
        private IOvertimeImportLogService importLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

        @Value("${aws-s3.third-party.key.monthly-ot-report.overtime-details.overtime}")
        private String s3FilePath;

        @Value("${file-max-size.import-report.overtime}")
        private long fileMaxSize;

        /**
         * 判断是否支持
         *
         * @param source 数据源
         * @return boolean
         * @author zc
         * @date 2024/8/16
         */
        @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;
                    }

                    // Last Name
                    String lastName = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isBlank(lastName)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Last Name cannot be blank");
                    } else {
                        if (lastName.length() > 30) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1), 30),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Last Name cannot be more than 30 characters");
                        }
                    }
                    // First Name
                    String firstName = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isBlank(firstName)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The First Name cannot be blank");
                    } else {
                        if (firstName.length() > 30) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2), 30),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The First Name cannot be more than 30 characters");
                        }
                    }
                    // Position ID
                    String positionIdStr = CellUtils.convertCellStr(row.getCell(3));
                    if (StringUtils.isBlank(positionIdStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3)),
                                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(3), 20),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Position ID cannot be more than 20 characters");
                        }
                    }
                    // Work Department Code
                    String departmentCode = CellUtils.convertCellStr(row.getCell(4));
                    if (StringUtils.isBlank(departmentCode)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4)),
                                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(4), 20),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Department Code cannot be more than 20 characters");
                        }
                    }
                    // Work Department Desc
                    String departmentDesc = CellUtils.convertCellStr(row.getCell(5));
                    if (StringUtils.isBlank(departmentDesc)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Department Code cannot be blank");
                    } else {
                        if (departmentDesc.length() > 60) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5), 60),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Department Desc cannot be more than 60 characters");
                        }
                    }
                    // Time In
                    String timeInStr = CellUtils.convertCellStr(row.getCell(6));
                    if (StringUtils.isNotBlank(timeInStr)) {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM, Locale.ENGLISH);
                            LocalDateTime.parse(timeInStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6), BaseConstant.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The timeIn format is incorrect, timeIn = " + timeInStr);
                        }
                    }
                    // Time Out
                    String timeOutStr = CellUtils.convertCellStr(row.getCell(7));
                    if (StringUtils.isNotBlank(timeOutStr)) {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM, Locale.ENGLISH);
                            LocalDateTime.parse(timeOutStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(7), BaseConstant.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The timeOut format is incorrect, timeOut = " + timeOutStr);
                        }
                    }
                    // Pay Rate
                    String payRateStr = CellUtils.convertCellStr(row.getCell(8));
                    if (StringUtils.isNotBlank(payRateStr)) {
                        BigDecimal payRate;
                        try {
                            payRate = new BigDecimal(payRateStr);
                            if (payRate.compareTo(BigDecimal.ZERO) < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(8)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Pay Rate cannot be less than 0, Pay Rate = " + payRateStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(8)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Pay Rate format is incorrect, Pay Rate = " + payRateStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = payRate.abs().toBigInteger().toString().length();
                        if (intLength > 8) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(8), 8),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Pay Rate exceeds the limit, Pay Rate = " + payRateStr);
                        }
                    }
                    // Hours
                    String hoursStr = CellUtils.convertCellStr(row.getCell(9));
                    if (StringUtils.isNotBlank(hoursStr)) {
                        BigDecimal hours;
                        try {
                            hours = new BigDecimal(hoursStr);
                            if (hours.compareTo(BigDecimal.ZERO) < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(9)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Hours cannot be less than 0, Hours = " + hoursStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(9)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Hours format is incorrect, Hours = " + hoursStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = hours.abs().toBigInteger().toString().length();
                        if (intLength > 4) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(9), 4),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Hours exceeds the limit, Hours = " + hoursStr);
                        }
                    }
                    // In Date
                    String inDateStr = CellUtils.convertCellStr(row.getCell(10));
                    if (StringUtils.isNotBlank(inDateStr)) {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(inDateStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(10), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The inDate format is incorrect, inDate = " + inDateStr);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check Mor Overtime Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTOList      资产集合
         * @param file                 文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @param logIds               日志 id 集合
         * @param operatorId           操作人 id
         * @author zc
         * @date 2025/3/15
         */
        @Override
        public void handleData(List<PropertyDTO> propertyDTOList, MultipartFile file, Map<Integer, List<Long>> propertyId2DateRange, 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.OVERTIME_IMPORT_RECORD, file, s3Key);

                // 解析报告
                List<OvertimeDailyBO> overtimeListBODaily = parse(propertyDTOList, in, propertyId2DateRange);
                // 处理报告数据
                overtimeDailyService.handleOvertimeWorkHour(propertyDTOList, overtimeListBODaily, operatorId, propertyId2DateRange);
            } catch (IOException e) {
                handleResult = false;
                log.error("Handle Mor Overtime Other Work Hour report send event exception.", e);
            } finally {
                importLogService.updateBatch(logIds, handleResult, operatorId, s3Key);
            }
        }

        /**
         * 读取报告文件，转换生成加班时间信息集合
         *
         * @param propertyDTOList      资产集合
         * @param in                   文件流
         * @param propertyId2DateRange 数据日期范围
         * @return OvertimeListBO 集合
         * @author zc
         * @date 2024/8/17
         */
        @Override
        public List<OvertimeDailyBO> parse(List<PropertyDTO> propertyDTOList, InputStream in, Map<Integer, List<Long>> propertyId2DateRange) 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<OvertimeDailyBO> overtimes = 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;
                    }
                    // 数据日期范围为空的不处理
                    List<Long> dateRangeList = propertyId2DateRange.getOrDefault(propertyDTO.getId(), Collections.emptyList());
                    if (CollectionUtils.isEmpty(dateRangeList)) {
                        continue;
                    }
                    // 跳过没有日期的数据
                    String theDateStr = CellUtils.convertCellStr(row.getCell(10));
                    if (StringUtils.isBlank(theDateStr)) {
                        continue;
                    }
                    // 只处理指定日期范围的数据
                    long theDate = Long.parseLong(DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(theDateStr,
                            BaseConstant.DATE_FORMAT_YYYY_MM_DD), BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (theDate < dateRangeList.get(0) || theDate > dateRangeList.get(1)) {
                        continue;
                    }
                    // 跳过没有工作部门 Code 的数据
                    String departmentCode = CellUtils.convertCellStr(row.getCell(4));
                    if (StringUtils.isBlank(departmentCode)) {
                        continue;
                    }
                    // 跳过没有加班时薪的数据
                    String payRateStr = CellUtils.convertCellStr(row.getCell(8));
                    if (StringUtils.isBlank(payRateStr)) {
                        continue;
                    }
                    overtimes.add(convert2Overtime(propertyDTO, row));
                }
                return overtimes;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Mor Overtime Other Work Hour report error.", e);
            }
        }

        /**
         * 将文件数据转成加班信息
         *
         * @param propertyDTO 资产
         * @param row         Row
         * @return OvertimeListBO
         * @author zc
         * @date 2023/4/3
         */
        private OvertimeDailyBO convert2Overtime(PropertyDTO propertyDTO, Row row) {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());

            OvertimeDailyBO overtime = new OvertimeDailyBO();
            overtime.setProperty(propertyDTO.getAbbr());
            overtime.setLastName(CellUtils.convertCellStr(row.getCell(1)));
            overtime.setFirstName(CellUtils.convertCellStr(row.getCell(2)));
            overtime.setPositionId(CellUtils.convertCellStr(row.getCell(3)));
            overtime.setWorkDepartmentCode(CellUtils.convertCellStr(row.getCell(4)));
            overtime.setWorkDepartmentDesc(CellUtils.convertCellStr(row.getCell(5)));
            overtime.setTimeInStr(CellUtils.convertCellStr(row.getCell(6)));
            overtime.setTimeOutStr(CellUtils.convertCellStr(row.getCell(7)));

            String payRateStr = CellUtils.convertCellStr(row.getCell(8));
            BigDecimal payRate = StringUtils.isBlank(payRateStr) ? BigDecimal.ZERO
                    : new BigDecimal(payRateStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            overtime.setPayRate(payRate);

            String hoursStr = CellUtils.convertCellStr(row.getCell(9));
            BigDecimal hours = StringUtils.isBlank(hoursStr) ? BigDecimal.ZERO
                    : new BigDecimal(hoursStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            overtime.setHours(hours);

            overtime.setAmount(payRate.multiply(hours).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            overtime.setTheDateStr(CellUtils.convertCellStr(row.getCell(10)));
            return overtime;
        }
    }