# WMRevenueHistoryAndForecastParseServiceByPEP.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.calculateoperation.CalculateOOORoomsDTO;
    import cloud.wconnect.commonlib.pojo.dto.calculateoperation.CalculateTransientRoomsDTO;
    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.pojo.bo.weeklymonthlyrevenue.WMRevenueHistoryAndForecastBO;
    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.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.stereotype.Component;

    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.Iterator;
    import java.util.List;
    import java.util.Objects;

    /**
     * 解析 PEP 系统的 History And Forecast/Service 报告
     *
     * @author yyt
     * @date 2026/03/12
     */
    @RequiredArgsConstructor
    @Slf4j
    @Component
    @DS("rate_shop")
    public class WMRevenueHistoryAndForecastParseServiceByPEP implements IWMRevenueHistoryAndForecastParseService {

        private final RoomsConfigInternalService roomsConfigInternalService;
        private final CalculatePropertyOperationService calculatePropertyOperationService;

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

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return WMRevenueHistoryAndForecastBO 集合
         * @author yyt
         * @date 2026/3/12
         */
        @Override
        public List<WMRevenueHistoryAndForecastBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            int totalRooms = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId()).getRooms();
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<WMRevenueHistoryAndForecastBO> historyAndForecastBOList = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = records.iterator();
                // 跳过第一行的标题行
                iterator.next();
                while (iterator.hasNext()) {
                    CSVRecord record = iterator.next();
                    String dateStr = CsvFileUtils.get(record, "A");
                    if(StringUtils.isEmpty(dateStr)) continue;
                    LocalDate dataLocalDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA);
                    long targetDate = Long.parseLong(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (targetDate < startDate || targetDate > endDate) {
                        continue;
                    }

                    historyAndForecastBOList.add(convert2Bo(dataLocalDate, record, totalRooms, roundingMode));
                }
                return historyAndForecastBOList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Weekly Monthly Revenue History and forecast PEP report error.", e);
            }
        }

        /**
         * 将报告中的信息转换为实体类
         *
         * @param dataLocalDate 数据日期
         * @param record        CSVRecord
         * @param totalRooms    总房间数
         * @param roundingMode  舍入模式
         * @return WMRevenueHistoryAndForecastBO
         * @author yyt
         * @date 2026/3/12
         */
        private WMRevenueHistoryAndForecastBO convert2Bo(LocalDate dataLocalDate, CSVRecord record, int totalRooms, RoundingMode roundingMode) {
            WMRevenueHistoryAndForecastBO bo = new WMRevenueHistoryAndForecastBO();

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

            // Total Occ.(Total Rooms Sold)
            String totalOccStr = CsvFileUtils.getAndFormatNumber(record, "D");
            bo.setTotalOcc(StringUtils.isBlank(totalOccStr) ? 0 : Integer.parseInt(totalOccStr));

            // Arrival Rooms
            String arrivalRoomsStr = CsvFileUtils.getAndFormatNumber(record, "F");
            bo.setArrivalRooms(StringUtils.isBlank(arrivalRoomsStr) ? 0 : Integer.parseInt(arrivalRoomsStr));

            // Departure Rooms
            String departureRoomsStr = CsvFileUtils.getAndFormatNumber(record, "H");
            bo.setDepartureRooms(StringUtils.isBlank(departureRoomsStr) ? 0 : Integer.parseInt(departureRoomsStr));

            // OCC %
            String occPercentStr = CsvFileUtils.getAndFormatNumber(record, "M");
            bo.setOccupancy(StringUtils.isBlank(occPercentStr) ? null : new BigDecimal(occPercentStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // Number of Persons
            String numberPersonsStr = CsvFileUtils.getAndFormatNumber(record, "K");
            bo.setNumberOfPersons(StringUtils.isBlank(numberPersonsStr) ? 0 : Integer.parseInt(numberPersonsStr));

            // ADR
            String adrStr = CsvFileUtils.getAndFormatNumber(record, "L");
            bo.setAverageRate(StringUtils.isBlank(adrStr) ? null : new BigDecimal(adrStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // Room Revenue = Rooms Sold * adr
            if(StringUtils.isNotEmpty(totalOccStr) && StringUtils.isNotEmpty(adrStr)){
                bo.setRoomRevenue(new BigDecimal(totalOccStr).multiply(new BigDecimal(adrStr))
                        .setScale(BaseConstant.DATA_PRECISION, roundingMode));
            }

            // OOO Rooms
            String availableRoomsStr = CsvFileUtils.getAndFormatNumber(record, "E");
            Integer oooRooms = calculatePropertyOperationService.calculateOooRooms(new CalculateOOORoomsDTO(totalRooms, bo.getTotalOcc(),
                    StringUtils.isEmpty(availableRoomsStr) ? null : Integer.parseInt(availableRoomsStr), null));
            bo.setOooRooms(Objects.isNull(oooRooms) ? 0 : oooRooms);

            // Sell Inventory Rooms = Sold Rooms + Available Rooms
            int sellInventoryRooms = 0;
            if(StringUtils.isNotEmpty(totalOccStr)){
                sellInventoryRooms = Integer.parseInt(totalOccStr);
            }
            if(StringUtils.isNotEmpty(availableRoomsStr)){
                sellInventoryRooms += Integer.parseInt(availableRoomsStr);
            }
            bo.setSellInventoryRooms(sellInventoryRooms);

            // Inventory Rooms
            bo.setInventoryRooms(totalRooms);

            // No Show Rooms
            bo.setNoShowRooms(0);

            // Complimentary Rooms
            bo.setComplimentaryRooms(0);

            // House Use Rooms
            bo.setHouseUseRooms(0);

            // Day Use Rooms
            bo.setDayUseRooms(0);

            // Deduct Individual
            Integer transientRooms = calculatePropertyOperationService.calculateTransientRooms(new CalculateTransientRoomsDTO(bo.getTotalOcc(), null));
            bo.setDeductIndividual(Objects.isNull(transientRooms) ? 0 : transientRooms);

            // Deduct Individual Revenue
            bo.setDeductIndividualRevenue(bo.getRoomRevenue());

            // Non-Deduct Individual
            bo.setNonDeductIndividual(0);

            // Non-Deduct Individual Revenue
            bo.setNonDeductIndividualRevenue(BigDecimal.ZERO);

            // Deduct Group
            bo.setDeductGroup(0);

            // Deduct Group Revenue
            bo.setDeductGroupRevenue(null);

            // Non-Deduct Group
            bo.setNonDeductGroup(0);

            // Non-Deduct Group Revenue
            bo.setNonDeductGroupRevenue(BigDecimal.ZERO);

            return bo;
        }

    }