# RFNext14DaysParseByOther.java

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

    import cloud.wconnect.commonlib.cons.*;
    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.util.CellUtils;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.cons.revenue.RevenueErrorFiledCons;
    import cloud.wconnect.rateshop.cons.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueImportLog;
    import cloud.wconnect.rateshop.entity.revenue.RevenueMarketCode;
    import cloud.wconnect.rateshop.pojo.bo.revenue.MarketCodeBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ResolveExceptionDTO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueMarketCodeService;
    import cloud.wconnect.rateshop.service.revenue.report.IImportRevenueReport;
    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.format.DateTimeFormatter;
    import java.util.*;
    import java.util.stream.Collectors;

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

        @Resource
        private IRevenueReportCommonService revenueImportCommonService;
        @Resource
        private IRevenueMarketCodeService revenueMarketCodeService;
        @Resource
        private IRevenueImportService revenueImportService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

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

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

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

        private static final int FILE_TYPE = RevenueImportCons.RESERVATION_FORECAST_NEXT_14_DAYS;

        /**
         * 判断支持的平台
         *
         * @param source   平台
         * @param fileType 文件类型
         * @return boolean
         * @author yyt
         * @date 2024/8/14
         */
        @Override
        public boolean supports(String source, int fileType) {
            return SOURCE.equals(source) && FILE_TYPE == fileType;
        }

        /**
         * 检查文件
         *
         * @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"));

            // 获取当前资产配置的 market code
            List<RevenueMarketCode> marketCodes = revenueMarketCodeService.listEffiective(propertyDTO.getId());
            if (marketCodes.isEmpty()) {
                throw new BadRequestException(CommonErrorI18nConstant.NOT_FOUND,
                        i18nMessageUtils.getErrorParamMapNeedTranslate(RevenueErrorFiledCons.MARKET_CODE),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "Please configure market code first");
            }

            Map<Integer, List<String>> marketCodesByType = marketCodes.stream().collect(Collectors.groupingBy(RevenueMarketCode::getType,
                                    Collectors.mapping(RevenueMarketCode::getMarketCode, Collectors.toList())));

            try (InputStream in = file.getInputStream();
                 Workbook workbook = WorkbookFactory.create(in)) {
                checkSheetData(workbook.getSheetAt(0), marketCodesByType.getOrDefault(RevenueCons.TRANSIENT, Collections.emptyList()));
                checkSheetData(workbook.getSheetAt(1), marketCodesByType.getOrDefault(RevenueCons.GROUP, Collections.emptyList()));
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse file failed", e);
            }
        }

        /**
         * 检查 sheet
         *
         * @param sheet       sheet
         * @param marketCodes market code
         * @author yyt
         * @date 2024/8/16
         **/
        private void checkSheetData(Sheet sheet, List<String> marketCodes) {
            if (CollectionUtils.isEmpty(marketCodes)) {
                return;
            }

            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");
            }

            for (int i = 1; i < titleRow.getLastCellNum(); i++) {
                Cell cell = titleRow.getCell(i);
                String name = CellUtils.convertCellStr(cell);
                if (StringUtils.isEmpty(name)) {
                    continue;
                }

                if (!marketCodes.contains(name)) {
                    throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate(name),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The market code is not found;market code:" + name);
                }
            }

            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.getErrorParamMapNeedTranslate(CommonFieldI18nConstant.DATE),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The date must not be null");
                } else {
                    try {
                        LocalDate.parse(CellUtils.convertCellStr(dateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                    } catch (Exception e) {
                        LinkedHashMap<String, Boolean> map = new LinkedHashMap<>();
                        map.put(CommonFieldI18nConstant.DATE, true);
                        map.put(BaseConstant.DATE_FORMAT_YYYY_MM_DD,false);
                        throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                i18nMessageUtils.getErrorParamMap(map),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The date format error");
                    }
                }

                for (int j = 1; j < row.getLastCellNum(); j++) {
                    Cell roomsCell = row.getCell(j);
                    if (Objects.nonNull(roomsCell) && StringUtils.isNotBlank(roomsCell.toString())) {
                        BigDecimal rooms;
                        try {
                            rooms = new BigDecimal(CellUtils.convertCellStr(roomsCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNeedTranslate(RevenueErrorFiledCons.ROOMS),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rooms must be a number");
                        }
                        if (rooms.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNeedTranslate(RevenueErrorFiledCons.ROOMS, 6, 0),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rooms exceed the limit");
                        }
                    }
                }
            }
        }

        /**
         * 处理导入记录
         *
         * @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<MarketCodeBO> marketCodeBOS = parseFile(propertyDTO, inputStream, importLog.getStartDate(), importLog.getEndDate());
                revenueImportService.saveMarketCodeRooms(propertyDTO, importLog.getTheDate(), marketCodeBOS, 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 MarketCodeBO
         * @author yyt
         * @date 2024/8/16
         **/
        private List<MarketCodeBO> parseFile(PropertyDTO propertyDTO, InputStream inputStream, Long startDate, Long endDate) throws IOException {
            // 获取当前资产配置的 market code
            Map<Integer, Map<String, Integer>> marketCodesByType = revenueMarketCodeService.listEffiective(propertyDTO.getId())
                    .stream().collect(Collectors.groupingBy(RevenueMarketCode::getType,
                            Collectors.toMap(RevenueMarketCode::getMarketCode, RevenueMarketCode::getId)));

            List<MarketCodeBO> marketCodeBOS = Lists.newArrayList();
            Workbook workbook = WorkbookFactory.create(inputStream);
            parseSheetData(propertyDTO, workbook.getSheetAt(0), marketCodesByType.getOrDefault(RevenueCons.TRANSIENT, Collections.emptyMap()),
                    startDate, endDate, marketCodeBOS);
            parseSheetData(propertyDTO, workbook.getSheetAt(1), marketCodesByType.getOrDefault(RevenueCons.GROUP, Collections.emptyMap()),
                    startDate, endDate, marketCodeBOS);

            workbook.close();

            return marketCodeBOS;
        }

        /**
         * 解析 sheet
         *
         * @param propertyDTO        资产
         * @param sheet              sheet
         * @param marketCodeIdByName market code
         * @param startDate          开始日期
         * @param endDate            结束日期
         * @param marketCodeBOS      market code bo
         * @author yyt
         * @date 2024/8/16
         **/
        private void parseSheetData(PropertyDTO propertyDTO, Sheet sheet, Map<String, Integer> marketCodeIdByName,
                                    Long startDate, Long endDate, List<MarketCodeBO> marketCodeBOS) {
            if (marketCodeIdByName.isEmpty()) return;

            Row titelRow = sheet.getRow(0);
            Map<Integer, Integer> indexByMarketCodeId = Maps.newLinkedHashMapWithExpectedSize(titelRow.getLastCellNum());
            for (int i = 1; i < titelRow.getLastCellNum(); i++) {
                String marketCode = CellUtils.convertCellStr(titelRow.getCell(i));
                if (StringUtils.isEmpty(marketCode)) continue;

                indexByMarketCodeId.put(marketCodeIdByName.get(marketCode), i);
            }

            ZoneId zoneId = ZoneId.of(propertyDTO.getTimezone());
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                String date = CellUtils.convertCellStr(row.getCell(0), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                long targetDate = LocalDate.parse(date, dateTimeFormatter).atStartOfDay(zoneId).toEpochSecond();
                if (targetDate < startDate || targetDate > endDate) {
                    continue;
                }

                indexByMarketCodeId.forEach((marketCodeId, index) -> {
                    String rooms = CellUtils.convertCellStr(row.getCell(index));
                    marketCodeBOS.add(new MarketCodeBO(targetDate, marketCodeId, StringUtils.isBlank(rooms) ? BaseConstant.ZERO : Integer.parseInt(rooms)));
                });
            }
        }

    }