# OccupancySummaryYesterdayParseImplByPep.java

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

    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.util.CsvFileUtils;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    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.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.time.LocalDate;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * Occupancy Summary Yesterday 报告解析
     *
     * @author yyt
     * @date 2026/3/4
     */
    @RequiredArgsConstructor
    @Service
    @Slf4j
    @DS("rate_shop")
    public class OccupancySummaryYesterdayParseImplByPep implements IOccupancySummaryYesterdayParse {

        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)) {
                List<HistoryAndForecastDailySummaryDTO> resultList = Lists.newArrayList();

                String timezone = propertyDTO.getTimezone();

                //获取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());

                    //comp rooms
                    String compRoomsStr = CsvFileUtils.getAndFormatNumber(csvRecord, "O");
                    Integer compRooms = StringUtils.isEmpty(compRoomsStr) ? null : Integer.parseInt(compRoomsStr);
                    historyAndForecastDailySummaryDTO.setCompRooms(compRooms);

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

        /**
         * 保存报告数据
         *
         * @param propertyDTO        资产
         * @param dailySummaryBOList 报告数据
         * @param operatorId   操作人 id
         * @param logId        导入记录 id
         * @author yyt
         * @date 2026/3/3
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void saveReportData(PropertyDTO propertyDTO, List<HistoryAndForecastDailySummaryDTO> dailySummaryBOList, Integer operatorId, Long logId) {
            List<DailySummaryBO> dailySummaryBOS = handleHFYesterdayAndNinetyCommonService.filterAndTransform(propertyDTO, operatorId, logId, dailySummaryBOList);
            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)));

                for (DailySummaryBO dailySummaryBO : dailySummaryBOS) {
                    RevenueDailySummary existRevenueDailySummary = existRevenueDailySummaryByDate.getOrDefault(dailySummaryBO.getTheDate(), Collections.emptyMap())
                            .get(dailySummaryBO.getTheHour());
                    if (Objects.nonNull(existRevenueDailySummary)) {
                        dailySummaryBO.setRoomsAvailable(existRevenueDailySummary.getRoomsAvailable());
                        dailySummaryBO.setTotalRoomsSold(existRevenueDailySummary.getTotalRoomsSold());
                        dailySummaryBO.setTotalOcc(existRevenueDailySummary.getTotalOcc());
                        dailySummaryBO.setOooRooms(existRevenueDailySummary.getOooRooms());
                        dailySummaryBO.setOcc(existRevenueDailySummary.getOcc());
                        dailySummaryBO.setTotalRooms(existRevenueDailySummary.getTotalRooms());
                    } else {
                        dailySummaryBO.setRoomsAvailable(BaseConstant.ZERO);
                        dailySummaryBO.setTotalRoomsSold(BaseConstant.ZERO);
                        dailySummaryBO.setTotalOcc(BaseConstant.ZERO);
                        dailySummaryBO.setOooRooms(BaseConstant.ZERO);
                    }

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

                revenueDailySummaryService.saveOrUpdate(propertyDTO, dailySummaryBOS);
            }
        }

    }