# HistoryAndForecastByPep.java

    package cloud.wconnect.workperformance.service.schedule.historyandforecast;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    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.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleHistoryAndForecastImportLog;
    import cloud.wconnect.workperformance.pojo.bo.schedule.ScheduleHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHandleReportService;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHistoryAndForecastImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;

    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;

    /**
     * History And Forecast By PEP Auto
     *
     * @author yyt
     * 2026/2/3
     */
    @RequiredArgsConstructor
    @Service
    @DS("work_performance")
    public class HistoryAndForecastByPep implements IHistoryAndForecastFileParse {

        private final IScheduleHistoryAndForecastImportLogService scheduleHistoryAndForecastImportLogService;
        private final IScheduleHandleReportService scheduleHandleReportService;

        @Value("${file-max-size.import-report.schedule}")
        private Long importReportFileMaxSize;

        /**
         * 判断支持的平台
         *
         * @param source 平台数据源
         * @return boolean
         * @author yyt
         * @date 2026/2/3
         */
        @Override
        public boolean supports(String source) {
            return source.equals(SystemPlatformEnum.PEP.getDesc());
        }

        /**
         * 解析报告数据
         *
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @param inputStream 文件流
         * @param propertyDTO 资产
         * @return history and forecast
         * @author yyt
         * @date 2026/2/3
         */
        @Override
        public List<ScheduleHistoryAndForecastBO> parsReport(Long startDate, Long endDate, InputStream inputStream,
                                                             PropertyDTO propertyDTO) {
            // 最多14天数据
            List<ScheduleHistoryAndForecastBO> historyAndForecasts = Lists.newArrayListWithExpectedSize(14);
            String timeZone = propertyDTO.getTimezone();
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream)) {
                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = iterable.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 = DateTimeUtils.localDateToLong(localDate, timeZone);

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

                        String roomSoldStr = CsvFileUtils.getAndFormatNumber(csvRecord, "D");
                        historyAndForecast.setSoldRooms(StringUtils.isEmpty(roomSoldStr) ? 0 : Integer.parseInt(roomSoldStr));

                        String arrivalRoomsStr = CsvFileUtils.getAndFormatNumber(csvRecord, "F");
                        historyAndForecast.setArrivalRooms(StringUtils.isEmpty(arrivalRoomsStr) ? 0 : Integer.parseInt(arrivalRoomsStr));

                        String departureRoomsStr = CsvFileUtils.getAndFormatNumber(csvRecord, "H");
                        historyAndForecast.setDepartureRooms(StringUtils.isEmpty(departureRoomsStr) ? 0 : Integer.parseInt(departureRoomsStr));

                        String occupancyStr = CsvFileUtils.getAndFormatNumber(csvRecord, "M");
                        historyAndForecast.setOcc(StringUtils.isEmpty(occupancyStr) ? BigDecimal.ZERO :
                                new BigDecimal(occupancyStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));

                        historyAndForecasts.add(historyAndForecast);
                    }
                }
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "parse pep [Occupancy Forecast] report error", e);
            }
            return historyAndForecasts;
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2026/2/3
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));

            try (InputStream in = file.getInputStream()) {
                PepFileCheckUtils.checkOccupancyForecast(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing pep [Occupancy Forecast] file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @param userId      操作人
         * @return 导入记录
         * @author yyt
         * @date 2026/2/3
         */
        @Override
        public ScheduleHistoryAndForecastImportLog handleImportLog(PropertyDTO propertyDTO,
                                                                   ScheduleHistoryAndForecastImportLog importLog,
                                                                   Long theDate, Long startDate, Long endDate, int userId) {
            if (Objects.isNull(importLog)) {
                importLog = scheduleHistoryAndForecastImportLogService.saveRecord(propertyDTO.getId(), theDate, startDate,
                        endDate, ReportImportResultCons.IMPORT_IN_PROGRESS, userId);
            } else {
                // 更新异常为修复中
                ScheduleHistoryAndForecastImportLog updateContent = new ScheduleHistoryAndForecastImportLog();
                updateContent.setId(importLog.getId());
                updateContent.setImportResult(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
                scheduleHistoryAndForecastImportLogService.updateById(updateContent);
            }
            return importLog;
        }

        /**
         * 处理文件
         *
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2026/2/3
         */
        @Override
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file, ScheduleHistoryAndForecastImportLog importLog, Integer userId) {
            scheduleHandleReportService.sendHistoryAndForecastEvent(propertyDTO, SystemPlatformEnum.PEP.getDesc(), file, importLog, userId);
        }

    }