# 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.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.util.CsvFileUtils;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    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 Shiji来源报告解析
     *
     * @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;

        /**
         * 支持的报告来源
         *
         * @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)) {
                String timezone = propertyDTO.getTimezone();
                InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

                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, "F");
                    Integer availableRooms = StringUtils.isEmpty(availableRoomsStr) ? BaseConstant.ZERO : Integer.parseInt(availableRoomsStr);
                    historyAndForecastDailySummaryDTO.setRoomsAvailable(availableRooms);

                    historyAndForecastDailySummaryDTO.setTotalRoomsSold(BaseConstant.ZERO);

                    //入住率
                    if (StringUtils.isNotEmpty(roomsSoldStr) && Objects.nonNull(totalRooms) && totalRooms > BaseConstant.ZERO) {
                        BigDecimal occPercent = new BigDecimal(roomsSoldStr).divide(BigDecimal.valueOf(totalRooms), BaseConstant.DATA_PRECISION, roundingMode);
                        historyAndForecastDailySummaryDTO.setOcc(occPercent);
                    }

                    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());

                    // 计算故障房 Total Rooms - Sold Rooms - Available Rooms - Comp Rooms
                    dailySummaryBO.setCompRooms(existRevenueDailySummary.getCompRooms());
                    dailySummaryBO.setOooRooms(revenueDailySummaryService.calculateOooRooms(dailySummaryBO));

                    // 计算散客
                    dailySummaryBO.setGroupRooms(existRevenueDailySummary.getGroupRooms());
                    dailySummaryBO.setTransientRooms(checkTransientDeduct ? revenueDailySummaryService.calculateTransientRooms(dailySummaryBO) : null);
                    // 计算总售出房间数
                    dailySummaryBO.setTotalRoomsSold(revenueDailySummaryService.calculateTotalRoomsSold(dailySummaryBO));
                }

                revenueDailySummaryService.saveOrUpdate(propertyDTO, dailySummaryBOS);
            }
        }

    }