# HkEfficiencyParseServiceByAdp.java

    package cloud.wconnect.workperformance.service.hkefficiency.hkefficiency;

    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.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.hkefficiency.HkEfficiencyListBO;
    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.*;

    /**
     * 服务实现类：Housekeeping Efficiency ADP 报告处理
     *
     * @author zc
     * @date 2023/03/30
     */
    @Component
    @DS("work_performance")
    public class HkEfficiencyParseServiceByAdp implements IHkEfficiencyParseService {
        @Resource
        private AttendancePropertyCodeInternalService attendancePropertyCodeInternalService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

        @Value("${aws-s3.third-party.key.hk.housekeeping-efficiency}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.hk-efficiency}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTOList 资产集合
         * @param file            文件
         * @author zc
         * @date 2024/8/20
         */
        @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.checkHousekeepingEfficiency(in);
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import [Housekeeping Efficiency] ADP report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTOList      资产集合
         * @param file                 文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @param logIds               日志 id 集合
         * @param operatorId           操作人 id
         * @author zc
         * @date 2024/8/20
         */
        @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.HOUSEKEEPING_EFFICIENCY.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_HOUSEKEEPING_EFFICIENCY.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import HK Efficiency ADP report exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTOList      资产集合
         * @param in                   报告文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @return HousekeepingEfficiencyListBO 集合
         * @author zc
         * @date 2024/8/20
         */
        @Override
        public List<HkEfficiencyListBO> 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<HkEfficiencyListBO> boList = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                for (CSVRecord record : records) {
                    // 跳过第一行的标题行
                    if (record.getRecordNumber() == 1) {
                        continue;
                    }

                    PropertyDTO propertyDTO = code2PropertyDTO.get(record.get(1));
                    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(0);
                    if (StringUtils.isBlank(payDateStr)) {
                        continue;
                    }

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

                    // 获取国际化配置
                    RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                            .getInternationalization().getNumber().getCalculationRule());

                    HkEfficiencyListBO bo = new HkEfficiencyListBO();
                    bo.setProperty(propertyDTO.getAbbr());
                    bo.setTheDay(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                    bo.setDepartmentCode(record.get(2));
                    bo.setPayrollName(record.get(4));
                    String hoursStr = record.get(5).trim();
                    bo.setHours(StringUtils.isBlank(hoursStr) ?
                            null : new BigDecimal(hoursStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));

                    bo.setEarningsCode(record.get(6));
                    boList.add(bo);
                }
                return boList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse HK Efficiency ADP report error.", e);
            }
        }
    }