# DbPmsHfParseServiceByPep.java

    package cloud.wconnect.workperformance.service.database.historyforecast;

    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.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.entity.database.DbPmsHfHistory;
    import cloud.wconnect.workperformance.entity.database.DbReportImportLog;
    import cloud.wconnect.workperformance.pojo.bo.database.historyforecast.DbPmsHfBO;
    import cloud.wconnect.workperformance.pojo.dto.database.historyforecast.DbPmsHfHistoryDTO;
    import cloud.wconnect.workperformance.service.database.IDbPmsHfHistoryService;
    import cloud.wconnect.workperformance.service.database.IDbReportService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import org.apache.commons.collections4.CollectionUtils;
    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.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 解析 PEP Occupancy Forecast 报告
     *
     * @author zc
     * @date 2026/02/27
     */
    @Component
    @DS("work_performance")
    public class DbPmsHfParseServiceByPep implements IDbPmsHfParseService {

        private final IDbPmsHfHistoryService hfHistoryService;
        private final IDbReportService reportService;
        private final ObjectMapper objectMapper;

        public DbPmsHfParseServiceByPep(IDbPmsHfHistoryService hfHistoryService, IDbReportService reportService, ObjectMapper objectMapper) {
            this.hfHistoryService = hfHistoryService;
            this.reportService = reportService;
            this.objectMapper = objectMapper;
        }

        @Value("${aws-s3.third-party.key.database.occupancy-forecast}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.database}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2026/2/27
         */
        @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 Database Occupancy forecast PEP report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2026/2/27
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, DbReportImportLog importLog, int operatorId) {
            reportService.sendReportEvent(propertyDTO, file, importLog, operatorId, s3FilePath,
                    EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_LAST_2_DAY_TO_365_DAY.getSubject());
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return List<DbPmsHfBO> 集合
         * @author zc
         * @date 2026/2/27
         */
        @Override
        public List<DbPmsHfBO> 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<DbPmsHfBO> 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));
                    }
                }
                // 补充计算数据
                supplementaryCalculations(propertyDTO.getId(), boList);

                return boList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Database Occupancy forecast PEP report error.", e);
            }
        }

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

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

            // Occ%
            String occStr = CsvFileUtils.getAndFormatNumber(record, "M");
            bo.setOcc(StringUtils.isBlank(occStr) ? null : new BigDecimal(occStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // Inventory Rooms(Total Rooms)
            String inventoryRoomsStr = CsvFileUtils.getAndFormatNumber(record, "C");
            int inventoryRooms = StringUtils.isBlank(inventoryRoomsStr) ? 0 : Integer.parseInt(inventoryRoomsStr);
            bo.setIr(inventoryRooms);

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

            // Available Rooms
            String availableRoomsStr = CsvFileUtils.getAndFormatNumber(record, "E");
            int availableRooms = StringUtils.isBlank(availableRoomsStr) ? 0 : Integer.parseInt(availableRoomsStr);
            bo.setAvr(availableRooms);

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

            // Room Revenue = Rooms Sold * ADR
            bo.setRr(new BigDecimal(String.valueOf(roomsSold)).multiply(adr).setScale(BaseConstant.DATA_PRECISION, roundingMode));

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

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

            // Adl. & Chl.
            String guestStr = CsvFileUtils.getAndFormatNumber(record, "K");
            bo.setGu(StringUtils.isBlank(guestStr) ? 0 : Integer.parseInt(guestStr));

            // Non-Ded. Indiv. Rooms Sold
            bo.setNdis(0);
            // Non-Ded. Indiv. Room Revenue
            bo.setNdir(BigDecimal.ZERO);

            // Non-Ded. Group Rooms Sold
            bo.setNdgs(null);
            // Non-Ded. Group Room Revenue
            bo.setNdgr(null);

            return bo;
        }

        /**
         * 补充计算
         *
         * @param propertyId 资产ID
         * @param boList     BO集合
         * @author zc
         * @date 2026/3/5
         */
        private void supplementaryCalculations(int propertyId, List<DbPmsHfBO> boList) {
            if (CollectionUtils.isEmpty(boList)) {
                return;
            }
            List<Long> dateList = boList.stream().map(bo -> {
                LocalDate localDate = DateTimeUtils.strToLocalDate(bo.getDStr(), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                return Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
            }).toList();

            long startDate = Collections.min(dateList);
            long endDate = Collections.max(dateList);
            List<DbPmsHfHistory> hfHistoryList = hfHistoryService.listByDateRange(propertyId, startDate, endDate);
            if (CollectionUtils.isEmpty(hfHistoryList)) {
                return;
            }
            Map<Long, DbPmsHfHistory> date2HfHistory = hfHistoryList.stream()
                    .collect(Collectors.toMap(DbPmsHfHistory::getDate, Function.identity()));

            boList.forEach(bo -> {
                LocalDate localDate = DateTimeUtils.strToLocalDate(bo.getDStr(), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                long date = Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));

                DbPmsHfHistoryDTO hfHistoryDTO = new DbPmsHfHistoryDTO();
                DbPmsHfHistory hfHistory = date2HfHistory.get(date);
                if (hfHistory != null) {
                    hfHistoryDTO = JsonUtils.convertStringToObject(objectMapper, hfHistory.getData(), DbPmsHfHistoryDTO.class);
                }

                // Total Rooms(Occupancy Forecast)
                int totalRooms = (bo.getIr() == null) ? 0 : bo.getIr();
                // Rooms Sold(Occupancy Forecast)
                int roomsSold = (bo.getRs() == null) ? 0 : bo.getRs();
                // Available Rooms(Occupancy Forecast)
                int availableRooms = (bo.getAvr() == null) ? 0 : bo.getAvr();
                // Room Revenue(Occupancy Forecast)
                BigDecimal roomRevenue = (bo.getRr() == null) ? BigDecimal.ZERO : bo.getRr();
                // Comp Rooms(Occupancy Summary)
                int compRooms = (hfHistoryDTO.getCom() == null) ? 0 : hfHistoryDTO.getCom();
                // Deduct Group Rooms Sold(Market Segment Summary)
                int deductGroupRoomsSold = (hfHistoryDTO.getDgs() == null) ? 0 : hfHistoryDTO.getDgs();
                // Deduct Group Room Revenue(Market Segment Summary)
                BigDecimal deductGroupRoomRevenue = (hfHistoryDTO.getDgr() == null) ? BigDecimal.ZERO : hfHistoryDTO.getDgr();

                // 设置数值
                // Sell inventory rooms = Rooms Sold + Available Rooms + Comp Rooms
                bo.setSir(roomsSold + availableRooms + compRooms);
                // OOO Rooms = Total Rooms - Sold Rooms - Available Rooms - Comp Rooms
                bo.setOoo(totalRooms - roomsSold - availableRooms - compRooms);
                // Deduct Indiv. Rooms Sold = Rooms Sold - Deduct Group Rooms Sold
                bo.setDis(roomsSold - deductGroupRoomsSold);
                // Deduct Indiv. Room Revenue = Room Revenue - Deduct Group Room Revenue
                bo.setDir(roomRevenue.subtract(deductGroupRoomRevenue));
                bo.setDgs(hfHistoryDTO.getDgs());
                bo.setDgr(hfHistoryDTO.getDgr());
                bo.setCom(hfHistoryDTO.getCom());
                bo.setNs(hfHistoryDTO.getNs());
                bo.setHu(hfHistoryDTO.getHu());
                bo.setDu(hfHistoryDTO.getDu());

            });
        }
    }