# WMRevenueHistoryAndForecastParseServiceByShiji.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    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.rateshop.pojo.bo.weeklymonthlyrevenue.WMRevenueHistoryAndForecastBO;
    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;

    /**
     * 解析 Shiji 系统的 History And Forecast/Service 报告
     *
     * @author zc
     * @date 2025/07/04
     */
    @Slf4j
    @Component
    @DS("rate_shop")
    public class WMRevenueHistoryAndForecastParseServiceByShiji implements IWMRevenueHistoryAndForecastParseService {

        @Resource
        private RoomsConfigInternalService roomsConfigInternalService;

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

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return WMRevenueHistoryAndForecastBO 集合
         * @author zc
         * @date 2025/7/4
         */
        @Override
        public List<WMRevenueHistoryAndForecastBO> 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<WMRevenueHistoryAndForecastBO> historyAndForecastBOList = 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;
                    }

                    historyAndForecastBOList.add(convert2Bo(dataLocalDate, record, iterator.next(),
                            iterator.next(), totalRooms, roundingMode));
                }
                return historyAndForecastBOList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Weekly Monthly Revenue 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 WMRevenueHistoryAndForecastBO
         * @author zc
         * @date 2025/5/21
         */
        private WMRevenueHistoryAndForecastBO convert2Bo(LocalDate dataLocalDate, CSVRecord recordTotal, CSVRecord recordIndividual,
                                                         CSVRecord recordGroup, int totalRooms, RoundingMode roundingMode) {
            WMRevenueHistoryAndForecastBO bo = new WMRevenueHistoryAndForecastBO();

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

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

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

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

            // OCC %
            String occPercentStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "E");
            bo.setOccupancy(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.setNumberOfPersons(numberOfAdults + numberOfChildren);

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

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

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

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

            // Inventory Rooms
            bo.setInventoryRooms(totalRooms);

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

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

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

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

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

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

            // Non-Deduct Individual
            bo.setNonDeductIndividual(0);

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

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

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

            // Non-Deduct Group
            bo.setNonDeductGroup(0);

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

            return bo;
        }

    }