# HistoryAndForecastByOther.java

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

    import cloud.wconnect.commonlib.cons.*;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    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.*;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleHistoryAndForecastImportLog;
    import cloud.wconnect.workperformance.pojo.bo.schedule.ScheduleHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHistoryAndForecastImportLogService;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHistoryAndForecastService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.poi.ss.usermodel.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.multipart.MultipartFile;

    import jakarta.annotation.Resource;
    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.Objects;

    /**
     * History And Forecast By Other
     *
     * @author yyt
     * 2024/8/6
     */
    @Component
    @DS("work_performance")
    public class HistoryAndForecastByOther implements IHistoryAndForecastFileParse {

        @Resource
        private IScheduleHistoryAndForecastImportLogService scheduleHistoryAndForecastImportLogService;
        @Resource
        private IScheduleHistoryAndForecastService scheduleHistoryAndForecastService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

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

        private static final String SOURCE = SystemPlatformEnum.OTHER.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 (InputStream in = inputStream;Workbook workbook = WorkbookFactory.create(in)) {

                Sheet sheet = workbook.getSheetAt(0);
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    Cell dateCell = row.getCell(0);
                    LocalDate localDate = LocalDate.parse(CellUtils.convertCellStr(dateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                    long targetDate = DateTimeUtils.toTimestamp(localDate.atStartOfDay(ZoneId.of(timeZone)));
                    if (targetDate >= startDate && targetDate <= endDate) {
                        ScheduleHistoryAndForecastBO historyAndForecast = new ScheduleHistoryAndForecastBO();
                        historyAndForecast.setTargetDate(dateTimeFormatter.format(localDate));

                        Cell arrivalsCell = row.getCell(1);
                        historyAndForecast.setArrivalRooms(Integer.parseInt(CellUtils.convertCellStr(arrivalsCell)));

                        Cell departuresCell = row.getCell(2);
                        historyAndForecast.setDepartureRooms(Integer.parseInt(CellUtils.convertCellStr(departuresCell)));

                        Cell roomSoldCell = row.getCell(3);
                        historyAndForecast.setSoldRooms(Integer.parseInt(CellUtils.convertCellStr(roomSoldCell)));

                        Cell occCell = row.getCell(4);
                        historyAndForecast.setOcc(new BigDecimal(CellUtils.convertCellStr(occCell)).setScale(dataPrecision, roundingMode));

                        historyAndForecasts.add(historyAndForecast);
                    }
                }
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing file failed.", 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("xls", "xlsx"));

            try (InputStream in = file.getInputStream();Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                Row titleRow = sheet.getRow(0);
                if (Objects.isNull(titleRow)) {
                    throw new BadRequestException(CommonErrorI18nConstant.IMPORT_REPORT_NOT_REQUIRED,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The imported report is not the one required for the current functionality");
                }

                String dateTitle = CellUtils.convertCellStr(titleRow.getCell(0));
                String arrivalsTitle = CellUtils.convertCellStr(titleRow.getCell(1));
                String departuresTitle = CellUtils.convertCellStr(titleRow.getCell(2));
                String roomSoldTitle = CellUtils.convertCellStr(titleRow.getCell(3));
                String occTitle = CellUtils.convertCellStr(titleRow.getCell(4));
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    Cell dateCell = row.getCell(0);
                    if (Objects.isNull(dateCell) || StringUtils.isBlank(dateCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(dateTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The date cannot be empty");
                    } else {
                        // 格式必须 yyyy-MM-dd
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(dateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(dateTitle, BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The date format error");
                        }
                    }

                    Cell arrivalsCell = row.getCell(1);
                    if (Objects.isNull(arrivalsCell) || StringUtils.isBlank(arrivalsCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(arrivalsTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The arrivals cannot be empty");
                    } else {
                        BigDecimal arrivals;
                        try {
                            arrivals = new BigDecimal(CellUtils.convertCellStr(arrivalsCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(arrivalsTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The arrivals must be number");
                        }
                        // 不能小于0
                        if (arrivals.compareTo(BigDecimal.ZERO) < BaseConstant.ZERO) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(arrivalsTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The arrivals cannot be less than 0");
                        }
                        // 最多10位数
                        if (arrivals.toBigInteger().toString().length() > 9) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(arrivalsTitle, 10, 0),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The arrivals exceed the limit");
                        }
                    }

                    Cell departuresCell = row.getCell(2);
                    if (Objects.isNull(departuresCell) || StringUtils.isBlank(departuresCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(departuresTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The departures cannot be empty");
                    } else {
                        BigDecimal departures;
                        try {
                            departures = new BigDecimal(CellUtils.convertCellStr(departuresCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(departuresTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The departures must be number");
                        }
                        // 不能小于0
                        if (departures.compareTo(BigDecimal.ZERO) < BaseConstant.ZERO) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(departuresTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The departures cannot be less than 0");
                        }
                        // 最多10位数
                        if (departures.toBigInteger().toString().length() > 9) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(departuresTitle, 10, 0),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The departures exceed the limit");
                        }
                    }

                    Cell roomSoldCell = row.getCell(3);
                    if (Objects.isNull(roomSoldCell) || StringUtils.isBlank(roomSoldCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomSoldTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The rooms sold cannot be empty");
                    } else {
                        BigDecimal roomSold;
                        try {
                            roomSold = new BigDecimal(CellUtils.convertCellStr(roomSoldCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomSoldTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rooms sold must be number");
                        }
                        // 不能小于0
                        if (roomSold.compareTo(BigDecimal.ZERO) < BaseConstant.ZERO) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomSoldTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The room sold cannot be less than 0");
                        }
                        // 最多10位数
                        if (roomSold.toBigInteger().toString().length() > 9) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomSoldTitle, 10, 0),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rooms sold exceed the limit");
                        }
                    }

                    Cell occCell = row.getCell(4);
                    if (Objects.isNull(occCell) || StringUtils.isBlank(occCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(occTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The occ cannot be empty");
                    } else {
                        BigDecimal occ;
                        try {
                            occ = new BigDecimal(CellUtils.convertCellStr(occCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(occTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The occ must be number");
                        }
                        // 不能小于0
                        if (occ.compareTo(BigDecimal.ZERO) < BaseConstant.ZERO) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(occTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The occ cannot be less than 0");
                        }
                        // 整数7位数
                        if (occ.toBigInteger().toString().length() > 7) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(occTitle, 7),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The occ exceed the limit");
                        }
                    }
                }

            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(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);
                importLog.setImportResult(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
            }
            return importLog;
        }

        /**
         * 处理文件
         *
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2024/8/6
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file,
                               ScheduleHistoryAndForecastImportLog importLog, Integer userId) {
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                List<ScheduleHistoryAndForecastBO> historyAndForecasts = parsReport(importLog.getFromDate(),
                        importLog.getToDate(), inputStream, propertyDTO);
                if (CollectionUtils.isNotEmpty(historyAndForecasts)) {
                    // 处理数据
                    scheduleHistoryAndForecastService.handleHistoryAndForecastData(propertyDTO, historyAndForecasts);
                }
            } catch (Exception e) {
                importSuccess = false;
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse history and forecast report error", e);
            } finally {
                if (importSuccess) {
                    importSuccess(importLog, userId);
                } else {
                    importFail(importLog);
                }
            }
        }

        /**
         * 导入成功
         *
         * @param importLog 导入记录
         * @param userId    操作人
         * @author yyt
         * @date 2024/8/6
         **/
        private void importSuccess(ScheduleHistoryAndForecastImportLog importLog, int userId) {
            TransactionUtils.afterCommitSyncExecute(() -> {
                // 更新导入记录
                ScheduleHistoryAndForecastImportLog updateLog = new ScheduleHistoryAndForecastImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setImportResult(ReportImportResultCons.IMPORT_RESULT_SUCCESS);
                if (importLog.getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING) {
                    updateLog.setResolvedBy(userId).setResolvedTime(DateTimeUtils.nowTimestamp());
                }
                scheduleHistoryAndForecastImportLogService.updateById(updateLog);
            });
        }

        /**
         * 导入失败
         *
         * @param importLog 导入记录
         * @author yyt
         * @date 2024/8/6
         **/
        private void importFail(ScheduleHistoryAndForecastImportLog importLog) {
            TransactionUtils.afterCompletionRollbackSyncExecute(() -> {
                // 更新导入记录
                ScheduleHistoryAndForecastImportLog updateLog = new ScheduleHistoryAndForecastImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setImportResult(ReportImportResultCons.IMPORT_RESULT_FAIL);
                scheduleHistoryAndForecastImportLogService.updateById(updateLog);
            });
        }

    }