# DbPmsMssParseServiceByPep.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.PropertyRoomSoldTypeCons;
    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.service.PropertyRoomSoldInternalService;
    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.time.LocalDate;
    import java.util.*;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 解析 PEP Market Segment Summary 报告
     *
     * @author zc
     * @date 2026/3/5
     */
    @Component
    @DS("work_performance")
    public class DbPmsMssParseServiceByPep implements IDbPmsMssParseService {

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

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

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

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

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

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

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return List<DbPmsHfBO> 集合
         * @author zc
         * @date 2026/3/5
         */
        @Override
        public List<DbPmsHfBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            // 获取有效的 Segment Code
            List<String> effectiveSegment = propertyRoomSoldInternalService.list(propertyDTO.getId()).stream()
                    .filter(item -> item.getType() == PropertyRoomSoldTypeCons.GROUP)
                    .map(item -> item.getMarketSymbol().toLowerCase()).toList();

            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) {
                        continue;
                    }
                    String marketSegmentStr = CsvFileUtils.get(csvRecord, "C");
                    if (!effectiveSegment.contains(marketSegmentStr.toLowerCase())) {
                        continue;
                    }
                    boList.add(convert2Bo(localDate, csvRecord));
                }
                // 日期分组汇总数据
                List<DbPmsHfBO> summaryBoList = groupSummary(boList);

                // 补充计算数据
                supplementaryCalculations(propertyDTO.getId(), summaryBoList);

                return summaryBoList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Database Market Segment Summary PEP report error.", e);
            }
        }

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

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

            // 用于汇总 Stays
            String staysStr = CsvFileUtils.getAndFormatNumber(record, "H");
            // Deduct Group Rooms Sold
            bo.setDgs(StringUtils.isBlank(staysStr) ? 0 : Integer.parseInt(staysStr));

            // 用于汇总 Room Revenue
            String roomRevenueStr = CsvFileUtils.getAndFormatNumber(record, "E");
            // Deduct Group Room Revenue
            bo.setDgr(StringUtils.isBlank(roomRevenueStr) ? BigDecimal.ZERO : new BigDecimal(roomRevenueStr));

            return bo;
        }

        /**
         * 以日期分组汇总数据
         *
         * @param boList BO集合
         * @author zc
         * @date 2026/3/5
         */
        private List<DbPmsHfBO> groupSummary(List<DbPmsHfBO> boList) {
            if (CollectionUtils.isEmpty(boList)) {
                return Lists.newArrayList();
            }

            Map<String, List<DbPmsHfBO>> groupedByDate = boList.stream()
                    .collect(Collectors.groupingBy(DbPmsHfBO::getDStr));

            List<DbPmsHfBO> result = Lists.newArrayList();
            groupedByDate.forEach((dateStr, boGroup) -> {
                DbPmsHfBO summaryBO = new DbPmsHfBO();
                summaryBO.setDStr(dateStr);

                Integer totalDgs = boGroup.stream().map(DbPmsHfBO::getDgs)
                        .filter(Objects::nonNull).reduce(0, Integer::sum);
                summaryBO.setDgs(totalDgs);

                BigDecimal totalDgr = boGroup.stream().map(DbPmsHfBO::getDgr)
                        .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                summaryBO.setDgr(totalDgr);

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

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

                result.add(summaryBO);
            });

            return result;
        }

        /**
         * 补充计算
         *
         * @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 = (hfHistoryDTO.getIr() == null) ? 0 : hfHistoryDTO.getIr();
                // Rooms Sold(Occupancy Forecast)
                int roomsSold = (hfHistoryDTO.getRs() == null) ? 0 : hfHistoryDTO.getRs();
                // Available Rooms(Occupancy Forecast)
                int availableRooms = (hfHistoryDTO.getAvr() == null) ? 0 : hfHistoryDTO.getAvr();
                // Room Revenue(Occupancy Forecast)
                BigDecimal roomRevenue = (hfHistoryDTO.getRr() == null) ? BigDecimal.ZERO : hfHistoryDTO.getRr();
                // Comp Rooms(Occupancy Summary)
                int compRooms = (hfHistoryDTO.getCom() == null) ? 0 : hfHistoryDTO.getCom();

                // Deduct Group Rooms Sold(Market Segment Summary)
                int deductGroupRoomsSold = (bo.getDgs() == null) ? 0 : bo.getDgs();
                // Deduct Group Room Revenue(Market Segment Summary)
                BigDecimal deductGroupRoomRevenue = (bo.getDgr() == null) ? BigDecimal.ZERO : bo.getDgr();

                // 设置数值
                bo.setOcc(hfHistoryDTO.getOcc());
                bo.setIr(hfHistoryDTO.getIr());
                // Sell inventory rooms = Rooms Sold + Available Rooms + Comp Rooms
                bo.setSir(roomsSold + availableRooms + compRooms);
                bo.setRs(hfHistoryDTO.getRs());
                // Deduct Indiv. Rooms Sold = Rooms Sold - Deduct Group Rooms Sold
                bo.setDis(roomsSold - deductGroupRoomsSold);
                bo.setRr(hfHistoryDTO.getRr());
                // Deduct Indiv. Room Revenue = Room Revenue - Deduct Group Room Revenue
                bo.setDir(roomRevenue.subtract(deductGroupRoomRevenue));
                bo.setArr(hfHistoryDTO.getArr());
                bo.setDep(hfHistoryDTO.getDep());
                bo.setCom(hfHistoryDTO.getCom());
                // OOO Rooms = Total Rooms - Sold Rooms - Available Rooms - Comp Rooms
                bo.setOoo(totalRooms - roomsSold - availableRooms - compRooms);
                bo.setNs(hfHistoryDTO.getNs());
                bo.setHu(hfHistoryDTO.getHu());
                bo.setDu(hfHistoryDTO.getDu());
                bo.setGu(hfHistoryDTO.getGu());
                bo.setAdr(hfHistoryDTO.getAdr());
                bo.setAvr(hfHistoryDTO.getAvr());
            });
        }
    }