# RateShopMarketSegmentSummaryListenerFileParseByPepImpl.java

    package cloud.wconnect.rateshop.service.rateshop.marketsegmentsummary.messagelistener;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.PropertyRoomSoldTypeCons;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.calculateoperation.CalculateTransientRoomsDTO;
    import cloud.wconnect.commonlib.service.CalculatePropertyOperationService;
    import cloud.wconnect.commonlib.service.PropertyRoomSoldInternalService;
    import cloud.wconnect.commonlib.util.CsvFileUtils;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.rateshop.entity.rateshop.PropertyOperation;
    import cloud.wconnect.rateshop.entity.revenue.RevenueAdrConfig;
    import cloud.wconnect.rateshop.pojo.dto.rateshop.MarketSegmentSummaryDTO;
    import cloud.wconnect.rateshop.service.rateshop.IPropertyOperationService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueAdrConfigService;
    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.Service;
    import org.springframework.transaction.annotation.Transactional;

    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.time.LocalDate;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * Market Segment Summary PEP 来源报告解析
     *
     * @author yyt
     * @date 2026/3/10
     */
    @RequiredArgsConstructor
    @Service
    @Slf4j
    @DS("rate_shop")
    public class RateShopMarketSegmentSummaryListenerFileParseByPepImpl implements IRateShopMarketSegmentSummaryListenerFileParse {

        private final IRevenueAdrConfigService revenueAdrConfigService;
        private final PropertyRoomSoldInternalService propertyRoomSoldInternalService;
        private final IPropertyOperationService propertyOperationService;
        private final CalculatePropertyOperationService calculatePropertyOperationService;

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

        /**
         * 解析报告数据
         *
         * @param propertyDTO 资产
         * @param in          文件流
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @return MarkegSegmentSummaryDTO
         * @author yyt
         * @date 2026/3/10
         */
        @Override
        public List<MarketSegmentSummaryDTO> parseReport(PropertyDTO propertyDTO, InputStream in, Long startDate, Long endDate) throws Exception {
            // 解析文件数据
            Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(new InputStreamReader(in));
            Iterator<CSVRecord> iterator = records.iterator();
            if (!iterator.hasNext()) return Collections.emptyList();

            Integer propertyId = propertyDTO.getId();
            List<String> marketSymbols = propertyRoomSoldInternalService.list(propertyId)
                    .stream().filter(item -> item.getType() == PropertyRoomSoldTypeCons.GROUP)
                    .map(item-> item.getMarketSymbol().toLowerCase())
                    .toList();
            if (CollectionUtils.isEmpty(marketSymbols)) return Collections.emptyList();

            RevenueAdrConfig revenueAdrConfig = revenueAdrConfigService.get(propertyId);
            boolean checkGroupDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckGroupDeduct();
            if (!checkGroupDeduct) return Collections.emptyList();

            String timezone = propertyDTO.getTimezone();
            List<MarketSegmentSummaryDTO> marketSegmentSummaryDTOS = new ArrayList<>();

            // 跳过标题
            iterator.next();
            while (iterator.hasNext()) {
                CSVRecord record = iterator.next();
                // 空行
                if (record.size() == BaseConstant.ZERO) continue;

                // 解析每天数据
                String date = CsvFileUtils.get(record, "A");
                if (StringUtils.isEmpty(date)) continue;

                LocalDate localDate = DateTimeUtils.strToLocalDate(date, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA);
                long dataDate = DateTimeUtils.localDateToLong(localDate, timezone);
                if (dataDate < startDate || dataDate > endDate) {
                    continue;
                }

                MarketSegmentSummaryDTO marketSegmentSummaryDTO = new MarketSegmentSummaryDTO();
                marketSegmentSummaryDTO.setDate(dataDate);
                String marketSegment = CsvFileUtils.get(record, "C");
                if(StringUtils.isEmpty(marketSegment)) continue;
                if(!marketSymbols.contains(marketSegment.toLowerCase())){
                    continue;
                }

                String staysStr = CsvFileUtils.getAndFormatNumber(record, "H");
                if (StringUtils.isNotEmpty(staysStr)) {
                    marketSegmentSummaryDTO.setGroupRooms(Integer.parseInt(staysStr));
                }
                marketSegmentSummaryDTOS.add(marketSegmentSummaryDTO);
            }

            if(CollectionUtils.isEmpty(marketSegmentSummaryDTOS)) return Collections.emptyList();

            // 数据按照日期汇总，每天的数据汇总 group room number 作为一天的数据
            List<MarketSegmentSummaryDTO> result = Lists.newArrayListWithExpectedSize(1);
            Map<Long, List<Integer>> groupRoomNumbersByDate = marketSegmentSummaryDTOS.stream().collect(Collectors.groupingBy(MarketSegmentSummaryDTO::getDate,
                    Collectors.collectingAndThen(Collectors.toList(), list -> list.stream().map(MarketSegmentSummaryDTO::getGroupRooms)
                            .filter(Objects::nonNull).toList())));
            groupRoomNumbersByDate.forEach((date, groupRoomNumbers) -> {
                MarketSegmentSummaryDTO marketSegmentSummaryDTO = new MarketSegmentSummaryDTO();
                marketSegmentSummaryDTO.setDate(date);
                marketSegmentSummaryDTO.setGroupRooms(groupRoomNumbers.stream().mapToInt(item -> item).sum());
                result.add(marketSegmentSummaryDTO);
            });

            return result;
        }

        /**
         * 保存报告数据
         *
         * @param propertyDTO              资产
         * @param marketSegmentSummaryDTOS 报告数据
         * @param operatorId               操作人 id
         * @author yyt
         * @date 2026/3/10
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void saveReportData(PropertyDTO propertyDTO, List<MarketSegmentSummaryDTO> marketSegmentSummaryDTOS, int operatorId) {
            if (CollectionUtils.isEmpty(marketSegmentSummaryDTOS)) return;

            // 查询已存在的数据，然后重新计算相关数据
            List<Long> dates = marketSegmentSummaryDTOS.stream().map(MarketSegmentSummaryDTO::getDate).sorted().toList();
            Long startDate = dates.get(0);
            Long endDate = dates.get(dates.size() - 1);
            Map<Long, PropertyOperation> existPropertyOperationByDate = propertyOperationService.listByDateRange(propertyDTO.getId(), startDate, endDate)
                    .stream().collect(Collectors.toMap(PropertyOperation::getTargetDate, v -> v));

            Integer propertyId = propertyDTO.getId();
            long now = DateTimeUtils.nowTimestamp();
            List<PropertyOperation> propertyOperations = Lists.newArrayListWithExpectedSize(marketSegmentSummaryDTOS.size());
            for (MarketSegmentSummaryDTO marketSegmentSummaryDTO : marketSegmentSummaryDTOS) {
                PropertyOperation existPropertyOperation = existPropertyOperationByDate.getOrDefault(marketSegmentSummaryDTO.getDate(), new PropertyOperation());
                PropertyOperation propertyOperation = new PropertyOperation();
                propertyOperation.setPropertyId(propertyId);
                propertyOperation.setTargetDate(marketSegmentSummaryDTO.getDate());

                Integer groupRooms = marketSegmentSummaryDTO.getGroupRooms();
                propertyOperation.setGroupSold(groupRooms);
                // 计算散客
                propertyOperation.setTransientSold(calculatePropertyOperationService.calculateTransientRooms(new CalculateTransientRoomsDTO(existPropertyOperation.getRoomsSold(), groupRooms)));

                propertyOperation.setPmsUpdatedBy(operatorId);
                propertyOperation.setPmsUpdatedTime(now);
                propertyOperations.add(propertyOperation);
            }

            propertyOperationService.saveMarketSegmentSummaryData(propertyOperations);
        }

    }