# DailySummaryHistoryAndForecastParseImplByShiji.java

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

    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.entity.revenue.RevenueAdrConfig;
    import cloud.wconnect.rateshop.pojo.dto.revenue.HistoryAndForecastDailySummaryDTO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueAdrConfigService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    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.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

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

    /**
     * History And Forecast Shiji来源报告解析
     *
     * @author lichen
     * @date 2025/7/5
     */
    @Service
    @Slf4j
    @DS("rate_shop")
    public class DailySummaryHistoryAndForecastParseImplByShiji implements IDailySummaryHistoryAndForecastParse {

        @Autowired
        private RoomsConfigInternalService roomsConfigInternalService;
        @Autowired
        private IRevenueAdrConfigService revenueAdrConfigService;

        /**
         * 支持的报告来源
         *
         * @param source 来源
         * @return boolean
         * @author lichen
         * @date 2025/7/5
         */
        @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.revenue.HistoryAndForecastDailySummaryDTO>
         * @author lichen
         * @date 2025/7/5
         */
        @Override
        public List<HistoryAndForecastDailySummaryDTO> parse(InputStream in, PropertyDTO propertyDTO, Long startDate, Long endDate) throws ParseReportException {
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                // 获取房间数配置
                RoomsConfigDTO roomsConfig = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId());
                Integer rooms = roomsConfig.getRooms();

                //资产配置的规则
                RevenueAdrConfig revenueAdrConfig = revenueAdrConfigService.get(propertyDTO.getId());
                boolean checkTransientDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckTransientDeduct();
                boolean checkGroupDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckGroupDeduct();

                InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());
                BigDecimal oneHundred = BigDecimal.valueOf(100L);

                ArrayList<HistoryAndForecastDailySummaryDTO> 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();
                    HistoryAndForecastDailySummaryDTO historyAndForecastDailySummaryDTO = new HistoryAndForecastDailySummaryDTO();

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

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

                    //小时数
                    int hour = DateTimeUtils.dateTimeNow(propertyDTO.getTimezone()).getHour();
                    historyAndForecastDailySummaryDTO.setTheHour(hour);
                    //同步时间
                    historyAndForecastDailySummaryDTO.setSyncTime(DateTimeUtils.nowTimestamp());

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

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

                    //获取散客房间数
                    CSVRecord individualRecord = iterator.next();
                    String individualDeductStr = ShijiFileCheckUtils.getAndFormatNumber(individualRecord, "F");
                    // 如果勾选了 individual non deduct，则累加未交订金的 individual 房间数
                    int individualDeduct = 0;
                    if (checkTransientDeduct && StringUtils.isNotEmpty(individualDeductStr)) {
                        individualDeduct = Integer.parseInt(individualDeductStr);
                    }
                    historyAndForecastDailySummaryDTO.setTransientRooms(individualDeduct);

                    //获取团客房间数
                    CSVRecord groupRecord = iterator.next();
                    String groupDeductStr = ShijiFileCheckUtils.getAndFormatNumber(groupRecord, "F");
                    // 如果勾选了 Group deduct，则累加交订金的 Group 房间数
                    int groupDeduct = 0;
                    if (checkGroupDeduct && StringUtils.isNotEmpty(groupDeductStr)) {
                        groupDeduct = Integer.parseInt(groupDeductStr);
                    }
                    historyAndForecastDailySummaryDTO.setGroupRooms(groupDeduct);

                    historyAndForecastDailySummaryDTO.setTotalRoomsSold(individualDeduct + groupDeduct);

                    // 计算 Rooms Available = 配置的房间数 - 入住房间数 - 故障房间数
                    Integer roomsAvailable = Objects.nonNull(rooms) ?
                            (rooms - subtractRoomsSold - subtractOooRooms) : null;
                    historyAndForecastDailySummaryDTO.setRoomsAvailable(roomsAvailable);

                    // 设置 occ，根据 occ 的配置规则判断：1.使用配置的房间数计算 occ，2.直接使用文件中的 occ
                    if (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE) {
                        if (StringUtils.isNotEmpty(roomsSoldStr)) {
                            //  Occ. % = total occ rooms / 总房间数
                            BigDecimal occPercent = new BigDecimal(roomsSoldStr).multiply(oneHundred)
                                    .divide(BigDecimal.valueOf(rooms), BaseConstant.DATA_PRECISION, roundingMode);
                            historyAndForecastDailySummaryDTO.setOcc(occPercent);
                        }
                    } else {
                        //入住率
                        String occupancyStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "E");
                        BigDecimal occPercent = StringUtils.isEmpty(occupancyStr) ?
                                null : new BigDecimal(occupancyStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
                        historyAndForecastDailySummaryDTO.setOcc(occPercent);
                    }

                    resultList.add(historyAndForecastDailySummaryDTO);
                }
                return resultList;
            } catch (IOException e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Shiji [History And Forecast] report error", e);
            }
        }
    }