# RateShopHistoryAndForecastServiceByOpera.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.lang3.StringUtils;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.io.SAXReader;
    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.InputStream;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.util.*;

    /**
     * 解析 Opera 系统的 History And Forecast/Service 报告
     */
    @Slf4j
    @Component
    @DS("rate_shop")
    public class RateShopHistoryAndForecastServiceByOpera 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 2023/6/15
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OPERA.getDesc().equals(source);
        }

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产
         * @param startDate   数据日期，开始时间(整点时刻时间戳)
         * @param endDate     数据日期，结束时间(整点时刻时间戳)
         * @return HistoryAndForecastForRateShopDTO
         * @author zc
         * @date 2024/3/23
         */
        @Override
        public List<HistoryAndForecastForRateShopBO> parse(InputStream in, PropertyDTO propertyDTO, long startDate, long endDate) throws ParseReportException {
            try {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
                ZoneId zoneId = ZoneId.of(propertyDTO.getTimezone());

                // 获取国际化的配置
                InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_CONSIDERED_DATE");

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

                List<HistoryAndForecastForRateShopBO> resultList = Lists.newArrayListWithCapacity(nodes.size());
                for (Node node : nodes) {
                    Element dataElement = (Element) node;

                    // 获取数据日期
                    String consideredDateStr = dataElement.element("CONSIDERED_DATE").getTextTrim();
                    String[] consideredDateArr = StringUtils.split(consideredDateStr, "-");
                    consideredDateArr[1] = DateTimeUtils.capitalize(consideredDateArr[1]);
                    LocalDate localDate = LocalDate.parse(String.join("-", consideredDateArr), dateTimeFormatter);
                    long consideredDate = DateTimeUtils.toTimestamp(localDate.atStartOfDay(zoneId));

                    // 判断数据日期是否在开始日期 和 结束日期之间
                    if (consideredDate < startDate || consideredDate > endDate) continue;

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

                    // 获取 Total occ
                    String totalOccStr = dataElement.elementTextTrim("CF_CALC_OCC_ROOMS");
                    Integer totalOcc = StringUtils.isEmpty(totalOccStr) ? null : Integer.parseInt(totalOccStr);
                    int subtractTotalOcc = Optional.ofNullable(totalOcc).orElse(BaseConstant.ZERO);

                    // 获取 OOO Rooms
                    String oooRoomsStr = dataElement.elementTextTrim("CF_OOO_ROOMS");
                    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(totalOcc)
                            && (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE)) {
                        // pc occ = sold rooms / total rooms
                        BigDecimal totalOccBD = BigDecimal.valueOf(totalOcc);
                        pcOccPercent = totalOccBD.multiply(BigDecimal.valueOf(100))
                                .divide(new BigDecimal(configTotalRooms), BaseConstant.DATA_PRECISION, roundingMode);
                    } else {
                        String occPercentStr = dataElement.elementTextTrim("CF_OCCUPANCY");
                        pcOccPercent = StringUtils.isEmpty(occPercentStr) ?
                                null : new BigDecimal(occPercentStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
                    }

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

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

                    // 获取 ADR
                    String adrStr = dataElement.element("CF_AVERAGE_ROOM_RATE").getTextTrim();
                    BigDecimal adr = StringUtils.isEmpty(adrStr) ? null : new BigDecimal(adrStr)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);

                    // 获取 Deduct Ind.
                    String deductIndStr = dataElement.element("IND_DEDUCT_ROOMS").getTextTrim();
                    Integer deductInd = StringUtils.isEmpty(deductIndStr) ? null : Integer.parseInt(deductIndStr);

                    // 获取 Deduct Group
                    String deductGroupStr = dataElement.element("GRP_DEDUCT_ROOMS").getTextTrim();
                    Integer deductGroup = StringUtils.isEmpty(deductGroupStr) ? null : Integer.parseInt(deductGroupStr);

                    resultList.add(HistoryAndForecastForRateShopBO.builder()
                            .date(formattedDateStr)
                            .roomsSold(totalOcc)
                            .transientSold(deductInd)
                            .groupSold(deductGroup)
                            .pcOcc(pcOccPercent)
                            .scOcc(scOccPercent)
                            .adr(adr)
                            .oooRooms(oooRooms)
                            .roomsAvailable(roomsAvailable)
                            .build());
                }
                return resultList;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.INTERNAL_SERVICE_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.INTERNAL_SERVICE_ERROR.getCode(),
                        "source=opera, parse [History and forecast/service] report error", e);
            }
        }

        /**
         * 校验文件内容是否合法
         *
         * @param file 文件
         * @author lichen
         * @date 2024/8/14
         */
        @Override
        public void checkFile(MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xml"));
            try (InputStream inputStream = file.getInputStream()) {
                FileCheckUtils.checkHistoryAndForecastFile(inputStream);
            } catch (BadRequestException exception) {
                throw exception;
            } catch (Exception ioException) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse [History and forecast/service] report error", ioException);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param file        文件
         * @param startDate   开始时间整点时刻时间戳
         * @param endDate     结束时间整点时刻时间戳
         * @param logId       日志ID
         * @param userId      操作人ID
         * @return void
         * @author lichen
         * @date 2024/8/14
         */
        @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.OPERA.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 history-and-forecast/service report, send event exception", e);
            }
        }

    }