# HFHistoryDataListenerFileParseByShiJiImpl.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.ShijiFileCheckUtils;
    import cloud.wconnect.rateshop.pojo.bo.revenue.HistoryAndForecastBO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    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.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.format.DateTimeFormatter;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;

    /**
     * @author yyt
     * 2025/7/4
     */
    @RequiredArgsConstructor
    @Service
    @DS("rate_shop")
    public class HFHistoryDataListenerFileParseByShiJiImpl implements IHFHistoryDataListenerFileParse {

        private final IRevenueImportService revenueImportService;

        private static final String SOURCE = SystemPlatformEnum.SHI_JI.getDesc();

        /**
         * 判断支持的平台
         *
         * @param source 平台
         * @return boolean
         * @author yyt
         * @date 2025/7/4
         */
        @Override
        public boolean supports(String source) {
            return SOURCE.equals(source);
        }

        /**
         * 解析 History and Forecast 报告数据
         *
         * @param propertyDTO 资产
         * @param in          文件流
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @return java.util.List<cloud.wconnect.rateshop.pojo.bo.revenue.HistoryAndForecastBO>
         * @author yyt
         * @date 2026/3/3
         */
        @Override
        public List<HistoryAndForecastBO> 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();

            // 最多31天数据
            List<HistoryAndForecastBO> historyAndForecastBOS = Lists.newArrayListWithExpectedSize(31);
            String timeZone = propertyDTO.getTimezone();
            DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            // 先加载所有行
            List<CSVRecord> allRows = Lists.newArrayListWithExpectedSize(104 * 3);
            records.forEach(record -> {
                // 跳过第一行的标题
                if (record.getRecordNumber() == 1) {
                    return;
                }
                allRows.add(record);
            });

            for (int i = 0; i < allRows.size(); i+=3) {
                CSVRecord record = allRows.get(i);
                // 空行
                if (record.size() == BaseConstant.ZERO) continue;

                // 解析每天数据
                String date = ShijiFileCheckUtils.get(record, "A");
                if (StringUtils.isEmpty(date)) continue;
                String dateStr = date.substring(date.length() - 8);
                if (StringUtils.isEmpty(dateStr)) continue;
                long dataDate = DateTimeUtils.dateStrToEpochSecond(dateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY, timeZone);
                if (dataDate < startDate || dataDate > endDate) {
                    continue;
                }

                HistoryAndForecastBO historyAndForecastBO = new HistoryAndForecastBO();
                historyAndForecastBO.setTargetDate(DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY).format(dateTimeFormatter2));

                String occPercentStr = ShijiFileCheckUtils.getAndFormatNumber(record, "E");
                if (StringUtils.isNotEmpty(occPercentStr)) {
                    historyAndForecastBO.setOccPercent(new BigDecimal(occPercentStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
                }

                // 如果勾选了 Transient deduct，则累加交订金的 Transient 房间数
                CSVRecord transientRecord = allRows.get(i + 1);
                String transientRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(transientRecord, "F");
                if (StringUtils.isNotEmpty(transientRoomsStr)) {
                    historyAndForecastBO.setTransientRoomNum(Integer.valueOf(transientRoomsStr));
                }

                CSVRecord groupRecord = allRows.get(i + 2);
                // 如果勾选了 Group deduct，则累加交订金的 Group 房间数
                String groupRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(groupRecord, "F");
                if (StringUtils.isNotEmpty(groupRoomsStr)) {
                    historyAndForecastBO.setGroupRoomNum(Integer.valueOf(groupRoomsStr));
                }

                String adrStr = ShijiFileCheckUtils.getAndFormatNumber(record, "P");
                if (StringUtils.isNotEmpty(adrStr)) {
                    historyAndForecastBO.setAdr(new BigDecimal(adrStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
                }
                historyAndForecastBOS.add(historyAndForecastBO);

                // 提前结束循环
                if (dataDate == endDate) {
                    break;
                }
            }
            return historyAndForecastBOS;
        }

        /**
         * 保存报告数据
         *
         * @param propertyDTO 资产
         * @param boList      报告数据
         * @param operatorId  操作人
         * @author yyt
         * @date 2026/3/3
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void saveReportData(PropertyDTO propertyDTO, List<HistoryAndForecastBO> boList, int operatorId) {
            revenueImportService.saveHistoryAndForecastData(propertyDTO, boList, operatorId);
        }

    }