# HotelKpiManagerFlashParseServiceByOther.java

    package cloud.wconnect.workperformance.service.hotelkpi.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.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.workperformance.cons.S3BucketFunctionCons;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiManagerFlashCons;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiTriggerTypeCons;
    import cloud.wconnect.workperformance.pojo.bo.hotelkpi.HotelKpiManagerFlashBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiCommonSummaryService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiImportLogService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiManagerFlashService;
    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.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.math.BigDecimal;
    import java.math.RoundingMode;
    import java.util.List;

    /**
     * 解析 Opera 系统的 Manager Flash/Service 报告
     *
     * @author zc
     * @date 2025/07/23
     */
    @Slf4j
    @Component
    @DS("work_performance")
    public class HotelKpiManagerFlashParseServiceByOther implements IHotelKpiManagerFlashParseService {
        @Resource
        private IHotelKpiManagerFlashService managerFlashService;
        @Resource
        private IHotelKpiCommonSummaryService commonSummaryService;
        @Resource
        private IHotelKpiImportLogService importLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

        @Value("${aws-s3.third-party.key.hotel-kpi.manager-flash}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.hotel-kpi}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2025/7/23
         */
        @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 <= 3; i++) {
                    titleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

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

                    // 校验 Description
                    String descriptionStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(descriptionStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Description cannot be blank");
                    }
                    for (int j = 1; j <= 3; j++) {
                        String recordStr = CellUtils.convertCellStr(row.getCell(j));
                        if (StringUtils.isBlank(recordStr)) {
                            continue;
                        }
                        BigDecimal recordValue;
                        try {
                            recordValue = new BigDecimal(recordStr);
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(j)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Record Value format is incorrect, Record Value = " + recordStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = recordValue.abs().toBigInteger().toString().length();
                        if (intLength > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(j), 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Record Value exceeds the limit, Record Value = " + recordStr);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check Hotel KPI Manager Flash Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author zc
         * @date 2025/7/23
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, List<Long> dateRange, 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.HOTEL_KPI_IMPORT_RECORD, file, s3Key);
                // 解析报告
                List<HotelKpiManagerFlashBO> boList = parse(propertyDTO, in);
                // 保存数据
                managerFlashService.insertOrUpdateBatch(propertyDTO.getId(), dateRange.get(0), boList);

                handleData(propertyDTO, dateRange.get(0));
            } catch (Exception e) {
                handleResult = false;
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Hotel KPI Manager Flash Other report error.", e);
            } finally {
                importLogService.update(logId, operatorId, s3Key, handleResult);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param reportDate  报告数据日期(yyyyMMdd)
         * @author zc
         * @date 2025/8/25
         */
        private void handleData(PropertyDTO propertyDTO, long reportDate) {
            List<Integer> metricsTypeList = Lists.newArrayList(HotelKpiMetricsEnum.OCC.getMetricsType(),
                    HotelKpiMetricsEnum.ADR.getMetricsType(), HotelKpiMetricsEnum.RM_REVENUE.getMetricsType(),
                    HotelKpiMetricsEnum.TOTAL_REVENUE.getMetricsType());
            for (int metricsType : metricsTypeList) {
                commonSummaryService.triggerSetMetricsData(propertyDTO, HotelKpiTriggerTypeCons.MANAGER_FLASH,
                        reportDate, reportDate, metricsType);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @return HotelKpiManagerFlashBO 集合
         * @author zc
         * @date 2025/7/23
         */
        @Override
        public List<HotelKpiManagerFlashBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            try (Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);

                List<HotelKpiManagerFlashBO> boList = Lists.newArrayList();
                // 获取最大行数
                int lastRowNum = sheet.getLastRowNum();
                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);
                    String descriptionStr = CellUtils.convertCellStr(row.getCell(0));
                    if ("Arrival Rooms".equalsIgnoreCase(descriptionStr)) {
                        boList.add(convert2Bo(row, HotelKpiManagerFlashCons.ARRIVAL_ROOMS, roundingMode));
                    } else if ("Total Revenue".equalsIgnoreCase(descriptionStr)) {
                        boList.add(convert2Bo(row, HotelKpiManagerFlashCons.TOTAL_REVENUE, roundingMode));
                    } else if ("Room Revenue".equalsIgnoreCase(descriptionStr)) {
                        boList.add(convert2Bo(row, HotelKpiManagerFlashCons.ROOM_REVENUE, roundingMode));
                    } else if ("Rooms Occupied".equalsIgnoreCase(descriptionStr)) {
                        boList.add(convert2Bo(row, HotelKpiManagerFlashCons.ROOMS_OCCUPIED, roundingMode));
                    } else if ("ADR".equalsIgnoreCase(descriptionStr)) {
                        boList.add(convert2Bo(row, HotelKpiManagerFlashCons.ADR, roundingMode));
                    }
                }
                return boList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Hotel KPI Manager Flash Other report error.", e);
            }
        }

        /**
         * 转换为 BO
         *
         * @param row          行数据
         * @param category     类别
         * @param roundingMode 舍入模式
         * @return HotelKpiManagerFlashBO
         * @author zc
         * @date 2025/7/24
         */
        private HotelKpiManagerFlashBO convert2Bo(Row row, String category, RoundingMode roundingMode) {
            HotelKpiManagerFlashBO managerFlashBO = new HotelKpiManagerFlashBO();
            managerFlashBO.setCategory(category);
            String recordDayStr = CellUtils.convertCellStr(row.getCell(1));
            managerFlashBO.setDay(StringUtils.isBlank(recordDayStr) ? null :
                    new BigDecimal(recordDayStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            String recordMtdStr = CellUtils.convertCellStr(row.getCell(2));
            managerFlashBO.setMtd(StringUtils.isBlank(recordMtdStr) ? null :
                    new BigDecimal(recordMtdStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            String recordYtdStr = CellUtils.convertCellStr(row.getCell(3));
            managerFlashBO.setYtd(StringUtils.isBlank(recordYtdStr) ? null :
                    new BigDecimal(recordYtdStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            return managerFlashBO;
        }
    }