# DbPmsOsParseServiceByPep.java

    package cloud.wconnect.workperformance.service.database.occsummary;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    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.EventSubjectEnum;
    import cloud.wconnect.workperformance.entity.database.DbPmsHfHistory;
    import cloud.wconnect.workperformance.entity.database.DbReportImportLog;
    import cloud.wconnect.workperformance.pojo.bo.database.historyforecast.DbPmsHfBO;
    import cloud.wconnect.workperformance.pojo.dto.database.historyforecast.DbPmsHfHistoryDTO;
    import cloud.wconnect.workperformance.service.database.IDbPmsHfHistoryService;
    import cloud.wconnect.workperformance.service.database.IDbReportService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import org.apache.commons.collections4.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.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.time.LocalDate;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 解析 PEP Occupancy Summary 报告
     *
     * @author zc
     * @date 2026/3/5
     */
    @Component
    @DS("work_performance")
    public class DbPmsOsParseServiceByPep implements IDbPmsOsParseService {

        private final IDbPmsHfHistoryService hfHistoryService;
        private final IDbReportService reportService;
        private final ObjectMapper objectMapper;

        public DbPmsOsParseServiceByPep(IDbPmsHfHistoryService hfHistoryService, IDbReportService reportService,
                                        ObjectMapper objectMapper) {
            this.hfHistoryService = hfHistoryService;
            this.reportService = reportService;
            this.objectMapper = objectMapper;
        }

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

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2026/3/5
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.PEP.getDesc().equals(source);
        }

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2026/3/5
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                PepFileCheckUtils.checkOccupancySummary(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Database Occupancy Summary PEP report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2026/3/5
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, DbReportImportLog importLog, int operatorId) {
            reportService.sendReportEvent(propertyDTO, file, importLog, operatorId, s3FilePath,
                    EventSubjectEnum.OCCUPANCY_SUMMARY_LAST_2_DAY_TO_LAST_1_DAY.getSubject());
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return List<DbPmsHfBO> 集合
         * @author zc
         * @date 2026/3/5
         */
        @Override
        public List<DbPmsHfBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<DbPmsHfBO> boList = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = records.iterator();
                // 跳过第一行的标题行
                iterator.next();
                while (iterator.hasNext()) {
                    CSVRecord csvRecord = iterator.next();
                    String dateStr = CsvFileUtils.get(csvRecord, "A");
                    if (StringUtils.isEmpty(dateStr)) continue;

                    LocalDate localDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA);
                    long targetDate = Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));

                    // 判断目标日期是否在范围中
                    if (targetDate >= startDate && targetDate <= endDate) {
                        boList.add(convert2Bo(localDate, csvRecord));
                    }
                }
                // 补充计算数据
                supplementaryCalculations(propertyDTO.getId(), boList);

                return boList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Database Occupancy Summary PEP report error.", e);
            }
        }

        /**
         * 将报告中的信息转换为实体类
         *
         * @param dataLocalDate 数据日期
         * @param record        CSVRecord
         * @return DbPmsHfBO
         * @author zc
         * @date 2026/3/5
         */
        private DbPmsHfBO convert2Bo(LocalDate dataLocalDate, CSVRecord record) {
            DbPmsHfBO bo = new DbPmsHfBO();

            bo.setDStr(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

            String compRoomsStr = CsvFileUtils.getAndFormatNumber(record, "O");
            int compRooms = StringUtils.isBlank(compRoomsStr) ? 0 : Integer.parseInt(compRoomsStr);
            bo.setCom(compRooms);

            // No Show Rooms
            String noShowRoomsStr = CsvFileUtils.getAndFormatNumber(record, "S");
            bo.setNs(StringUtils.isBlank(noShowRoomsStr) ? 0 : Integer.parseInt(noShowRoomsStr));

            // House Use
            String houseUseRoomsStr = CsvFileUtils.getAndFormatNumber(record, "P");
            bo.setHu(StringUtils.isBlank(houseUseRoomsStr) ? 0 : Integer.parseInt(houseUseRoomsStr));

            // Day Use
            String dayUseRoomsStr = CsvFileUtils.getAndFormatNumber(record, "R");
            bo.setDu(StringUtils.isBlank(dayUseRoomsStr) ? 0 : Integer.parseInt(dayUseRoomsStr));

            // Non-Ded. Indiv. Rooms Sold
            bo.setNdis(0);
            // Non-Ded. Indiv. Room Revenue
            bo.setNdir(BigDecimal.ZERO);

            // Non-Ded. Group Rooms Sold
            bo.setNdgs(null);
            // Non-Ded. Group Room Revenue
            bo.setNdgr(null);

            return bo;
        }

        /**
         * 补充计算
         *
         * @param propertyId 资产ID
         * @param boList     BO集合
         * @author zc
         * @date 2026/3/5
         */
        private void supplementaryCalculations(int propertyId, List<DbPmsHfBO> boList) {
            if (CollectionUtils.isEmpty(boList)) {
                return;
            }
            List<Long> dateList = boList.stream().map(bo -> {
                LocalDate localDate = DateTimeUtils.strToLocalDate(bo.getDStr(), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                return Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
            }).toList();

            long startDate = Collections.min(dateList);
            long endDate = Collections.max(dateList);
            List<DbPmsHfHistory> hfHistoryList = hfHistoryService.listByDateRange(propertyId, startDate, endDate);
            if (CollectionUtils.isEmpty(hfHistoryList)) {
                return;
            }
            Map<Long, DbPmsHfHistory> date2HfHistory = hfHistoryList.stream()
                    .collect(Collectors.toMap(DbPmsHfHistory::getDate, Function.identity()));

            boList.forEach(bo -> {
                LocalDate localDate = DateTimeUtils.strToLocalDate(bo.getDStr(), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                long date = Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));

                DbPmsHfHistoryDTO hfHistoryDTO = new DbPmsHfHistoryDTO();
                DbPmsHfHistory hfHistory = date2HfHistory.get(date);
                if (hfHistory != null) {
                    hfHistoryDTO = JsonUtils.convertStringToObject(objectMapper, hfHistory.getData(), DbPmsHfHistoryDTO.class);
                }

                // Total Rooms(Occupancy Forecast)
                int totalRooms = (hfHistoryDTO.getIr() == null) ? 0 : hfHistoryDTO.getIr();
                // Rooms Sold(Occupancy Forecast)
                int roomsSold = (hfHistoryDTO.getRs() == null) ? 0 : hfHistoryDTO.getRs();
                // Available Rooms(Occupancy Forecast)
                int availableRooms = (hfHistoryDTO.getAvr() == null) ? 0 : hfHistoryDTO.getAvr();
                // Comp Rooms(Occupancy Summary)
                int compRooms = (bo.getCom() == null) ? 0 : bo.getCom();

                bo.setOcc(hfHistoryDTO.getOcc());
                bo.setIr(hfHistoryDTO.getIr());
                // Sell inventory rooms = Rooms Sold + Available Rooms + Comp Rooms
                bo.setSir(roomsSold + availableRooms + compRooms);
                bo.setRs(hfHistoryDTO.getRs());
                bo.setDis(hfHistoryDTO.getDis());
                bo.setDgs(hfHistoryDTO.getDgs());
                bo.setRr(hfHistoryDTO.getRr());
                bo.setDir(hfHistoryDTO.getDir());
                bo.setDgr(hfHistoryDTO.getDgr());
                bo.setArr(hfHistoryDTO.getArr());
                bo.setDep(hfHistoryDTO.getDep());
                // OOO Rooms = Total Rooms - Sold Rooms - Available Rooms - Comp Rooms
                bo.setOoo(totalRooms - roomsSold - availableRooms - compRooms);
                bo.setGu(hfHistoryDTO.getGu());
                bo.setAdr(hfHistoryDTO.getAdr());
                bo.setAvr(hfHistoryDTO.getAvr());
            });
        }
    }