# HotelKpiHistoryAndForecastParseServiceByPep.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    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.util.*;
    import cloud.wconnect.workperformance.pojo.bo.hotelkpi.HotelKpiHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiHandleReportService;
    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.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

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

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

        private final IHotelKpiHandleReportService hotelKpiHandleReportService;

        @Value("${file-max-size.import-report.hotel-kpi}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2026/2/6
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                PepFileCheckUtils.checkOccupancyForecast(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Hotel KPI History and forecast PEP report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author yyt
         * @date 2026/2/6
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, List<Long> dateRange, long logId, int operatorId) {
            hotelKpiHandleReportService.sendHistoryAndForecastEvent(propertyDTO, SystemPlatformEnum.PEP.getDesc(), file, dateRange, logId, operatorId);
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return HotelKpiHistoryAndForecastBO 集合
         * @author yyt
         * @date 2026/2/6
         */
        @Override
        public List<HotelKpiHistoryAndForecastBO> 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<HotelKpiHistoryAndForecastBO> 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) {
                        boList.add(convert2Bo(localDate, csvRecord, roundingMode));
                    }
                }
                return boList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Hotel KPI History and forecast PEP report error.", e);
            }
        }

        /**
         * 将报告中的信息转换为实体类
         *
         * @param dataLocalDate 数据日期
         * @param recordTotal   CSVRecord Total
         * @param roundingMode  舍入模式
         * @return HotelKpiHistoryAndForecastBO
         * @author yyt
         * @date 2026/2/6
         */
        private HotelKpiHistoryAndForecastBO convert2Bo(LocalDate dataLocalDate, CSVRecord recordTotal, RoundingMode roundingMode) {
            HotelKpiHistoryAndForecastBO bo = new HotelKpiHistoryAndForecastBO();

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

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

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

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

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

            // Room Revenue = Rooms Sold * ADR
            bo.setRoomRevenue(Objects.isNull(adr) ? null : adr.multiply(new BigDecimal(roomsSold)).setScale(BaseConstant.DATA_PRECISION, roundingMode));

            return bo;
        }

    }