# TaOtaParseServiceByOther.java

    package cloud.wconnect.finance.service.ta.ota;

    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.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.finance.cons.S3BucketFunctionCons;
    import cloud.wconnect.finance.pojo.bo.ta.ota.TaOtaBO;
    import cloud.wconnect.finance.pojo.bo.ta.ota.TaOtaListBO;
    import cloud.wconnect.finance.pojo.dto.ta.compare.TaCompareOtaRateCodeDTO;
    import cloud.wconnect.finance.service.AmazonS3Service;
    import cloud.wconnect.finance.service.ta.ITaCompareOtaRateCodeConfigService;
    import cloud.wconnect.finance.service.ta.ITaCompareOtaService;
    import cloud.wconnect.finance.service.ta.ITaImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    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.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.IOException;
    import java.io.InputStream;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeParseException;
    import java.util.List;
    import java.util.Locale;
    import java.util.stream.Collectors;

    /**
     * 解析 OTA Other 报告
     *
     * @author zc
     * @date 2023/07/19
     */
    @Slf4j
    @Component
    @DS("finance")
    public class TaOtaParseServiceByOther implements ITaOtaParseService {
        @Resource
        private ITaCompareOtaRateCodeConfigService rateCodeConfigService;
        @Resource
        private ITaCompareOtaService compareOtaService;
        @Resource
        private ITaImportLogService importLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

        @Value("${aws-s3.third-party.key.ta-commission.ota}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.ta}")
        private long fileMaxSize;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2023/7/19
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OTHER.getDesc().equals(source);
        }

        /**
         * 校验文件是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2024/8/21
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            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;
                }

                // 提取标题
                List<String> titleList = Lists.newArrayList();
                Row titleRow = sheet.getRow(0);
                for (int i = 0; i <= 9; i++) {
                    titleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);

                    // Arrival Date
                    String arrivalDateStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(arrivalDateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Arrival Date cannot be blank");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(arrivalDateStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Arrival Date format is incorrect, Arrival Date = " + arrivalDateStr);
                        }
                    }

                    // Departure Date
                    String departureDateStr = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isBlank(departureDateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Departure Date cannot be blank");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(departureDateStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Departure Date format is incorrect, Departure Date = " + departureDateStr);
                        }
                    }

                    // Guest Name
                    String guestNameStr = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isBlank(guestNameStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Guest Name cannot be blank");
                    } else {
                        if (guestNameStr.length() > 200) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2), 200),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Guest Name cannot be longer than 200 characters");
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check TA OTA Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param date        报告数据日期(时间戳)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author zc
         * @date 2024/8/21
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, long date, long logId, int operatorId) {
            // 处理是否成功
            boolean handleResult = true;
            // 获取报告 S3 Key
            String s3Key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                    + UploadUtils.getRandomFileName(file.getOriginalFilename());

            try (InputStream in = file.getInputStream()) {
                // 上传报告到 S3，用于导入记录下载报告
                amazonS3Service.uploadFile(S3BucketFunctionCons.TA_IMPORT_RECORD, file, s3Key);

                // 解析报告
                List<TaOtaListBO> taOtaList = parse(propertyDTO, in);

                TaOtaBO taOtaBO = TaOtaBO.builder()
                        .dataDate(DateTimeUtils.timestampToStr(date, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone()))
                        .list(taOtaList).build();
                // 处理报告
                compareOtaService.handleOtaReport(propertyDTO, taOtaBO);
            } catch (Exception e) {
                handleResult = false;
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import OTA Other report error.", e);
            } finally {
                importLogService.update(logId, handleResult, operatorId, s3Key);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          文件流
         * @return TaOtaListBO 集合
         * @author zc
         * @date 2023/7/19
         */
        @Override
        public List<TaOtaListBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            // 获取过滤条件
            List<String> otaRateCodeList = rateCodeConfigService.list(propertyDTO.getId()).stream()
                    .map(TaCompareOtaRateCodeDTO::getRateCode).collect(Collectors.toList());
            try(Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                // 获取最大行数
                int lastRowNum = sheet.getLastRowNum();

                List<TaOtaListBO> taOtaList = Lists.newArrayList();
                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);

                    String rateCodeStr = CellUtils.convertCellStr(row.getCell(3));
                    if (CollectionUtils.isNotEmpty(otaRateCodeList)
                            && !otaRateCodeList.contains(rateCodeStr)) {
                        continue;
                    }

                    TaOtaListBO taOta = new TaOtaListBO();
                    taOta.setArrivalDay(CellUtils.convertCellStr(row.getCell(0)));
                    taOta.setDepartureDay(CellUtils.convertCellStr(row.getCell(1)));
                    taOta.setName(CellUtils.convertCellStr(row.getCell(2)));

                    taOtaList.add(taOta);
                }
                return taOtaList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse TA OTA Other report error.", e);
            }
        }
    }