# HistoryAndForecastByOpera.java

    package cloud.wconnect.workperformance.service.schedule.historyandforecast;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    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.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleHistoryAndForecastImportLog;
    import cloud.wconnect.workperformance.pojo.bo.schedule.ScheduleHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHandleReportService;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHistoryAndForecastImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import org.apache.commons.lang3.StringUtils;
    import org.dom4j.Document;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.io.SAXReader;
    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.List;
    import java.util.Locale;
    import java.util.Objects;

    /**
     * History And Forecast By Opera Auto
     *
     * @author yyt
     * 2023/7/4
     */
    @Component
    @DS("work_performance")
    public class HistoryAndForecastByOpera implements IHistoryAndForecastFileParse {

        @Resource
        private IScheduleHistoryAndForecastImportLogService scheduleHistoryAndForecastImportLogService;
        @Resource
        private IScheduleHandleReportService scheduleHandleReportService;

        @Value("${file-max-size.import-report.schedule}")
        private Long importReportFileMaxSize;

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

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

        /**
         * 解析报告数据
         *
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @param inputStream 文件流
         * @param propertyDTO  资产
         * @return history and forecast
         * @author yyt
         * @date 2023/7/4
         */
        @Override
        public List<ScheduleHistoryAndForecastBO> parsReport(Long startDate, Long endDate, InputStream inputStream,
                                                             PropertyDTO propertyDTO) {
            // 最多14天数据
            List<ScheduleHistoryAndForecastBO> historyAndForecasts = Lists.newArrayListWithExpectedSize(14);

            String timeZone = propertyDTO.getTimezone();
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            int dataPrecision = BaseConstant.DATA_PRECISION;
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            try {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
                DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                Document document = new SAXReader().read(inputStream);
                List<Node> nodes = document.selectNodes("//G_CONSIDERED_DATE");
                for (Node node : nodes) {
                    Element dataElement = (Element) node;
                    String consideredDate = dataElement.element("CONSIDERED_DATE").getTextTrim();
                    String[] consideredDateArr = StringUtils.split(consideredDate, "-");
                    consideredDateArr[1] = DateTimeUtils.capitalize(consideredDateArr[1]);
                    LocalDate localDate = LocalDate.parse(String.join("-", consideredDateArr), dateTimeFormatter);
                    long targetDate = DateTimeUtils.toTimestamp(localDate.atStartOfDay(ZoneId.of(timeZone)));
                    if (targetDate >= startDate && targetDate <= endDate) {
                        ScheduleHistoryAndForecastBO historyAndForecast = new ScheduleHistoryAndForecastBO();
                        historyAndForecast.setTargetDate(dateTimeFormatter2.format(localDate));

                        String totalOcc = dataElement.element("CF_CALC_OCC_ROOMS").getTextTrim();
                        historyAndForecast.setSoldRooms(StringUtils.isEmpty(totalOcc) ? 0 : Integer.parseInt(totalOcc));

                        String arrRooms = dataElement.element("ARRIVAL_ROOMS").getTextTrim();
                        historyAndForecast.setArrivalRooms(StringUtils.isEmpty(arrRooms) ? 0 : Integer.parseInt(arrRooms));

                        String occPercent = dataElement.element("CF_OCCUPANCY").getTextTrim();
                        historyAndForecast.setOcc(StringUtils.isEmpty(occPercent) ? BigDecimal.ZERO : new BigDecimal(occPercent)
                                .setScale(dataPrecision, roundingMode));

                        String depRooms = dataElement.element("DEPARTURE_ROOMS").getTextTrim();
                        historyAndForecast.setDepartureRooms(StringUtils.isEmpty(depRooms) ? 0 : Integer.parseInt(depRooms));
                        historyAndForecasts.add(historyAndForecast);
                    }
                }
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "parse history and forecast report error", e);
            }
            return historyAndForecasts;
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2024/8/6
         **/
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xml"));

            try (InputStream in = file.getInputStream()) {
                FileCheckUtils.checkHistoryAndForecastFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @param userId      操作人
         * @return 导入记录
         * @author yyt
         * @date 2024/8/6
         **/
        @Override
        public ScheduleHistoryAndForecastImportLog handleImportLog(PropertyDTO propertyDTO,
                                                                   ScheduleHistoryAndForecastImportLog importLog,
                                                                   Long theDate, Long startDate, Long endDate, int userId) {
            if (Objects.isNull(importLog)) {
                importLog = scheduleHistoryAndForecastImportLogService.saveRecord(propertyDTO.getId(), theDate, startDate,
                        endDate, ReportImportResultCons.IMPORT_IN_PROGRESS, userId);
            } else {
                // 更新异常为修复中
                ScheduleHistoryAndForecastImportLog updateContent = new ScheduleHistoryAndForecastImportLog();
                updateContent.setId(importLog.getId());
                updateContent.setImportResult(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
                scheduleHistoryAndForecastImportLogService.updateById(updateContent);
            }
            return importLog;
        }

        /**
         * 处理文件
         *
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2024/8/6
         **/
        @Override
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file, ScheduleHistoryAndForecastImportLog importLog, Integer userId) {
            scheduleHandleReportService.sendHistoryAndForecastEvent(propertyDTO, SystemPlatformEnum.OPERA.getDesc(), file, importLog, userId);
        }

    }