# OccJumpAlertOccupancySummaryYesterdayParseServiceByPep.java

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

    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.util.CsvFileUtils;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    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.OccForecastValueDTO;
    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.RoundingMode;
    import java.time.LocalDate;
    import java.util.*;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 解析 pep 系统的 Occupancy Summary Yesterday 报告
     */
    @RequiredArgsConstructor
    @Slf4j
    @Component
    @DS("rate_shop")
    public class OccJumpAlertOccupancySummaryYesterdayParseServiceByPep implements IOccJumpAlertOccupancySummaryYesterdayParseService {

        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 {
            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.isEmpty(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));
                    }
                }
                return resultList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "source=PEP, parse [Occupancy Summary Yesterday] report error", e);
            }
        }

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

            //入住率
            String compRoomsStr = CsvFileUtils.getAndFormatNumber(record, "O");
            bo.setCompRooms(StringUtils.isEmpty(compRoomsStr) ? null : Integer.parseInt(compRoomsStr));

            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 {
                        OccForecastValueDTO value = valuesDTO.getValue();
                        historyAndForecastDTO.setTotalRooms(value.getTotalRooms());
                        historyAndForecastDTO.setRoomsSold(value.getRoomsSold());
                        historyAndForecastDTO.setAvailableRooms(value.getAvailableRooms());
                        historyAndForecastDTO.setPcOcc(value.getPcOcc());
                        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);
        }

    }