# RateShopGroupPickupServiceByShiji.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    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.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.rateshop.cons.BusinessEnum;
    import cloud.wconnect.rateshop.cons.EventSubjectEnum;
    import cloud.wconnect.rateshop.cons.rateshop.BookingStatusEnum;
    import cloud.wconnect.rateshop.pojo.bo.rateshop.GroupPickupBO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.sns.http.processor.Sender;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.codec.digest.DigestUtils;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    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.io.InputStreamReader;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.util.*;

    /**
     * 解析 Shiji Group Pickup 报告
     *
     * @author zc
     * @date 2026/02/05
     */
    @Slf4j
    @Component
    @DS("rate_shop")
    public class RateShopGroupPickupServiceByShiji implements IRateShopGroupPickupService {

        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        @Qualifier("3pSender")
        private Sender snsSender;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Value("${aws-s3.third-party.key.rate-shop.group-pickup}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.rate-shop}")
        private long fileMaxSize;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2026/2/5
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.SHI_JI.getDesc().equals(source);
        }

        /**
         * 检查文件
         *
         * @param file        文件
         * @author zc
         * @date 2026/2/5
         */
        @Override
        public void checkFile(MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                ShijiFileCheckUtils.checkGroupPickup(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Group Pickup Shiji report error", e);
            }
        }

        /**
         * 解析报告
         *
         * @param in                  报告文件流
         * @param propertyDTO         资产
         * @param startDate           数据日期，开始时间（整点时间戳）
         * @param endDate             数据日期，结束时间（整点时间戳）
         * @param bookingStatusLocale 解析预订状态的语言标识(解析Other报告时，用户可以自主选择系统支持的语言模板)
         * @return 报告数据
         * @author zc
         * @date 2024/3/22
         */
        @Override
        public List<GroupPickupBO> parse(InputStream in, PropertyDTO propertyDTO, long startDate, long endDate,
                                         Locale bookingStatusLocale) throws ParseReportException {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            String timezone = propertyDTO.getTimezone();

            String groupTarget = "Group Name:";
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                // 读取所有记录到List
                List<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader).getRecords();
                int i = 1;

                Map<String, GroupPickupBO> sign2BoMap = Maps.newHashMap();

                while (i < records.size()) {
                    CSVRecord titleRecord_1 = records.get(i);
                    String colA = CsvFileUtils.get(titleRecord_1, "A");
                    if (!groupTarget.equals(colA)) {
                        i++;
                        continue;
                    }

                    // 跳过 "Group Name:" 行
                    i++;
                    CSVRecord titleRecord_2 = records.get(i);

                    // 获取 Booking Status
                    String bookingStatusStr = CsvFileUtils.get(titleRecord_2, "K");
                    if (StringUtils.isBlank(bookingStatusStr)) {
                        i++;
                        continue;
                    }
                    // 转换为 Booking Status Code
                    int bookingStatus = BookingStatusEnum.getCodeBySymbol(bookingStatusStr);
                    // 忽略无效的 Booking Status
                    if (bookingStatus == BaseConstant.ZERO) {
                        i++;
                        continue;
                    }

                    // 获取 Group Name
                    String groupNameStr = CsvFileUtils.get(titleRecord_2, "A");

                    // 跳过标题行
                    i += 5;

                    // 处理数据行，直到遇到下一个分组
                    while (i < records.size()) {
                        CSVRecord dataRecord = records.get(i);

                        // 检查是否到了下一个分组（A列是"Group Name:"）
                        String nextColA = CsvFileUtils.get(dataRecord, "A");
                        if (groupTarget.equals(nextColA)) {
                            break; // 不增加i，让外层循环处理
                        }

                        // 跳过空日期的数据行
                        if (StringUtils.isBlank(nextColA)) {
                            i++;
                            continue;
                        }

                        // 忽略掉非指定日期的数据
                        long dateTimestamp = DateTimeUtils.dateStrToEpochSecond(nextColA,
                                BaseConstant.DATE_TIME_FORMAT_MM_DD_YY, timezone);
                        if (dateTimestamp < startDate || dateTimestamp > endDate) {
                            i++;
                            continue;
                        }

                        // 格式化日期为 yyyy-MM-dd
                        String formattedDateStr = DateTimeUtils.timestampToStr(dateTimestamp,
                                BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone());

                        // 累加当前数据行的数据
                        BigDecimal totalSingleRate = parseDecimal(dataRecord, "H", roundingMode);
                        int totalOriginal = parseInt(dataRecord, "D");
                        int totalPickedUp = parseInt(dataRecord, "F");

                        // 获取签名，用于累加相同签名的数据
                        String signStr = DigestUtils.sha256Hex(formattedDateStr + groupNameStr + bookingStatusStr);
                        // 获取已存在 或 创建新的 GroupPickupBO
                        GroupPickupBO bo = sign2BoMap.get(signStr);
                        if (Objects.isNull(bo)) {
                            bo = new GroupPickupBO();
                            bo.setDate(formattedDateStr);
                            bo.setGroupName(groupNameStr);
                            bo.setBookingStatus(bookingStatus);
                        } else {
                            // 累加相同签名的数据
                            totalSingleRate = bo.getRateBlocked().add(totalSingleRate);
                            totalOriginal += bo.getRoomBlocked();
                            totalPickedUp += bo.getRoomPickup();
                        }

                        i++;

                        // 继续处理后续没有日期的数据行（属于同一天）
                        while (i < records.size()) {
                            CSVRecord nextRecord = records.get(i);

                            // 如果遇到新日期或新分组，则跳出循环
                            String nextColACheck = CsvFileUtils.get(nextRecord, "A");
                            if (groupTarget.equals(nextColACheck) || StringUtils.isNotBlank(nextColACheck)) {
                                break;
                            }

                            // 累加同日期的数据
                            totalSingleRate = totalSingleRate.add(parseDecimal(nextRecord, "H", roundingMode));
                            totalOriginal += parseInt(nextRecord, "D");
                            totalPickedUp += parseInt(nextRecord, "F");

                            i++;
                        }

                        // 设置汇总值
                        bo.setRateBlocked(totalSingleRate);
                        bo.setRatePickup(totalSingleRate);
                        bo.setRoomBlocked(totalOriginal);
                        bo.setRoomPickup(totalPickedUp);

                        // 添加到结果列表
                        sign2BoMap.put(signStr, bo);
                    }
                }
                return new ArrayList<>(sign2BoMap.values());
            } catch (IOException e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Parse Shiji [Group Pickup] report error", e);
            }
        }

        /**
         * 解析金额列
         *
         * @param record       CSV记录
         * @param column       列名
         * @param roundingMode 舍入模式
         * @return BigDecimal
         * @author zc
         * @date 2026/2/5
         */
        private BigDecimal parseDecimal(CSVRecord record, String column, RoundingMode roundingMode) {
            String value = CsvFileUtils.getAndFormatNumber(record, column);
            if (StringUtils.isBlank(value)) return BigDecimal.ZERO;
            return new BigDecimal(value).setScale(BaseConstant.DATA_PRECISION, roundingMode);
        }

        /**
         * 解析数字列
         *
         * @param record CSV记录
         * @param column 列名
         * @return int
         * @author zc
         * @date 2026/2/5
         */
        private int parseInt(CSVRecord record, String column) {
            String value = CsvFileUtils.getAndFormatNumber(record, column);
            if (StringUtils.isBlank(value)) return 0;
            return Integer.parseInt(value);
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param file        文件
         * @param startDate   开始时间整点时刻时间戳
         * @param endDate     结束时间整点时刻时间戳
         * @param logId       日志ID
         * @param userId      操作人ID
         * @author zc
         * @date 2026/2/5
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, long startDate, long endDate, long logId, int userId) {
            try {
                String key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());
                // 上传报告到 S3 服务器，用于事件监听解析报告
                amazonS3Service.uploadFile(file, key);

                // 设置事件体
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(7);
                params.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), propertyDTO.getTenantSymbol());
                params.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), Lists.newArrayList(propertyDTO.getAbbr()));
                params.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.SHI_JI.getDesc());
                params.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.RATE_SHOP.getBusiness());
                params.put(EventBodyParamEnum.UID.getDesc(), userId);
                params.put(EventBodyParamEnum.ID.getDesc(), logId);
                params.put(EventBodyParamEnum.START_DATE.getDesc(), startDate);
                params.put(EventBodyParamEnum.END_DATE.getDesc(), endDate);

                snsSender.publish(EventSubjectEnum.GROUP_PICKUP_SERVICE_TODAY_NINETY_DAY.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Shiji [Group Pickup] report error, send event exception", e);
            }
        }
    }