# OccJumpAlertHistoryAndForecastParseServiceByShiji.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.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.RoomsConfigDTO;
    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.revenue.HistoryAndForecastOccJumpAlertBO;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    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 java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Locale;
    import java.util.Objects;

    /**
     * 解析 Shiji 系统的 History And Forecast/Service -1,90d 报告
     */
    @Slf4j
    @Component
    @DS("rate_shop")
    public class OccJumpAlertHistoryAndForecastParseServiceByShiji implements IOccJumpAlertHistoryAndForecastParseService {
        @Resource
        private RoomsConfigInternalService roomsConfigInternalService;

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

        /**
         * 解析报告
         *
         * @param in        报告文件流
         * @param property  资产
         * @param startDate 数据日期，开始时间（时间戳）
         * @param endDate   数据日期，结束时间（时间戳）
         * @return HistoryAndForecastOccJumpAlertBO
         * @author zc
         * @date 2025/7/9
         */
        @Override
        public List<HistoryAndForecastOccJumpAlertBO> parse(InputStream in, PropertyDTO property, Long startDate, Long endDate) throws ParseReportException {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("EEE  MM/dd/yy", Locale.ENGLISH);
            String timezone = property.getTimezone();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(property
                    .getInternationalization().getNumber().getCalculationRule());

            // 获取 Revenue 房间数配置
            RoomsConfigDTO roomsConfigDTO = roomsConfigInternalService.getRoomsConfig(property.getId());
            Integer configTotalRooms = roomsConfigDTO.getRooms();
            Integer configOccRule = roomsConfigDTO.getOccRule();

            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<HistoryAndForecastOccJumpAlertBO> resultList = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = records.iterator();
                // 跳过第一行的标题行
                iterator.next();
                while (iterator.hasNext()) {
                    CSVRecord record = iterator.next();
                    String dateStr = ShijiFileCheckUtils.get(record, "A");
                    LocalDate dataLocalDate = LocalDate.parse(dateStr, dateTimeFormatter);
                    long targetDateTimestamp = DateTimeUtils.localDateToLong(dataLocalDate, timezone);
                    if (targetDateTimestamp >= startDate && targetDateTimestamp <= endDate) {
                        resultList.add(convert2Bo(dataLocalDate, record, configTotalRooms, configOccRule, roundingMode));
                    }
                    // 跳过 Individual
                    iterator.next();
                    // 跳过 Group
                    iterator.next();
                }
                return resultList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "source=SHIJI, parse [History and forecast/service] report error", e);
            }
        }

        /**
         * 转换为 BO
         *
         * @param dataLocalDate    数据日期
         * @param record           行数据
         * @param configTotalRooms 房间数配置
         * @param configOccRule    Occ 规则配置
         * @param roundingMode     舍入模式
         * @return HistoryAndForecastOccJumpAlertBO
         * @author zc
         * @date 2025/7/9
         */
        private HistoryAndForecastOccJumpAlertBO convert2Bo(LocalDate dataLocalDate, CSVRecord record, Integer configTotalRooms,
                                                            Integer configOccRule, RoundingMode roundingMode) {
            HistoryAndForecastOccJumpAlertBO bo = new HistoryAndForecastOccJumpAlertBO();
            bo.setDate(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

            // Total Occ.(Total Rooms Sold)
            String totalOccStr = ShijiFileCheckUtils.get(record, "B").replace(",", "");
            int totalOcc = StringUtils.isBlank(totalOccStr) ? 0 : Integer.parseInt(totalOccStr);
            bo.setRoomsSold(totalOcc);

            // OOO Rooms
            String oooRoomsStr = ShijiFileCheckUtils.get(record, "S").replace(",", "");
            int oooRooms = StringUtils.isBlank(oooRoomsStr) ? 0 : Integer.parseInt(oooRoomsStr);
            bo.setOooRooms(oooRooms);

            // 获取 PC occ
            // 如果配置了房间数，则根据 pc occ 计算规则判断：1.使用配置的房间数计算 pc occ，2.直接使用文件中的 occ 作为 pc occ
            if (Objects.nonNull(configTotalRooms) && configOccRule == RevenueCons.USE_ROOMS_TO_CALCULATE) {
                // pc occ = sold rooms / total rooms
                bo.setPcOcc(new BigDecimal(String.valueOf(totalOcc)).multiply(new BigDecimal("100"))
                        .divide(new BigDecimal(configTotalRooms), BaseConstant.DATA_PRECISION, roundingMode));
            } else {
                // OCC %
                String occPercentStr = ShijiFileCheckUtils.get(record, "E").replace(",", "");
                bo.setPcOcc(StringUtils.isEmpty(occPercentStr) ? null :
                        new BigDecimal(occPercentStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            }

            // 获取 SC occ
            if (Objects.nonNull(configTotalRooms)) {
                // sc occ = sold rooms / (total rooms - ooo rooms)
                int scRooms = configTotalRooms - oooRooms;
                if (scRooms != BaseConstant.ZERO) {
                    bo.setScOcc(new BigDecimal(String.valueOf(totalOcc)).multiply(new BigDecimal("100"))
                            .divide(BigDecimal.valueOf(scRooms), BaseConstant.DATA_PRECISION, roundingMode));
                }
            }
            return bo;
        }
    }