# DbPmsHfParseServiceByShiji.java

    package cloud.wconnect.workperformance.service.database.historyforecast;

    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.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.RoomsConfigInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.entity.database.DbReportImportLog;
    import cloud.wconnect.workperformance.pojo.bo.database.historyforecast.DbPmsHfBO;
    import cloud.wconnect.workperformance.service.database.IDbReportService;
    import com.google.common.collect.Lists;
    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.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Locale;

    /**
     * 解析 Shiji History and Forecast/Service 报告
     *
     * @author zc
     * @date 2026/1/5
     */
    @Component
    public class DbPmsHfParseServiceByShiji implements IDbPmsHfParseService {
        private final IDbReportService reportService;
        private final RoomsConfigInternalService roomsConfigInternalService;

        public DbPmsHfParseServiceByShiji(IDbReportService reportService, RoomsConfigInternalService roomsConfigInternalService) {
            this.roomsConfigInternalService = roomsConfigInternalService;
            this.reportService = reportService;
        }

        @Value("${aws-s3.third-party.key.database.history-and-forecast}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.database}")
        private long fileMaxSize;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2026/1/5
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.SHI_JI.getDesc().equals(source);
        }

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2026/1/5
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                ShijiFileCheckUtils.checkHistoryAndForecast(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Database History and forecast Shiji report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2026/1/5
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, DbReportImportLog importLog, int operatorId) {
            reportService.sendReportEvent(propertyDTO, file, importLog, operatorId, s3FilePath,
                    EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_LAST_2_DAY_TO_365_DAY.getSubject());
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return List<DbPmsHfBO> 集合
         * @author zc
         * @date 2026/1/5
         */
        @Override
        public List<DbPmsHfBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("EEE  MM/dd/yy", Locale.ENGLISH);
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            int totalRooms = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId()).getRooms();
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<DbPmsHfBO> boList = 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 targetDate = Long.parseLong(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (targetDate < startDate || targetDate > endDate) {
                        // 跳过 Individual
                        iterator.next();
                        // 跳过 Group
                        iterator.next();
                        continue;
                    }

                    boList.add(convert2Bo(dataLocalDate, record, iterator.next(),
                            iterator.next(), totalRooms, roundingMode));
                }
                return boList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Database History and forecast Shiji report error.", e);
            }
        }

        /**
         * 将报告中的信息转换为实体类
         *
         * @param dataLocalDate    数据日期
         * @param recordTotal      CSVRecord Total
         * @param recordIndividual CSVRecord Individual
         * @param recordGroup      CSVRecord Group
         * @param totalRooms       总房间数
         * @param roundingMode     舍入模式
         * @return PmsHfBO
         * @author zc
         * @date 2026/1/5
         */
        private DbPmsHfBO convert2Bo(LocalDate dataLocalDate, CSVRecord recordTotal, CSVRecord recordIndividual,
                                     CSVRecord recordGroup, int totalRooms, RoundingMode roundingMode) {
            DbPmsHfBO bo = new DbPmsHfBO();

            bo.setDStr(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

            // Total Occ.(Total Rooms Sold)
            String totalOccStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "B");
            bo.setRs(StringUtils.isBlank(totalOccStr) ? 0 : Integer.parseInt(totalOccStr));

            // Arrival Rooms
            String arrivalRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "C");
            bo.setArr(StringUtils.isBlank(arrivalRoomsStr) ? 0 : Integer.parseInt(arrivalRoomsStr));

            // Departure Rooms
            String departureRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "D");
            bo.setDep(StringUtils.isBlank(departureRoomsStr) ? 0 : Integer.parseInt(departureRoomsStr));

            // OCC %
            String occPercentStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "E");
            bo.setOcc(StringUtils.isBlank(occPercentStr) ? null : new BigDecimal(occPercentStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // Number of Persons
            String adultsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "K");
            int numberOfAdults = StringUtils.isBlank(adultsStr) ? 0 : Integer.parseInt(adultsStr);
            String childrenStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "L");
            int numberOfChildren = StringUtils.isBlank(childrenStr) ? 0 : Integer.parseInt(childrenStr);
            bo.setGu(numberOfAdults + numberOfChildren);

            // Room Revenue
            String revenueStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "N");
            bo.setRr(StringUtils.isBlank(revenueStr) ? null : new BigDecimal(revenueStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // ADR
            String adrStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "P");
            bo.setAdr(StringUtils.isBlank(adrStr) ? null : new BigDecimal(adrStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // No Show Rooms
            String noShowRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "R");
            bo.setNs(StringUtils.isBlank(noShowRoomsStr) ? 0 : Integer.parseInt(noShowRoomsStr));

            // OOO Rooms
            String oooRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "S");
            bo.setOoo(StringUtils.isBlank(oooRoomsStr) ? 0 : Integer.parseInt(oooRoomsStr));

            // Inventory Rooms
            bo.setIr(totalRooms);

            // Sell Inventory Rooms
            int sellInventoryRooms = totalRooms - bo.getOoo();
            bo.setSir(Math.max(sellInventoryRooms, 0));

            // Complimentary Rooms
            String complimentaryRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "U");
            bo.setCom(StringUtils.isBlank(complimentaryRoomsStr) ? 0 : Integer.parseInt(complimentaryRoomsStr));

            // House Use Rooms
            String houseUseRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "V");
            bo.setHu(StringUtils.isBlank(houseUseRoomsStr) ? 0 : Integer.parseInt(houseUseRoomsStr));

            // Day Use Rooms
            String dayUseRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "W");
            bo.setDu(StringUtils.isBlank(dayUseRoomsStr) ? 0 : Integer.parseInt(dayUseRoomsStr));

            // Deduct Individual
            String deductIndividualStr = ShijiFileCheckUtils.getAndFormatNumber(recordIndividual, "F");
            bo.setDis(StringUtils.isBlank(deductIndividualStr) ? 0 : Integer.parseInt(deductIndividualStr));

            // Deduct Individual Revenue
            String deductIndividualRevenueStr = ShijiFileCheckUtils.getAndFormatNumber(recordIndividual, "N");
            bo.setDir(StringUtils.isBlank(deductIndividualRevenueStr) ? null : new BigDecimal(deductIndividualRevenueStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // Non-Deduct Individual
            String nonDeductIndividualStr = ShijiFileCheckUtils.getAndFormatNumber(recordIndividual, "H");
            bo.setNdis(StringUtils.isBlank(nonDeductIndividualStr) ? 0 : Integer.parseInt(nonDeductIndividualStr));

            // Non-Deduct Individual Revenue
            bo.setNdir(BigDecimal.ZERO);

            // Deduct Group
            String deductGroupStr = ShijiFileCheckUtils.getAndFormatNumber(recordGroup, "F");
            bo.setDgs(StringUtils.isBlank(deductGroupStr) ? 0 : Integer.parseInt(deductGroupStr));

            // Deduct Group Revenue
            String deductGroupRevenueStr = ShijiFileCheckUtils.getAndFormatNumber(recordGroup, "N");
            bo.setDgr(StringUtils.isBlank(deductGroupRevenueStr) ? null : new BigDecimal(deductGroupRevenueStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // Non-Deduct Group
            String nonDeductGroupStr = ShijiFileCheckUtils.getAndFormatNumber(recordGroup, "H");
            bo.setNdgs(StringUtils.isBlank(nonDeductGroupStr) ? 0 : Integer.parseInt(nonDeductGroupStr));

            // Non-Deduct Group Revenue
            bo.setNdgr(BigDecimal.ZERO);

            return bo;
        }
    }