# RFNext90DaysParseByOther.java

    package cloud.wconnect.rateshop.service.revenue.report.reservationforecast.next90days;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.CellUtils;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.rateshop.cons.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueImportLog;
    import cloud.wconnect.rateshop.entity.revenue.RevenueSegment;
    import cloud.wconnect.rateshop.pojo.bo.revenue.RoomsAndRevenueBO;
    import cloud.wconnect.rateshop.pojo.bo.revenue.SegmentBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.HandleImportReportDTO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ResolveExceptionDTO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueSegmentService;
    import cloud.wconnect.rateshop.service.revenue.report.IImportRevenueReport;
    import cloud.wconnect.rateshop.service.revenue.report.IParseRevenueExcelService;
    import cloud.wconnect.rateshop.service.revenue.report.IRevenueReportCommonService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    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.Service;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.multipart.MultipartFile;

    import jakarta.annotation.Resource;
    import java.io.IOException;
    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.stream.Collectors;

    /**
     * @author: yyt
     * 2024-08-14
     */
    @Service
    @DS("rate_shop")
    public class RFNext90DaysParseByOther implements IImportRevenueReport {

        @Resource
        private IRevenueReportCommonService revenueImportCommonService;
        @Resource
        private IParseRevenueExcelService parseRevenueExcelService;
        @Resource
        private IRevenueImportService revenueImportService;
        @Autowired
        private IRevenueSegmentService revenueSegmentService;

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

        @Value("${aws-s3.third-party.key.revenue.reservation-forecast-next-90-days}")
        private String s3Key;

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

        private static final int FILE_TYPE = RevenueImportCons.RESERVATION_FORECAST_NEXT_90_DAYS;

        /**
         * 判断支持的平台
         *
         * @param handleImportReportDTO 处理报告
         * @return boolean
         * @author yyt
         * @date 2024/8/14
         */
        @Override
        public boolean supports(HandleImportReportDTO handleImportReportDTO) {
            return SOURCE.equals(handleImportReportDTO.getSource()) && FILE_TYPE == handleImportReportDTO.getReportType();
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2024/8/14
         **/
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);

            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xls", "xlsx"));

            parseRevenueExcelService.checkSegmentFile(propertyDTO, file);
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO         资产
         * @param importLog           导入记录
         * @param resolveExceptionDTO 选择条件
         * @param file                文件
         * @param userId              操作人
         * @return 导入记录
         * @author yyt
         * @date 2024/8/14
         **/
        @Override
        public RevenueImportLog handleImportLog(PropertyDTO propertyDTO, RevenueImportLog importLog,
                                                ResolveExceptionDTO resolveExceptionDTO, MultipartFile file, int userId) {
            return revenueImportCommonService.handleImportLog(propertyDTO, importLog, resolveExceptionDTO, s3Key, file, userId);
        }

        /**
         * 处理文件
         *
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2024/8/14
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file, RevenueImportLog importLog, Integer userId) {
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                List<SegmentBO> segmentBOList = parseFile(propertyDTO, inputStream, importLog.getStartDate(), importLog.getEndDate());
                if (CollectionUtils.isEmpty(segmentBOList)) {
                    return;
                }

                revenueImportService.saveForecastNext90DaysSegmentData(propertyDTO, segmentBOList, segmentBOList, userId);
            } catch (Exception e) {
                importSuccess = false;
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse report error", e);
            } finally {
                revenueImportCommonService.updateImportStatus(importLog, importSuccess, userId);
            }
        }

        /**
         * 解下文件
         *
         * @param propertyDTO 资产
         * @param inputStream 文件
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @return SegmentBO
         * @author yyt
         * @date 2024/8/17
         **/
        private List<SegmentBO> parseFile(PropertyDTO propertyDTO, InputStream inputStream, Long startDate, Long endDate) throws IOException {
            Integer propertyId = propertyDTO.getId();
            List<RevenueSegment> segments = revenueSegmentService.listActiveSegment(propertyId);
            if (segments.isEmpty()) {
                return Collections.emptyList();
            }

            Map<String, Integer> segmentIdByName = segments.stream()
                    .collect(Collectors.toMap(RevenueSegment::getSegment, RevenueSegment::getId));

            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Row titelRow = sheet.getRow(0);
            Map<Integer, Integer> indexBySegmentId = Maps.newLinkedHashMapWithExpectedSize(titelRow.getLastCellNum());
            for (int i = 1; i < titelRow.getLastCellNum(); i++) {
                Cell cell = titelRow.getCell(i);
                String name = CellUtils.convertCellStr(cell);
                Integer segmentId = segmentIdByName.get(name);
                indexBySegmentId.put(segmentId, i);
                // 连续跨 2 列
                i++;
            }

            String timezone = propertyDTO.getTimezone();
            ZoneId zoneId = ZoneId.of(timezone);
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_TIME_FORMAT_SLASH);
            // 最多 90 天
            List<SegmentBO> segmentBOList = Lists.newArrayListWithExpectedSize(90);
            for (int i = 2; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                String date = CellUtils.convertCellStr(row.getCell(0), BaseConstant.DATE_TIME_FORMAT_SLASH);
                if (StringUtils.isEmpty(date)) {
                    continue;
                }
                long targetDate = LocalDate.parse(date, dateTimeFormatter).atStartOfDay(zoneId).toEpochSecond();
                if (targetDate < startDate || targetDate > endDate) {
                    continue;
                }

                List<RoomsAndRevenueBO> details = Lists.newArrayListWithExpectedSize(indexBySegmentId.size());
                indexBySegmentId.forEach((segmentId, index) -> {
                    String rooms = CellUtils.convertCellStr(row.getCell(index));
                    String revenue = CellUtils.convertCellStr(row.getCell(index + 1));
                    details.add(new RoomsAndRevenueBO(segmentId, StringUtils.isEmpty(rooms) ? BaseConstant.ZERO : Integer.parseInt(rooms),
                            StringUtils.isEmpty(revenue) ? BigDecimal.ZERO : new BigDecimal(revenue)));
                });

                segmentBOList.add(new SegmentBO(StringUtils.replace(date, "/", "-"), details));
            }

            // 处理选择日期内，文件中没有对应日期的数据的情况，统一设置默认值0，跟自动导入报告的逻辑保持一致
            List<Integer> segmentIds = segments.stream().map(RevenueSegment::getId).toList();
            Map<String, SegmentBO> segmentBOByDate = segmentBOList.stream().collect(Collectors.toMap(SegmentBO::getDate, v -> v));
            ZonedDateTime startDateZoneDateTime = DateTimeUtils.toZonedDateTime(startDate, timezone);
            ZonedDateTime endDateZoneDateTime = DateTimeUtils.toZonedDateTime(endDate, timezone);
            DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            for (ZonedDateTime everyDay = startDateZoneDateTime; !everyDay.isAfter(endDateZoneDateTime); everyDay = everyDay.plusDays(1)) {
                String date = everyDay.format(dateTimeFormatter2);
                SegmentBO segmentBO = segmentBOByDate.get(date);
                if (Objects.isNull(segmentBO)) {
                    segmentBO = new SegmentBO();
                    segmentBO.setDate(date);
                    segmentBO.setDetail(segmentIds.stream().map(item -> new RoomsAndRevenueBO(item, BaseConstant.ZERO, BigDecimal.ZERO)).toList());
                    segmentBOList.add(segmentBO);
                } else {
                    List<RoomsAndRevenueBO> detail = segmentBO.getDetail();
                    Map<Integer, RoomsAndRevenueBO> roomsAndRevenueBOSegmentId = detail.stream().collect(Collectors.toMap(RoomsAndRevenueBO::getId, v -> v));
                    segmentIds.forEach(segmentId -> {
                        int totalRooms = 0;
                        BigDecimal totalRevenue = BigDecimal.ZERO;
                        RoomsAndRevenueBO roomsAndRevenueBO = roomsAndRevenueBOSegmentId.get(segmentId);
                        if (Objects.isNull(roomsAndRevenueBO)) {
                            detail.add(new RoomsAndRevenueBO(segmentId, totalRooms, totalRevenue));
                        }
                    });
                    segmentBO.setDetail(detail);
                }
            }

            workbook.close();

            return segmentBOList;
        }

    }