# HistoryAndForecastListenerFileServiceByShiji.java

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

    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.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.RoomsConfigDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.service.RoomsConfigInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.ShijiFileCheckUtils;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.pojo.bo.rateshop.HistoryAndForecastForRateShopBO;
    import cloud.wconnect.rateshop.service.rateshop.IPropertyOperationService;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopOccForecastService;
    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.stereotype.Component;
    import org.springframework.transaction.annotation.Transactional;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.util.*;

    /**
     * 解析Shiji来源的History And Forecast报告
     *
     * @author lichen
     * @date 2025/7/4
     */
    @RequiredArgsConstructor
    @Component
    @DS("rate_shop")
    @Slf4j
    public class HistoryAndForecastListenerFileServiceByShiji implements IHistoryAndForecastListenerFileService {

        private final RoomsConfigInternalService roomsConfigInternalService;
        private final IPropertyOperationService propertyOperationService;
        private final IRateShopOccForecastService rateShopOccForecastService;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author lichen
         * @date 2025/7/4
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.SHI_JI.getDesc().equals(source);
        }

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产DTO
         * @param startDate   数据日期，开始时间(整点时刻时间戳)
         * @param endDate     数据日期，结束时间(整点时刻时间戳)
         * @return java.util.List<cloud.wconnect.rateshop.pojo.dto.rateshop.messagelistener.HistoryAndForecastForRateShopDTO>
         * @author lichen
         * @date 2025/7/4
         */
        @Override
        public List<HistoryAndForecastForRateShopBO> parse(InputStream in, PropertyDTO propertyDTO, long startDate, long endDate) throws ParseReportException {
            // 获取国际化的配置
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            // 获取房间数配置
            RoomsConfigDTO roomsConfig = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId());
            Integer configTotalRooms = Objects.isNull(roomsConfig) ? null : roomsConfig.getRooms();

            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                ArrayList<HistoryAndForecastForRateShopBO> resultList = Lists.newArrayList();

                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = iterable.iterator();

                //跳过第一行标题行
                iterator.next();

                while (iterator.hasNext()) {
                    CSVRecord csvRecord = iterator.next();

                    //日期格式Wed  07/02/25
                    String dateStr = ShijiFileCheckUtils.get(csvRecord, "A");
                    String[] split = dateStr.split("  ");
                    long dateTimestamp = DateTimeUtils.dateStrToEpochSecond(split[1], BaseConstant.DATE_TIME_FORMAT_MM_DD_YY, propertyDTO.getTimezone());

                    // 判断数据日期是否在开始日期 和 结束日期之间
                    if (dateTimestamp < startDate || dateTimestamp > endDate) {
                        iterator.next();
                        iterator.next();
                        continue;
                    }

                    String formattedDateStr = DateTimeUtils.timestampToStr(dateTimestamp, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone());

                    //已售房间数
                    String roomsSoldStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "B");
                    Integer roomsSold = StringUtils.isEmpty(roomsSoldStr) ? null : Integer.parseInt(roomsSoldStr);
                    int subtractRoomsSold = Optional.ofNullable(roomsSold).orElse(BaseConstant.ZERO);

                    //故障房
                    String oooRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "S");
                    Integer oooRooms = StringUtils.isEmpty(oooRoomsStr) ? null : Integer.parseInt(oooRoomsStr);
                    int subtractOooRooms = Optional.ofNullable(oooRooms).orElse(BaseConstant.ZERO);

                    // 获取 PC occ
                    BigDecimal pcOccPercent;
                    // 如果配置了房间数，则根据 pc occ 计算规则判断：1.使用配置的房间数计算 pc occ，2.直接使用文件中的 occ 作为 pc occ
                    if (Objects.nonNull(roomsConfig) && Objects.nonNull(roomsSold)
                            && (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE)) {
                        // pc occ = sold rooms / total rooms
                        pcOccPercent = BigDecimal.valueOf(roomsSold).multiply(BigDecimal.valueOf(100))
                                .divide(new BigDecimal(configTotalRooms), BaseConstant.DATA_PRECISION, roundingMode);
                    } else {
                        //入住率
                        String occupancyStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "E");
                        pcOccPercent = StringUtils.isEmpty(occupancyStr) ?
                                null : new BigDecimal(occupancyStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
                    }

                    // 获取 SC occ
                    BigDecimal scOccPercent = null;
                    if (Objects.nonNull(roomsConfig) && Objects.nonNull(roomsSold)) {
                        // sc occ = sold rooms / (total rooms - ooo rooms)
                        BigDecimal roomsSoldBigDecimal = BigDecimal.valueOf(roomsSold);
                        int denominator = configTotalRooms - subtractOooRooms;
                        if (denominator != BaseConstant.ZERO) {
                            scOccPercent = roomsSoldBigDecimal.multiply(BigDecimal.valueOf(100))
                                    .divide(BigDecimal.valueOf(denominator), BaseConstant.DATA_PRECISION, roundingMode);
                        } else {
                            scOccPercent = BigDecimal.ZERO;
                        }
                    }

                    //平均房价
                    String adrStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "P");
                    BigDecimal adr = StringUtils.isEmpty(adrStr) ? null : new BigDecimal(adrStr)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);

                    //获取散客房间数
                    CSVRecord individualRecord = iterator.next();
                    String individualDeductStr = ShijiFileCheckUtils.getAndFormatNumber(individualRecord, "F");
                    Integer individualDeduct = StringUtils.isEmpty(individualDeductStr) ? null : Integer.parseInt(individualDeductStr);

                    //获取团客房间数
                    CSVRecord groupRecord = iterator.next();
                    String groupDeductStr = ShijiFileCheckUtils.getAndFormatNumber(groupRecord, "F");
                    Integer groupDeduct = StringUtils.isEmpty(groupDeductStr) ? null : Integer.parseInt(groupDeductStr);

                    // 计算 Rooms Available = 资产总房间数 - Total Occ. - OOO Rooms
                    Integer roomsAvailable = Objects.nonNull(configTotalRooms) ?
                            (configTotalRooms - subtractRoomsSold - subtractOooRooms) : null;

                    resultList.add(HistoryAndForecastForRateShopBO.builder()
                            .date(formattedDateStr)
                            .roomsSold(roomsSold)
                            .transientSold(individualDeduct)
                            .groupSold(groupDeduct)
                            .pcOcc(pcOccPercent)
                            .scOcc(scOccPercent)
                            .adr(adr)
                            .oooRooms(oooRooms)
                            .roomsAvailable(roomsAvailable)
                            .build());
                }
                return resultList;
            } catch (IOException e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Parse Shiji [History And Forecast] report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param boList      报告数据
         * @param operatorId  操作人 id
         * @author yyt
         * @date 2026/3/10
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void saveReportData(PropertyDTO propertyDTO, List<HistoryAndForecastForRateShopBO> boList, int operatorId) {
            // 保存数据
            propertyOperationService.saveHistoryAndForecastReportData(propertyDTO, operatorId, boList);
            // 保存occ数据
            rateShopOccForecastService.saveOccForecast(propertyDTO, operatorId, boList);
        }

    }