# ScheduleHourParseServiceByAdp.java

    package cloud.wconnect.workperformance.service.sva.actualschedulehour.schedulehour;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.service.AttendancePropertyCodeInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.sns.http.processor.Sender;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.pojo.bo.sva.actualschedulehour.SvaScheduleHoursBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Qualifier;
    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.io.InputStreamReader;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.util.*;

    /**
     * 服务实现类：ADP 考勤平台 Schedule Hour 报告处理
     *
     * @author yyt
     * @date 2025/03/23
     */
    @Component
    @DS("work_performance")
    public class ScheduleHourParseServiceByAdp implements IScheduleHourParseService {
        @Resource
        private AttendancePropertyCodeInternalService attendancePropertyCodeInternalService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

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

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTOList 资产集合
         * @param file            文件
         * @author zc
         * @date 2025/4/21
         */
        @Override
        public void checkFile(List<PropertyDTO> propertyDTOList, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream in = file.getInputStream()) {
                AdpFileCheckUtils.checkScheduledWorkDepartment(in);
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import [Scheduled Work Department] ADP report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTOList      资产集合
         * @param file                 文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @param logIds               日志 id 集合
         * @param operatorId           操作人 id
         * @author yyt
         * @date 2025/3/26
         */
        @Override
        public void handleData(List<PropertyDTO> propertyDTOList, MultipartFile file,
                               Map<Integer, List<Long>> propertyId2DateRange, List<Long> logIds, int operatorId) {
            try {
                String tenantSymbol = propertyDTOList.get(0).getTenantSymbol();
                List<String> propertyAbbrList = propertyDTOList.stream().map(PropertyDTO::getAbbr).toList();

                String key = tenantSymbol + "/" + StringUtils.join(propertyAbbrList, "_") + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());
                // 上传文件到 S3 服务器，用于监听器监听并处理文件
                amazonS3Service.uploadFile(file, key);

                List<Long> dateRangeList = propertyId2DateRange.values().stream().toList().get(0);

                // 封装事件体
                HashMap<String, Object> parameter = Maps.newHashMap();
                parameter.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), tenantSymbol);
                parameter.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), propertyAbbrList);
                parameter.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.SVA_AV_HOURS.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.ADP.getDesc());
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);
                parameter.put(EventBodyParamEnum.ID.getDesc(), logIds);
                parameter.put(EventBodyParamEnum.START_DATE.getDesc(), dateRangeList.get(0));
                parameter.put(EventBodyParamEnum.END_DATE.getDesc(), dateRangeList.get(1));

                // 手动发送事件通知
                snsSender.publish(EventSubjectEnum.ATTENDANCE_AV_SCHEDULE_HOURS.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Sva Schedule Hour ADP report exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTOList      资产集合
         * @param in                   报告文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @return Schedule Hour
         * @author yyt
         * @date 2025/3/26
         */
        @Override
        public List<SvaScheduleHoursBO> parse(List<PropertyDTO> propertyDTOList, InputStream in,
                                              Map<Integer, List<Long>> propertyId2DateRange) throws ParseReportException {
            Map<String, PropertyDTO> code2PropertyDTO = attendancePropertyCodeInternalService.getCode2PropertyDTO(propertyDTOList);
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<SvaScheduleHoursBO> avHoursListBOList = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                for (CSVRecord record : records) {
                    // 跳过第一行的标题
                    if (record.getRecordNumber() == 1) {
                        continue;
                    }

                    PropertyDTO propertyDTO = code2PropertyDTO.get(record.get(0));
                    if (Objects.isNull(propertyDTO)) {
                        continue;
                    }
                    // 数据日期范围配置为空的不处理
                    List<Long> dateRangeList = propertyId2DateRange.getOrDefault(propertyDTO.getId(), Collections.emptyList());
                    if (CollectionUtils.isEmpty(dateRangeList)) {
                        continue;
                    }

                    // Pay Date 为空的不保存
                    String payDateStr = record.get(11);
                    if (StringUtils.isBlank(payDateStr)) {
                        continue;
                    }

                    // 只提取指定日期范围的数据
                    LocalDate payDateLocalDate = DateTimeUtils.strToLocalDate(payDateStr, BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH);
                    long targetDate = Long.parseLong(DateTimeUtils.localDateToStr(payDateLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (targetDate < dateRangeList.get(0) || targetDate > dateRangeList.get(1)) {
                        continue;
                    }

                    // Home Department Code & Work Department Code 都为空的不保存
                    String homeDepartmentCode = record.get(5);
                    String workDepartmentCode = record.get(9);
                    if (StringUtils.isBlank(homeDepartmentCode) && StringUtils.isBlank(workDepartmentCode)) {
                        continue;
                    }

                    avHoursListBOList.add(convert2AvHourBo(record, propertyDTO));
                }
                return avHoursListBOList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Sva Schedule Hour ADP report error.", e);
            }
        }

        /**
         * 将报告中的信息转换为实体类
         *
         * @param record   信息记录
         * @param property 资产
         * @return SvaScheduleHoursBO 实例
         * @author yyt
         * @date 2025/3/26
         */
        private SvaScheduleHoursBO convert2AvHourBo(CSVRecord record, PropertyDTO property) {
            // 获取国际化配置
            InternationalizationNumberDTO numberDTO = property.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(numberDTO.getCalculationRule());

            SvaScheduleHoursBO scheduleHoursBO = new SvaScheduleHoursBO();
            scheduleHoursBO.setProperty(property.getAbbr());
            // Position ID
            String positionId = record.get(3);
            scheduleHoursBO.setPositionId(positionId);
            // Pay Code
            scheduleHoursBO.setPayCode(record.get(7));
            // Regular Pay Rate Description
            String regularPayRateDescription = record.get(6);
            BigDecimal payRate = null;
            // 当 Regular Pay Rate Description 为 Hourly 时，才设置 payRate
            if ("Hourly".equalsIgnoreCase(regularPayRateDescription)) {
                // Pay Rate
                String payRateStr = record.get(4);
                payRate = StringUtils.isBlank(payRateStr) ?
                        BigDecimal.ZERO : new BigDecimal(payRateStr.split(" ")[1]).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            }
            scheduleHoursBO.setPayRate(payRate);
            // Department Code、Department Desc
            String workDepartmentCode = record.get(9);
            if (StringUtils.isNotBlank(workDepartmentCode)) {
                scheduleHoursBO.setDepartmentCode(workDepartmentCode);
                String workDepartmentDesc = record.get(10);
                scheduleHoursBO.setDepartmentDesc(workDepartmentDesc);
            } else {
                String homeDepartmentCode = record.get(5);
                scheduleHoursBO.setDepartmentCode(homeDepartmentCode);
                String homeDepartmentDesc = record.get(8);
                scheduleHoursBO.setDepartmentDesc(homeDepartmentDesc);
            }
            // Pay Date
            String payDateStr = record.get(11);
            LocalDate payDateLocalDate = DateTimeUtils.strToLocalDate(payDateStr, BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH);
            scheduleHoursBO.setPayDateStr(DateTimeUtils.localDateToStr(payDateLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
            // Hours
            String hoursStr = record.get(12);
            BigDecimal hours = StringUtils.isBlank(hoursStr) ?
                    BigDecimal.ZERO : new BigDecimal(hoursStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            scheduleHoursBO.setHours(hours);
            // Payroll
            if (Objects.nonNull(payRate)) {
                scheduleHoursBO.setPayroll(payRate.multiply(hours).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            }

            return scheduleHoursBO;
        }
    }