# GmwrHistoryAndForecastParseServiceByPep.java

    package cloud.wconnect.workperformance.service.gmwr.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.InternalServerErrorException;
    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.workperformance.entity.gmwr.GmwrHistoryAndForecast;
    import cloud.wconnect.workperformance.pojo.bo.gmwr.GmwrHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.gmwr.IGmwrHistoryAndForecastService;
    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.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.stream.Collectors;

    /**
     * 解析 PEP 系统的 History And Forecast 报告
     */
    @RequiredArgsConstructor
    @Slf4j
    @Component
    @DS("work_performance")
    public class GmwrHistoryAndForecastParseServiceByPep implements IGmwrHistoryAndForecastParseService {

        private final IGmwrHistoryAndForecastService historyAndForecastService;
        private final BeanMapper beanMapper;

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

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return GmwrHistoryAndForecastBO 集合
         * @author yyt
         * @date 2025/7/23
         */
        @Override
        public List<GmwrHistoryAndForecastBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO.getInternationalization().getNumber().getCalculationRule());
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<GmwrHistoryAndForecastBO> boList = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = records.iterator();
                // 跳过第一行的标题行
                iterator.next();
                while (iterator.hasNext()) {
                    CSVRecord csvRecord = iterator.next();
                    String dateStr = CsvFileUtils.get(csvRecord, "A");
                    if (StringUtils.isEmpty(dateStr)) continue;

                    LocalDate localDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA);
                    long targetDate = Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));

                    //判断目标日期是否在范围中
                    if (targetDate >= startDate && targetDate <= endDate) {
                        GmwrHistoryAndForecastBO historyAndForecast = new GmwrHistoryAndForecastBO();
                        historyAndForecast.setDateStr(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

                        String totalRoomsStr = CsvFileUtils.getAndFormatNumber(csvRecord, "C");
                        historyAndForecast.setTotalRooms(StringUtils.isEmpty(totalRoomsStr) ? 0 : Integer.parseInt(totalRoomsStr));

                        String roomsSoldStr = CsvFileUtils.getAndFormatNumber(csvRecord, "D");
                        int roomSold = StringUtils.isEmpty(roomsSoldStr) ? 0 : Integer.parseInt(roomsSoldStr);
                        historyAndForecast.setRoomsSold(roomSold);

                        String availableRoomsStr = CsvFileUtils.getAndFormatNumber(csvRecord, "E");
                        historyAndForecast.setAvailableRooms(StringUtils.isEmpty(availableRoomsStr) ? 0 : Integer.parseInt(availableRoomsStr));

                        // 默认 0
                        historyAndForecast.setOoo(0);

                        String adrStr = CsvFileUtils.getAndFormatNumber(csvRecord, "L");
                        BigDecimal adr = StringUtils.isEmpty(adrStr) ? BigDecimal.ZERO : new BigDecimal(adrStr);
                        historyAndForecast.setRoomRevenue(BigDecimal.valueOf(roomSold).multiply(adr).setScale(BaseConstant.DATA_PRECISION, roundingMode));

                        boList.add(historyAndForecast);
                    }
                }
                return boList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse GM Weekly Report History and forecast pep report error.", e);
            }
        }

        /**
         * 处理 History And Forecast 数据
         *
         * @param propertyDTO              资产
         * @param historyAndForecastBOList 报告数据
         * @author yyt
         * @date 2026/2/5
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleHistoryAndForecast(PropertyDTO propertyDTO, List<GmwrHistoryAndForecastBO> historyAndForecastBOList) {
            if (CollectionUtils.isEmpty(historyAndForecastBOList)) {
                return;
            }

            Integer propertyId = propertyDTO.getId();
            List<GmwrHistoryAndForecast> historyAndForecasts = beanMapper.mapList(historyAndForecastBOList,
                    GmwrHistoryAndForecast.class, (bo, entity) -> {
                        entity.setPropertyId(propertyId);
                        LocalDate localDate = DateTimeUtils.strToLocalDate(bo.getDateStr(), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                        entity.setDate(Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD)));
                    });

            // 查询已存在的数据
            historyAndForecasts.sort(Comparator.comparing(GmwrHistoryAndForecast::getDate));
            Map<Long, GmwrHistoryAndForecast> existDateByDate = historyAndForecastService.list(propertyDTO,
                            historyAndForecasts.get(0).getDate(), historyAndForecasts.get(historyAndForecasts.size() - 1).getDate())
                    .stream().collect(Collectors.toMap(GmwrHistoryAndForecast::getDate, v -> v));

            for (GmwrHistoryAndForecast historyAndForecast : historyAndForecasts) {
                GmwrHistoryAndForecast existData = existDateByDate.get(historyAndForecast.getDate());
                if (Objects.nonNull(existData)) {
                    // 重置 OOO 房数
                    historyAndForecast.setCompRooms(existData.getCompRooms());
                    historyAndForecast.setOoo(historyAndForecastService.calculateOooRooms(historyAndForecast));
                }
            }

            historyAndForecastService.insertOrUpdateBatchByUnique(historyAndForecasts);
        }

    }