# GroupPickupParseByOther.java

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

    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.rateshop.cons.rateshop.BookingStatusForOperaGroupPicupEnum;
    import cloud.wconnect.rateshop.cons.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueImportLog;
    import cloud.wconnect.rateshop.pojo.bo.revenue.DailySummaryGroupPickupBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.HandleImportReportDTO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ResolveExceptionDTO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryGroupPickupService;
    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 jakarta.annotation.Resource;
    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.context.i18n.LocaleContextHolder;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.IOException;
    import java.io.InputStream;
    import java.time.format.DateTimeFormatter;
    import java.util.*;

    /**
     * 解析 Group Pickup 报告
     *
     * @author yyt
     * @date 2025/6/25
     */
    @Service
    @DS("rate_shop")
    public class GroupPickupParseByOther implements IImportRevenueReport {

        @Resource
        private IRevenueReportCommonService revenueImportCommonService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Autowired
        private IRevenueDailySummaryGroupPickupService revenueDailySummaryGroupPickupService;

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

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

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

        private static final int FILE_TYPE = RevenueImportCons.GROUP_PICKUP_YESTERDAY;

        /**
         * 判断支持的平台
         *
         * @param handleImportReportDTO 处理报告
         * @return boolean
         * @author yyt
         * @date 2025/6/25
         */
        @Override
        public boolean supports(HandleImportReportDTO handleImportReportDTO) {
            return SOURCE.equals(handleImportReportDTO.getSource()) && FILE_TYPE == handleImportReportDTO.getReportType();
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2025/6/25
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);

            //校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xlsx", "xls"));

            Locale locale = getLocale(file);

            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);
                String groupNameTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(titleRow, "A"));
                String bookingStatusTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(titleRow, "B"));
                String pickupTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(titleRow, "C"));

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

                    String groupName = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "A"));
                    if (StringUtils.isEmpty(groupName)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(groupNameTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The group name cannot be null");
                    } else {
                        if (groupName.length() > 255) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(groupNameTitle, 255),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The group name maximum length is 255");
                        }
                    }

                    String bookingStatusStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "B"));
                    if (StringUtils.isEmpty(bookingStatusStr)) {
                        //获取国际化的参数
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(bookingStatusTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The booking status cannot be null");
                    } else {
                        //预订状态集合
                        List<String> bookingStatusStrList = Arrays.stream(BookingStatusForOperaGroupPicupEnum.values())
                                .map(bookingStatusEnum -> i18nMessageUtils.message(bookingStatusEnum.getI18nCode(), locale))
                                .toList();
                        if (!bookingStatusStrList.contains(bookingStatusStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.INVALID_VALUE,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(bookingStatusTitle, StringUtils.join(bookingStatusStrList, ",")),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The booking status is not valid, booking status = " + bookingStatusStr);
                        }
                    }

                    String roomPickupStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "C"));
                    if (StringUtils.isNotBlank(roomPickupStr)) {
                        try {
                            Integer roomPickup = Integer.parseInt(roomPickupStr);
                            if (roomPickup < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(pickupTitle),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The actual number of rooms booked cannot be less than 0, roomPickupStr = " + roomPickupStr);
                            }
                            if (String.valueOf(roomPickup).length() > 6) {
                                throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(pickupTitle, 6),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The actual number of rooms booked exceed the limit");
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(pickupTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The actual number of rooms booked must integer, roomPickupStr = " + roomPickupStr);
                        }
                    }
                }

            } catch (IOException ioException) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse group booking error", ioException);
            }
        }

        /**
         * 获取当前语言标识，优先级：根据文件名后缀获取 > 当前上下文语言标识
         *
         * @param file 文件
         * @return Locale
         * @author yyt
         * @date 2025/6/25
         */
        private Locale getLocale(MultipartFile file){
            Locale locale;
            try {
                //从文件名中获取语言标识
                String originalFilename = file.getOriginalFilename();
                if (StringUtils.isEmpty(originalFilename)) return LocaleContextHolder.getLocale();
                // 去除文件后缀
                originalFilename = originalFilename.substring(0, originalFilename.length() - 5);
                // 获取文件名称的多语言标识
                String language = originalFilename.substring(originalFilename.length() - 5);
                locale = InternationalizationUtils.getLocale(language);
            }catch (Exception e){
                //从当前上下文中获取语言标识
                locale = LocaleContextHolder.getLocale();
            }
            return locale;
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO         资产
         * @param importLog           导入记录
         * @param resolveExceptionDTO 选择条件
         * @param file                文件
         * @param userId              操作人
         * @return RevenueImportLog
         * @author yyt
         * @date 2025/6/25
         */
        @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 2025/6/25
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file, RevenueImportLog importLog, Integer userId) {
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                String timezone = propertyDTO.getTimezone();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYYMMDD);
                Integer targetDate = Integer.parseInt(DateTimeUtils.longToLocalDate(importLog.getTheDate(), timezone).format(dateTimeFormatter));

                List<DailySummaryGroupPickupBO> groupPickupBOList = parseFile(inputStream, getLocale(file));

                revenueDailySummaryGroupPickupService.saveGroupPickupData(propertyDTO, targetDate, groupPickupBOList, 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 inputStream 文件流
         * @return group pickup
         * @author yyt
         * @date 2025/6/25
         */
        private List<DailySummaryGroupPickupBO> parseFile(InputStream inputStream, Locale locale) throws IOException {
            List<DailySummaryGroupPickupBO> groupPickupBOList = new ArrayList<>();
            Workbook workbook = WorkbookFactory.create(inputStream);

            Map<String, Integer> bookingStatusByStr = Maps.newHashMapWithExpectedSize(2);
            for (BookingStatusForOperaGroupPicupEnum bookingStatus : BookingStatusForOperaGroupPicupEnum.values()) {
                bookingStatusByStr.put(i18nMessageUtils.message(bookingStatus.getI18nCode(), locale), bookingStatus.getCode());
            }

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

                String groupNameStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "A"));
                String bookingStatusStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "B"));
                String pickupStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "C"));
                groupPickupBOList.add(DailySummaryGroupPickupBO.builder()
                        .groupName(groupNameStr)
                        .bookingStatus(bookingStatusByStr.get(bookingStatusStr))
                        .roomPickup(StringUtils.isEmpty(pickupStr) ? null : Integer.parseInt(pickupStr))
                        .build());
            }

            workbook.close();

            return groupPickupBOList;
        }

    }