# RateShopHistoryAndForecastServiceByShiji.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    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.EventBodyDTO;
    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.*;
    import cloud.wconnect.rateshop.cons.BusinessEnum;
    import cloud.wconnect.rateshop.cons.EventSubjectEnum;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.pojo.bo.rateshop.HistoryAndForecastForRateShopBO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.sns.http.processor.Sender;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    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.beans.factory.annotation.Qualifier;
    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.util.*;

    /**
     * 解析Shiji来源的History And Forecast报告
     *
     * @author lichen
     * @date 2025/7/4
     */
    @Component
    @DS("rate_shop")
    @Slf4j
    public class RateShopHistoryAndForecastServiceByShiji implements IRateShopHistoryAndForecastService {

        @Autowired
        private RoomsConfigInternalService roomsConfigInternalService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Value("${aws-s3.third-party.key.rate-shop.history-and-forecast}")
        private String s3FilePath;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        @Qualifier("3pSender")
        private Sender snsSender;
        @Value("${file-max-size.import-report.rate-shop}")
        private long fileMaxSize;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author lichen
         * @date 2025/7/4
         */
        @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.rateshop.messagelistener.HistoryAndForecastForRateShopDTO>
         * @author lichen
         * @date 2025/7/4
         */
        @Override
        public List<HistoryAndForecastForRateShopBO> parse(InputStream in, PropertyDTO propertyDTO, long startDate, long endDate) throws ParseReportException {
            // 获取国际化的配置
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            // 获取房间数配置
            RoomsConfigDTO roomsConfig = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId());
            Integer configTotalRooms = Objects.isNull(roomsConfig) ? null : roomsConfig.getRooms();

            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                ArrayList<HistoryAndForecastForRateShopBO> 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();

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

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

                    String formattedDateStr = DateTimeUtils.timestampToStr(dateTimestamp, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone());

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

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

                    // 获取 PC occ
                    BigDecimal pcOccPercent;
                    // 如果配置了房间数，则根据 pc occ 计算规则判断：1.使用配置的房间数计算 pc occ，2.直接使用文件中的 occ 作为 pc occ
                    if (Objects.nonNull(roomsConfig) && Objects.nonNull(roomsSold)
                            && (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE)) {
                        // pc occ = sold rooms / total rooms
                        pcOccPercent = BigDecimal.valueOf(roomsSold).multiply(BigDecimal.valueOf(100))
                                .divide(new BigDecimal(configTotalRooms), BaseConstant.DATA_PRECISION, roundingMode);
                    } else {
                        //入住率
                        String occupancyStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "E");
                        pcOccPercent = StringUtils.isEmpty(occupancyStr) ?
                                null : new BigDecimal(occupancyStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
                    }

                    // 获取 SC occ
                    BigDecimal scOccPercent = null;
                    if (Objects.nonNull(roomsConfig) && Objects.nonNull(roomsSold)) {
                        // sc occ = sold rooms / (total rooms - ooo rooms)
                        BigDecimal roomsSoldBigDecimal = BigDecimal.valueOf(roomsSold);
                        int denominator = configTotalRooms - subtractOooRooms;
                        if (denominator != BaseConstant.ZERO) {
                            scOccPercent = roomsSoldBigDecimal.multiply(BigDecimal.valueOf(100))
                                    .divide(BigDecimal.valueOf(denominator), BaseConstant.DATA_PRECISION, roundingMode);
                        } else {
                            scOccPercent = BigDecimal.ZERO;
                        }
                    }

                    //平均房价
                    String adrStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "P");
                    BigDecimal adr = StringUtils.isEmpty(adrStr) ? null : new BigDecimal(adrStr)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);

                    //获取散客房间数
                    CSVRecord individualRecord = iterator.next();
                    String individualDeductStr = ShijiFileCheckUtils.getAndFormatNumber(individualRecord, "F");
                    Integer individualDeduct = StringUtils.isEmpty(individualDeductStr) ? null : Integer.parseInt(individualDeductStr);

                    //获取团客房间数
                    CSVRecord groupRecord = iterator.next();
                    String groupDeductStr = ShijiFileCheckUtils.getAndFormatNumber(groupRecord, "F");
                    Integer groupDeduct = StringUtils.isEmpty(groupDeductStr) ? null : Integer.parseInt(groupDeductStr);

                    // 计算 Rooms Available = 资产总房间数 - Total Occ. - OOO Rooms
                    Integer roomsAvailable = Objects.nonNull(configTotalRooms) ?
                            (configTotalRooms - subtractRoomsSold - subtractOooRooms) : null;

                    resultList.add(HistoryAndForecastForRateShopBO.builder()
                            .date(formattedDateStr)
                            .roomsSold(roomsSold)
                            .transientSold(individualDeduct)
                            .groupSold(groupDeduct)
                            .pcOcc(pcOccPercent)
                            .scOcc(scOccPercent)
                            .adr(adr)
                            .oooRooms(oooRooms)
                            .roomsAvailable(roomsAvailable)
                            .build());
                }
                return resultList;
            } catch (IOException e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Parse Shiji [History And Forecast] report error", e);
            }
        }

        /**
         * 校验文件内容是否合法
         *
         * @param file 文件
         * @author lichen
         * @date 2025/7/4
         */
        @Override
        public void checkFile(MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            //校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            //校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                ShijiFileCheckUtils.checkHistoryAndForecast(inputStream);
            } catch (BadRequestException exception) {
                throw exception;
            } catch (Exception e2) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Check Shiji [History And Forecast] report error", e2);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param file        文件
         * @param startDate   开始时间整点时刻时间戳
         * @param endDate     结束时间整点时刻时间戳
         * @param logId       日志ID
         * @param userId      操作人ID
         * @return void
         * @author lichen
         * @date 2025/7/4
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, long startDate, long endDate, long logId, int userId) {
            try {
                String key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());
                // 上传报告到 S3 服务器，用于事件监听解析报告
                amazonS3Service.uploadFile(file, key);

                // 设置事件体
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(7);
                params.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), propertyDTO.getTenantSymbol());
                params.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), Lists.newArrayList(propertyDTO.getAbbr()));
                params.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.SHI_JI.getDesc());
                params.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.RATE_SHOP.getBusiness());
                params.put(EventBodyParamEnum.UID.getDesc(), userId);
                params.put(EventBodyParamEnum.ID.getDesc(), logId);
                params.put(EventBodyParamEnum.START_DATE.getDesc(), startDate);
                params.put(EventBodyParamEnum.END_DATE.getDesc(), endDate);

                snsSender.publish(EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_YESTERDAY_NINETY_DAY.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "handle shiji [History and Forecast] report error, send event exception", e);
            }
        }
    }