# DailySummaryHistoryAndForecastParseImplByPep.java

    package cloud.wconnect.rateshop.service.revenue.historyandforecast;

    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.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.RoomsConfigDTO;
    import cloud.wconnect.commonlib.pojo.dto.calculateoperation.CalculateOOORoomsDTO;
    import cloud.wconnect.commonlib.pojo.dto.calculateoperation.CalculateTotalRoomsSoldDTO;
    import cloud.wconnect.commonlib.pojo.dto.calculateoperation.CalculateTransientRoomsDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.service.CalculatePropertyOperationService;
    import cloud.wconnect.commonlib.service.RoomsConfigInternalService;
    import cloud.wconnect.commonlib.util.CsvFileUtils;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueAdrConfig;
    import cloud.wconnect.rateshop.entity.revenue.RevenueDailySummary;
    import cloud.wconnect.rateshop.pojo.bo.revenue.DailySummaryBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.HistoryAndForecastDailySummaryDTO;
    import cloud.wconnect.rateshop.service.revenue.IHandleHistoryAndForecastReportCommonService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueAdrConfigService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    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.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    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.*;
    import java.util.stream.Collectors;

    /**
     * History And Forecast PEP 来源报告解析
     *
     * @author yyt
     * @date 2026/3/4
     */
    @RequiredArgsConstructor
    @Service
    @Slf4j
    @DS("rate_shop")
    public class DailySummaryHistoryAndForecastParseImplByPep implements IDailySummaryHistoryAndForecastParse {

        private final IRevenueAdrConfigService revenueAdrConfigService;
        private final IRevenueDailySummaryService revenueDailySummaryService;
        private final IHandleHistoryAndForecastReportCommonService handleHFYesterdayAndNinetyCommonService;
        private final RoomsConfigInternalService roomsConfigInternalService;
        private final CalculatePropertyOperationService calculatePropertyOperationService;

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

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产DTO
         * @param startDate   数据日期，开始时间
         * @param endDate     数据日期，结束时间
         * @return java.util.List<cloud.wconnect.rateshop.pojo.dto.revenue.HistoryAndForecastDailySummaryDTO>
         * @author yyt
         * @date 2026/3/4
         */
        @Override
        public List<HistoryAndForecastDailySummaryDTO> parse(InputStream in, PropertyDTO propertyDTO, Long startDate, Long endDate) throws ParseReportException {
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                // 获取房间数配置
                RoomsConfigDTO roomsConfig = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId());
                Integer rooms = roomsConfig.getRooms();

                String timezone = propertyDTO.getTimezone();
                InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());
                BigDecimal oneHundred = BigDecimal.valueOf(100L);

                List<HistoryAndForecastDailySummaryDTO> resultList = Lists.newArrayList();

                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = iterable.iterator();

                //跳过第一行标题行
                iterator.next();

                while (iterator.hasNext()) {
                    CSVRecord csvRecord = iterator.next();
                    // 空行
                    if (csvRecord.size() == BaseConstant.ZERO) continue;

                    //日期
                    String dateStr = CsvFileUtils.get(csvRecord, "A");
                    if(StringUtils.isEmpty(dateStr)) continue;
                    LocalDate localDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA);
                    long dataDate = DateTimeUtils.localDateToLong(localDate, timezone);
                    if (dataDate < startDate || dataDate > endDate) continue;

                    HistoryAndForecastDailySummaryDTO historyAndForecastDailySummaryDTO = new HistoryAndForecastDailySummaryDTO();
                    historyAndForecastDailySummaryDTO.setTheDate(dataDate);

                    //小时数
                    int hour = DateTimeUtils.dateTimeNow(propertyDTO.getTimezone()).getHour();
                    historyAndForecastDailySummaryDTO.setTheHour(hour);
                    //同步时间
                    historyAndForecastDailySummaryDTO.setSyncTime(DateTimeUtils.nowTimestamp());

                    //已售房间数
                    String roomsSoldStr = CsvFileUtils.getAndFormatNumber(csvRecord, "D");
                    Integer roomsSold = StringUtils.isEmpty(roomsSoldStr) ? BaseConstant.ZERO : Integer.parseInt(roomsSoldStr);
                    historyAndForecastDailySummaryDTO.setTotalOcc(roomsSold);

                    //总房间数
                    String totalRoomsStr = CsvFileUtils.getAndFormatNumber(csvRecord, "C");
                    Integer totalRooms = StringUtils.isEmpty(totalRoomsStr) ? null : Integer.parseInt(totalRoomsStr);
                    historyAndForecastDailySummaryDTO.setTotalRooms(totalRooms);

                    //可用房间数
                    String availableRoomsStr = CsvFileUtils.getAndFormatNumber(csvRecord, "E");
                    Integer availableRooms = StringUtils.isEmpty(availableRoomsStr) ? BaseConstant.ZERO : Integer.parseInt(availableRoomsStr);
                    historyAndForecastDailySummaryDTO.setRoomsAvailable(availableRooms);

                    historyAndForecastDailySummaryDTO.setTotalRoomsSold(BaseConstant.ZERO);

                    // 入住率
                    // 设置 occ，根据 occ 的配置规则判断：1.使用配置的房间数计算 occ，2.直接使用文件中的 occ
                    if (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE) {
                        if (StringUtils.isNotEmpty(roomsSoldStr)) {
                            //  Occ. % = total occ rooms / 总房间数
                            BigDecimal occPercent = new BigDecimal(roomsSoldStr).multiply(oneHundred)
                                    .divide(BigDecimal.valueOf(rooms), BaseConstant.DATA_PRECISION, roundingMode);
                            historyAndForecastDailySummaryDTO.setOcc(occPercent);
                        }
                    } else {
                        String occStr = CsvFileUtils.getAndFormatNumber(csvRecord, "M");
                        if (StringUtils.isNotEmpty(occStr)) {
                            historyAndForecastDailySummaryDTO.setOcc(new BigDecimal(occStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
                        }
                    }

                    resultList.add(historyAndForecastDailySummaryDTO);
                }
                return resultList;
            } catch (IOException e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check pep [History And Forecast] report error", e);
            }
        }

        /**
         * 保存报告数据
         *
         * @param propertyDTO      资产
         * @param dailySummaryDTOS 报告数据
         * @param operatorId       操作人 id
         * @param logId            导入记录 id
         * @author yyt
         * @date 2026/3/3
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void saveReportData(PropertyDTO propertyDTO, List<HistoryAndForecastDailySummaryDTO> dailySummaryDTOS, Integer operatorId, Long logId) {
            List<DailySummaryBO> dailySummaryBOS = handleHFYesterdayAndNinetyCommonService.filterAndTransform(propertyDTO, operatorId, logId, dailySummaryDTOS);
            if (CollectionUtils.isNotEmpty(dailySummaryBOS)) {
                // 查询已存在的数据，然后重新计算相关数据
                List<Long> dates = dailySummaryBOS.stream().map(DailySummaryBO::getTheDate).sorted().toList();
                Long startDate = dates.get(0);
                Long endDate = dates.get(dates.size() - 1);
                Map<Long, Map<Integer, RevenueDailySummary>> existRevenueDailySummaryByDate = revenueDailySummaryService.listDailySummary(propertyDTO.getId(), startDate, endDate)
                        .stream().collect(Collectors.groupingBy(RevenueDailySummary::getTheDate, Collectors.toMap(RevenueDailySummary::getTheHour, v -> v)));

                //资产配置的规则
                RevenueAdrConfig revenueAdrConfig = revenueAdrConfigService.get(propertyDTO.getId());
                boolean checkTransientDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckTransientDeduct();

                for (DailySummaryBO dailySummaryBO : dailySummaryBOS) {

                    RevenueDailySummary existRevenueDailySummary = existRevenueDailySummaryByDate.getOrDefault(dailySummaryBO.getTheDate(), Collections.emptyMap())
                            .getOrDefault(dailySummaryBO.getTheHour(), new RevenueDailySummary());

                    // 计算故障房
                    dailySummaryBO.setCompRooms(existRevenueDailySummary.getCompRooms());
                    Integer oooRooms = calculatePropertyOperationService.calculateOooRooms(new CalculateOOORoomsDTO(dailySummaryBO.getTotalRooms(), dailySummaryBO.getTotalOcc(),
                            dailySummaryBO.getRoomsAvailable(), dailySummaryBO.getCompRooms()));
                    dailySummaryBO.setOooRooms(Objects.isNull(oooRooms) ? BaseConstant.ZERO : oooRooms);

                    // 计算散客
                    dailySummaryBO.setGroupRooms(existRevenueDailySummary.getGroupRooms());
                    dailySummaryBO.setTransientRooms(checkTransientDeduct ?
                            calculatePropertyOperationService.calculateTransientRooms(new CalculateTransientRoomsDTO(dailySummaryBO.getTotalOcc(), dailySummaryBO.getGroupRooms())) : null);
                    // 计算总售出房间数
                    Integer totalRoomsSold = calculatePropertyOperationService.calculateTotalRoomsSold(new CalculateTotalRoomsSoldDTO(dailySummaryBO.getTransientRooms(), dailySummaryBO.getGroupRooms()));
                    dailySummaryBO.setTotalRoomsSold(Objects.isNull(totalRoomsSold) ? BaseConstant.ZERO : totalRoomsSold);
                }

                revenueDailySummaryService.saveOrUpdate(propertyDTO, dailySummaryBOS);
            }
        }

    }