# MarketCodeParseByOther.java

    package cloud.wconnect.rateshop.service.revenue.report.marketcode;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    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.RevenueErrorFiledCons;
    import cloud.wconnect.rateshop.cons.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueDailySummaryTaFilterConfig;
    import cloud.wconnect.rateshop.entity.revenue.RevenueImportLog;
    import cloud.wconnect.rateshop.pojo.bo.revenue.RoomDayBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ResolveExceptionDTO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryTaFilterConfigService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryTaService;
    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 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.util.List;
    import java.util.Objects;

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

        @Resource
        private IRevenueDailySummaryTaFilterConfigService revenueDailySummaryTaFilterConfigService;
        @Resource
        private IRevenueReportCommonService revenueImportCommonService;
        @Resource
        private IRevenueDailySummaryTaService revenueDailySummaryTaService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

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

        @Value("${aws-s3.third-party.key.revenue.market-code}")
        private String s3Key;

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

        private static final int FILE_TYPE = RevenueImportCons.MARKET_CODE;

        /**
         * 判断支持的平台
         *
         * @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"));

            List<String> marketCodes = revenueDailySummaryTaFilterConfigService.listByPropertyId(propertyDTO.getId())
                    .stream().map(RevenueDailySummaryTaFilterConfig::getMarketCode).toList();
            if (CollectionUtils.isEmpty(marketCodes)) {
                throw new BadRequestException(CommonErrorI18nConstant.NOT_FOUND,
                        i18nMessageUtils.getErrorParamMapNeedTranslate(RevenueErrorFiledCons.MARKET_CODE),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "Please configure market code first");
            }

            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 lengthOfStayTitle = CellUtils.convertCellStr(titleRow.getCell(1));

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

                    Cell marketCodeCell = row.getCell(0);
                    if (Objects.isNull(marketCodeCell) || StringUtils.isBlank(marketCodeCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNeedTranslate(RevenueErrorFiledCons.MARKET_CODE),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The market code cannot be empty");
                    } else {
                        if (!marketCodes.contains(CellUtils.convertCellStr(marketCodeCell))) {
                            throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(marketCodeCell.toString()),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The market code does not exist");
                        }
                    }

                    Cell lengthOfStayCell = row.getCell(1);
                    if (Objects.nonNull(lengthOfStayCell) && StringUtils.isNotBlank(lengthOfStayCell.toString())) {
                        BigDecimal lengthOfStay;
                        try {
                            lengthOfStay = new BigDecimal(CellUtils.convertCellStr(lengthOfStayCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(lengthOfStayTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The length of stay must be a number");
                        }
                        if (lengthOfStay.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(lengthOfStayTitle, 6, 0),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The length of stay 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 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()) {
                int lengthOfStay = parseFile(inputStream);
                revenueDailySummaryTaService.saveOrUpdate(propertyDTO, Lists.newArrayList(new RoomDayBO(importLog.getStartDate(), lengthOfStay)));
            } 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 inputStream 文件流
         * @return 入住天数
         * @author yyt
         * @date 2024/8/15
         **/
        private int parseFile(InputStream inputStream) throws IOException {
            int lengthOfStay = 0;
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (Objects.isNull(row)) {
                    continue;
                }

                String roomsDayStr = CellUtils.convertCellStr(row.getCell(1));
                lengthOfStay += StringUtils.isEmpty(roomsDayStr) ? BaseConstant.ZERO : Integer.parseInt(roomsDayStr);
            }

            workbook.close();

            return lengthOfStay;
        }

    }