# OccJumpAlertHistoryAndForecastParseServiceByPep.java

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

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.RoomsConfigDTO;
    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.commonlib.util.JsonUtils;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.entity.revenue.OccForecast;
    import cloud.wconnect.rateshop.pojo.bo.revenue.HistoryAndForecastOccJumpAlertBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.HistoryAndForecastOccJumpAlertDTO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.OccForecastValuesDTO;
    import cloud.wconnect.rateshop.service.revenue.IOccForecastService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    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.Component;
    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.function.Function;
    import java.util.stream.Collectors;

    /**
     * 解析 pep 系统的 History And Forecast/Service -1,90d 报告
     */
    @RequiredArgsConstructor
    @Slf4j
    @Component
    @DS("rate_shop")
    public class OccJumpAlertHistoryAndForecastParseServiceByPep implements IOccJumpAlertHistoryAndForecastParseService {

        private final RoomsConfigInternalService roomsConfigInternalService;
        private final IOccForecastService occForecastService;
        private final BeanMapper beanMapper;
        private final ObjectMapper objectMapper;

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

        /**
         * 解析报告
         *
         * @param in        报告文件流
         * @param property  资产
         * @param startDate 数据日期，开始时间（时间戳）
         * @param endDate   数据日期，结束时间（时间戳）
         * @return HistoryAndForecastOccJumpAlertBO
         * @author yyt
         * @date 2026/3/4
         */
        @Override
        public List<HistoryAndForecastOccJumpAlertBO> parse(InputStream in, PropertyDTO property, Long startDate, Long endDate) throws ParseReportException {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(property.getInternationalization().getNumber().getCalculationRule());
            // 获取 Revenue 房间数配置
            RoomsConfigDTO roomsConfigDTO = roomsConfigInternalService.getRoomsConfig(property.getId());
            Integer configTotalRooms = roomsConfigDTO.getRooms();
            Integer configOccRule = roomsConfigDTO.getOccRule();

            String timezone = property.getTimezone();
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<HistoryAndForecastOccJumpAlertBO> resultList = 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.isBlank(dateStr)) continue;

                    LocalDate localDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA);
                    long dataDate = DateTimeUtils.localDateToLong(localDate, timezone);
                    if (dataDate >= startDate && dataDate <= endDate) {
                        resultList.add(convert2Bo(localDate, record, configTotalRooms, configOccRule, roundingMode));
                    }
                }
                return resultList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "source=PEP, parse [History and forecast/service] report error", e);
            }
        }

        /**
         * 转换为 BO
         *
         * @param dataLocalDate    数据日期
         * @param record           行数据
         * @param roundingMode     舍入模式
         * @return HistoryAndForecastOccJumpAlertBO
         * @author yyt
         * @date 2026/3/4
         */
        private HistoryAndForecastOccJumpAlertBO convert2Bo(LocalDate dataLocalDate, CSVRecord record, Integer configTotalRooms,
                                                            Integer configOccRule, RoundingMode roundingMode) {
            HistoryAndForecastOccJumpAlertBO bo = new HistoryAndForecastOccJumpAlertBO();
            bo.setDate(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

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

            // 入住率
            // 如果配置了房间数，则根据 pc occ 计算规则判断：1.使用配置的房间数计算 pc occ，2.直接使用文件中的 occ 作为 pc occ
            if (Objects.nonNull(configTotalRooms) && configOccRule == RevenueCons.USE_ROOMS_TO_CALCULATE) {
                // pc occ = sold rooms / total rooms
                bo.setPcOcc(new BigDecimal(String.valueOf(totalOcc)).multiply(new BigDecimal("100"))
                        .divide(new BigDecimal(configTotalRooms), BaseConstant.DATA_PRECISION, roundingMode));
            } else {
                String occStr = CsvFileUtils.getAndFormatNumber(record, "M");
                if (StringUtils.isNotEmpty(occStr)) {
                    bo.setPcOcc(new BigDecimal(occStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
                }
            }

            String totalRoomsStr = CsvFileUtils.getAndFormatNumber(record, "C");
            Integer totalRooms = StringUtils.isEmpty(totalRoomsStr) ? null : Integer.parseInt(totalRoomsStr);
            if(Objects.nonNull(totalRooms)){
                bo.setTotalRooms(totalRooms);
            }

            String availableRoomsStr = CsvFileUtils.getAndFormatNumber(record, "E");
            bo.setAvailableRooms(StringUtils.isBlank(availableRoomsStr) ? null : Integer.parseInt(availableRoomsStr));

            return bo;
        }

        /**
         * 保存报告数据
         *
         * @param propertyDTO                          资产
         * @param historyAndForecastOccJumpAlertBOList 数据
         * @param operatorId                           操作人 id
         * @author yyt
         * @date 2026/3/4
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void saveReportData(PropertyDTO propertyDTO, List<HistoryAndForecastOccJumpAlertBO> historyAndForecastOccJumpAlertBOList, Integer operatorId) {
            if (CollectionUtils.isEmpty(historyAndForecastOccJumpAlertBOList)) return;

            List<HistoryAndForecastOccJumpAlertDTO> historyAndForecastDTOS = beanMapper.mapList(historyAndForecastOccJumpAlertBOList, HistoryAndForecastOccJumpAlertDTO.class,
                    (bo, dto) ->
                            dto.setTheDate(Long.parseLong(DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(bo.getDate(),
                                    BaseConstant.DATE_FORMAT_YYYY_MM_DD), BaseConstant.DATE_FORMAT_YYYYMMDD))));

            // 查询已存在的数据，重新计算相关数据
            Integer propertyId = propertyDTO.getId();
            List<Long> theDateList = historyAndForecastDTOS.stream().map(HistoryAndForecastOccJumpAlertDTO::getTheDate).toList();
            long startDateQuery = Collections.min(theDateList);
            long endDateQuery = Collections.max(theDateList);
            List<OccForecast> occForecastList = occForecastService.listByDateRangeForUpdate(propertyId, startDateQuery, endDateQuery);
            Map<Long, OccForecast> theDate2OccForecast = occForecastList.stream()
                    .collect(Collectors.toMap(OccForecast::getTheDate, Function.identity()));

            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO.getInternationalization().getNumber().getCalculationRule());

            // 获取当前时间的 key
            String currentKey = DateTimeUtils.parseToLong(DateTimeUtils.dateTimeNow(propertyDTO.getTimezone()),
                    BaseConstant.DATE_FORMAT_YYYYMMDDHH).toString();
            long nowTimestamp = DateTimeUtils.nowTimestamp();
            for (HistoryAndForecastOccJumpAlertDTO historyAndForecastDTO : historyAndForecastDTOS) {

                long theDate = historyAndForecastDTO.getTheDate();
                OccForecast originOccForecast = theDate2OccForecast.get(theDate);
                if (Objects.isNull(originOccForecast)) {
                    OccForecastValuesDTO currentValuesDTO = occForecastService.packageOccForecastValuesDTO(currentKey, historyAndForecastDTO, roundingMode, operatorId, nowTimestamp);
                    occForecastList.add(new OccForecast()
                            .setPropertyId(propertyId)
                            .setTheDate(theDate)
                            .setValues(JsonUtils.convertObjListToString(objectMapper, Lists.newArrayList(currentValuesDTO))));
                } else {
                    List<OccForecastValuesDTO> originValuesDTOList = JsonUtils.convertStringToList(objectMapper,
                            originOccForecast.getValues(), OccForecastValuesDTO.class);
                    Map<String, OccForecastValuesDTO> key2ValuesDTO = originValuesDTOList.stream()
                            .collect(Collectors.toMap(OccForecastValuesDTO::getKey, Function.identity()));
                    OccForecastValuesDTO valuesDTO = key2ValuesDTO.get(currentKey);
                    // 如果没有指定 currentKey 的数据，则新增，否则更新
                    if (Objects.isNull(valuesDTO)) {
                        OccForecastValuesDTO currentValuesDTO = occForecastService.packageOccForecastValuesDTO(currentKey, historyAndForecastDTO, roundingMode, operatorId, nowTimestamp);
                        originValuesDTOList.add(currentValuesDTO);
                    } else {
                        historyAndForecastDTO.setCompRooms(valuesDTO.getValue().getCompRooms());
                        OccForecastValuesDTO currentValuesDTO = occForecastService.packageOccForecastValuesDTO(currentKey, historyAndForecastDTO, roundingMode, operatorId, nowTimestamp);
                        valuesDTO.setValue(currentValuesDTO.getValue());
                        valuesDTO.setUpdatedBy(currentValuesDTO.getUpdatedBy());
                        valuesDTO.setUpdatedTime(currentValuesDTO.getUpdatedTime());
                    }
                    originOccForecast.setValues(JsonUtils.convertObjListToString(objectMapper, originValuesDTOList));
                }
            }
            // 批量保存
            occForecastService.saveOrUpdateBatch(occForecastList);
        }

    }