# ManagerFlashParseByOther.java

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

    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.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.rateshop.cons.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueImportLog;
    import cloud.wconnect.rateshop.pojo.bo.revenue.ManagerFlashBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ManagerFlashDTO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ResolveExceptionDTO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryManagerFlashService;
    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.lang3.StringUtils;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    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.math.RoundingMode;
    import java.util.*;

    /**
     * Manager Flash报告处理
     *
     * @author lichen
     * @date 2025/1/11
     */
    @Service
    @DS("rate_shop")
    public class ManagerFlashParseByOther implements IImportRevenueReport {

        @Resource
        private IRevenueReportCommonService revenueImportCommonService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Autowired
        private IRevenueDailySummaryManagerFlashService revenueDailySummaryManagerFlashService;

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

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

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

        private static final int FILE_TYPE = RevenueImportCons.MANAGER_FLASH;

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

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @return void
         * @author lichen
         * @date 2025/1/11
         */
        @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);
                //获取最大行数
                int lastRowNum = sheet.getLastRowNum();
                //只包含标题
                if (lastRowNum < 1) return;

                //标题行
                Row titleRow = sheet.getRow(0);
                //标题集合
                ArrayList<String> titles = Lists.newArrayList();
                for (int i = 0; i < 3; i++) {
                    titles.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

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

                    //ADR
                    String adrStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isEmpty(adrStr)) {
                        //获取国际化的参数
                        Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(0));
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY, language2ParamList,
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The ADR cannot be null");
                    } else {
                        BigDecimal adr;
                        try {
                            adr = new BigDecimal(adrStr);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(0)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The ADR must be a number");
                        }

                        //校验整数位是否超过限制
                        int intLength = adr.toBigInteger().toString().length();
                        if (intLength > 10) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(0), "10");
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of ADR exceeds the limit, adrStr  = " + adrStr);
                        }
                    }

                    //客人未来的房间数
                    String noShowRooms = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isEmpty(noShowRooms)) {
                        //获取国际化的参数
                        Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(1));
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY, language2ParamList,
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The no show rooms cannot be null");
                    } else {
                        try {
                            Integer.valueOf(noShowRooms);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(1)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The no show rooms must be integer");
                        }
                    }

                    //客人取消的房间数
                    String cancelled = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isEmpty(cancelled)) {
                        //获取国际化的参数
                        Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(2));
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY, language2ParamList,
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The cancelled cannot be null");
                    } else {
                        try {
                            Integer.valueOf(cancelled);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(2)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The cancelled must be integer");
                        }
                    }
                }
            } 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 cloud.wconnect.rateshop.entity.revenue.RevenueImportLog
         * @author lichen
         * @date 2025/1/11
         */
        @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      操作人
         * @return void
         * @author lichen
         * @date 2025/1/11
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file, RevenueImportLog importLog, Integer userId) {
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                ManagerFlashDTO managerFlashDTO = parseFile(propertyDTO, inputStream);
                if(Objects.nonNull(managerFlashDTO)){
                    ManagerFlashBO managerFlashBO = ManagerFlashBO.builder()
                            .adr(managerFlashDTO.getAdr())
                            .noShow(managerFlashDTO.getNoShow())
                            .cancelled(managerFlashDTO.getCancelled())
                            .theDate(importLog.getStartDate())
                            .build();
                    revenueDailySummaryManagerFlashService.saveOrUpdate(propertyDTO, Collections.singletonList(managerFlashBO));
                }
            } 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 资产DTO
         * @param inputStream 文件流
         * @return cloud.wconnect.rateshop.pojo.dto.revenue.ManagerFlashDTO
         * @author lichen
         * @date 2025/1/11
         */
        private ManagerFlashDTO parseFile(PropertyDTO propertyDTO, InputStream inputStream) throws IOException {
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Row row = sheet.getRow(1);

            if(Objects.isNull(row)) return null;

            //ADR
            String adrStr = CellUtils.convertCellStr(row.getCell(0));
            BigDecimal adr = new BigDecimal(adrStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            //No Show Rooms
            String noShow = CellUtils.convertCellStr(row.getCell(1));
            //Cancelled
            String cancelled = CellUtils.convertCellStr(row.getCell(2));

            ManagerFlashDTO managerFlashDTO = new ManagerFlashDTO();
            managerFlashDTO.setAdr(adr);
            managerFlashDTO.setNoShow(Integer.valueOf(noShow));
            managerFlashDTO.setCancelled(Integer.valueOf(cancelled));
            return managerFlashDTO;
        }

    }