# HotelKpiManagerFlashParseServiceByPep.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.PropertyRevenueDescriptionTypeCons;
    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.PropertyRevenueDescriptionDTO;
    import cloud.wconnect.commonlib.service.PropertyRevenueDescriptionInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiManagerFlashCons;
    import cloud.wconnect.workperformance.pojo.bo.hotelkpi.HotelKpiManagerFlashBO;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiHandleReportService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    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.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.util.*;
    import java.util.stream.Collectors;

    /**
     * 解析 PEP 系统的 Manager Flash/Service 报告
     *
     * @author yyt
     * @date 2026/02/7
     */
    @RequiredArgsConstructor
    @Component
    @DS("work_performance")
    public class HotelKpiManagerFlashParseServiceByPep implements IHotelKpiManagerFlashParseService {

        private final IHotelKpiHandleReportService hotelKpiHandleReportService;
        private final PropertyRevenueDescriptionInternalService propertyRevenueDescriptionInternalService;

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

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

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

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

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @return HotelKpiManagerFlashBO 集合
         * @author yyt
         * @date 2026/2/7
         */
        @Override
        public List<HotelKpiManagerFlashBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            // 查询资产 revenue description 配置
            Integer propertyId = propertyDTO.getId();
            List<PropertyRevenueDescriptionDTO> revenueDescriptionDTOS = propertyRevenueDescriptionInternalService.list(propertyId);
            Map<Boolean, List<String>> namesByIsRoomType = revenueDescriptionDTOS.stream().collect(Collectors.partitioningBy(item -> item.getType() == PropertyRevenueDescriptionTypeCons.ROOM,
                    Collectors.mapping(item -> item.getName().toLowerCase(), Collectors.toList())));
            List<String> roomTypeNames = namesByIsRoomType.getOrDefault(true, Collections.emptyList());
            List<String> fbAndOtherNames = namesByIsRoomType.getOrDefault(false, Collections.emptyList());

            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            List<HotelKpiManagerFlashBO> boList = Lists.newArrayList();
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {

                List<HotelKpiManagerFlashBO> fbAndOtherRevenueList = Lists.newArrayList();
                List<HotelKpiManagerFlashBO> roomRevenueList = Lists.newArrayList();

                // 获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = iterable.iterator();
                // 跳过标题行
                iterator.next();
                while (iterator.hasNext()) {
                    CSVRecord csvRecord = iterator.next();
                    String description = CsvFileUtils.get(csvRecord, "A");
                    if(StringUtils.isEmpty(description)) continue;

                    if ("ROOM SOLD - Stay Overs".equalsIgnoreCase(description)) {
                        boList.add(convert2Bo(csvRecord, HotelKpiManagerFlashCons.ARRIVAL_ROOMS, roundingMode));
                    } else if (fbAndOtherNames.contains(description.toLowerCase())) {
                        fbAndOtherRevenueList.add(convert2Bo(csvRecord, HotelKpiManagerFlashCons.TOTAL_REVENUE, roundingMode));
                    } else if (roomTypeNames.contains(description.toLowerCase())) {
                        roomRevenueList.add(convert2Bo(csvRecord, HotelKpiManagerFlashCons.ROOM_REVENUE, roundingMode));
                    } else if ("ROOM SOLD".equalsIgnoreCase(description)) {
                        boList.add(convert2Bo(csvRecord, HotelKpiManagerFlashCons.ROOMS_OCCUPIED, roundingMode));
                    } else if("ADR INCLUDING COMP, HOUSE USE ROOMS".equalsIgnoreCase(description)){
                         boList.add(convert2Bo(csvRecord, HotelKpiManagerFlashCons.ADR, roundingMode));
                     }
                }

                // category 去重，出现相同时取后面的一个元素
                if (CollectionUtils.isNotEmpty(boList)) {
                    boList = new ArrayList<>(boList.stream().collect(Collectors.toMap(HotelKpiManagerFlashBO::getCategory,
                                    v -> v, (a, b) -> b))
                            .values());
                }

                packageTotalRevenueBO(boList, fbAndOtherRevenueList, roomRevenueList);
                packageRoomRevenueBO(boList, roomRevenueList);

                return boList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Hotel KPI Manager Flash PEP report error.", e);
            }
        }

        /**
         * 转换为BO
         *
         * @param csvRecord    CSV数据行
         * @param category     类别
         * @param roundingMode 舍入模式
         * @return HotelKpiManagerFlashBO
         * @author yyt
         * @date 2026/2/7
         */
        private HotelKpiManagerFlashBO convert2Bo(CSVRecord csvRecord, String category, RoundingMode roundingMode) {
            HotelKpiManagerFlashBO managerFlashBO = new HotelKpiManagerFlashBO();
            managerFlashBO.setCategory(category);
            String recordDayStr = CsvFileUtils.getAndFormatNumber(csvRecord, "B");
            managerFlashBO.setDay(StringUtils.isEmpty(recordDayStr) ? null : new BigDecimal(recordDayStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));
            String recordMtdStr = CsvFileUtils.getAndFormatNumber(csvRecord, "C");
            managerFlashBO.setMtd(StringUtils.isEmpty(recordMtdStr) ? null : new BigDecimal(recordMtdStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));
            String recordYtdStr = CsvFileUtils.getAndFormatNumber(csvRecord, "E");
            managerFlashBO.setYtd(StringUtils.isEmpty(recordYtdStr) ? null : new BigDecimal(recordYtdStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));
            return managerFlashBO;
        }

        /**
         * 包装总收入BO
         *
         * @param boList                   总收入BO集合
         * @param fbAndOtherRevenueList    fbAndOtherRevenueList
         * @param roomRevenueList          roomRevenueList
         * @author yyt
         * @date 2026/2/7
         */
        private void packageTotalRevenueBO(List<HotelKpiManagerFlashBO> boList, List<HotelKpiManagerFlashBO> fbAndOtherRevenueList,
                                           List<HotelKpiManagerFlashBO> roomRevenueList) {
            if (CollectionUtils.isEmpty(fbAndOtherRevenueList) && CollectionUtils.isEmpty(roomRevenueList)) return;

            HotelKpiManagerFlashBO totalRevenueBO = new HotelKpiManagerFlashBO();
            totalRevenueBO.setCategory(HotelKpiManagerFlashCons.TOTAL_REVENUE);
            accumulateRevenue(totalRevenueBO, fbAndOtherRevenueList);
            accumulateRevenue(totalRevenueBO, roomRevenueList);
            boList.add(totalRevenueBO);
        }

        /**
         * 包装房间收入BO
         *
         * @param boList          房间收入BO集合
         * @param roomRevenueList 房间收入BO列表
         * @author yyt
         * @date 2026/2/7
         */
        private void packageRoomRevenueBO(List<HotelKpiManagerFlashBO> boList, List<HotelKpiManagerFlashBO> roomRevenueList) {
            if (CollectionUtils.isEmpty(roomRevenueList)) return;

            HotelKpiManagerFlashBO roomRevenueBO = new HotelKpiManagerFlashBO();
            roomRevenueBO.setCategory(HotelKpiManagerFlashCons.ROOM_REVENUE);
            accumulateRevenue(roomRevenueBO, roomRevenueList);
            boList.add(roomRevenueBO);
        }

        /**
         * 累加收入
         *
         * @param bo          hotelKpiManagerFlashBO
         * @param revenueList revenueList
         * @author yyt
         * @date 2026/2/7
         */
        private void accumulateRevenue(HotelKpiManagerFlashBO bo, List<HotelKpiManagerFlashBO> revenueList) {
            if (CollectionUtils.isEmpty(revenueList)) return;

            BigDecimal totalDay = bo.getDay();
            BigDecimal totalMtd = bo.getMtd();
            BigDecimal totalYtd = bo.getYtd();
            for (HotelKpiManagerFlashBO hotelKpiManagerFlashBO : revenueList) {
                // 累加 day、mtd、ytd 数据
                BigDecimal day = hotelKpiManagerFlashBO.getDay();
                if (Objects.nonNull(day)) {
                    totalDay = totalDay == null ? day : totalDay.add(day);
                }
                BigDecimal mtd = hotelKpiManagerFlashBO.getMtd();
                if (Objects.nonNull(mtd)) {
                    totalMtd = totalMtd == null ? mtd : totalMtd.add(mtd);
                }
                BigDecimal ytd = hotelKpiManagerFlashBO.getYtd();
                if (Objects.nonNull(ytd)) {
                    totalYtd = totalYtd == null ? ytd : totalYtd.add(ytd);
                }
            }
            bo.setDay(totalDay);
            bo.setMtd(totalMtd);
            bo.setYtd(totalYtd);
        }

    }