# DbPmsMarketCodeStatisticsParseServiceByShiji.java

    package cloud.wconnect.workperformance.service.database.marketcode;

    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.sns.http.processor.Sender;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.entity.database.DbReportImportLog;
    import cloud.wconnect.workperformance.pojo.bo.database.managerflash.DbPmsManagerFlashItemBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsDataBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsParentGroupBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsSubGroupBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.database.IDbPmsManagerFlashService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import jakarta.annotation.Resource;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    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.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.*;

    /**
     * 解析 Shiji Market Code Statistics/Service 报告
     *
     * @author zc
     * @date 2025/12/15
     */
    @Component
    public class DbPmsMarketCodeStatisticsParseServiceByShiji implements IDbPmsMarketCodeStatisticsParseService {
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private IDbPmsManagerFlashService managerFlashService;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

        @Value("${aws-s3.third-party.key.database.market-code-statistics}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.database}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2025/12/15
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                ShijiFileCheckUtils.checkMarketCodeStatistics(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Database Market Code Statistics Shiji report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2025/12/15
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, DbReportImportLog importLog, int operatorId) {
            try {
                String key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());

                // 上传报告到 S3 服务器，用于事件监听解析报告
                amazonS3Service.uploadFile(file, key);

                // 封装事件体
                HashMap<String, Object> parameter = Maps.newHashMap();
                parameter.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), propertyDTO.getTenantSymbol());
                parameter.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), List.of(propertyDTO.getAbbr()));
                parameter.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.DATABASE.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.SHI_JI.getDesc());
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);
                parameter.put(EventBodyParamEnum.ID.getDesc(), importLog.getId());
                parameter.put(EventBodyParamEnum.BUSINESS_DATE.getDesc(), importLog.getBusinessDate());
                parameter.put(EventBodyParamEnum.START_DATE.getDesc(), importLog.getStartDate());
                parameter.put(EventBodyParamEnum.END_DATE.getDesc(), importLog.getEndDate());

                // 手动发送事件通知
                snsSender.publish(EventSubjectEnum.MARKET_CODE_STATISTICS_LAST_1_DAY.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Database Market Code Statistics Shiji report exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return DbPmsMarketCodeStatisticsBO
         * @author zc
         * @date 2025/12/15
         */
        @Override
        public DbPmsMarketCodeStatisticsBO parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            String dataDate = dateRange.get(0).toString();
            // 从 Manager Flash 中获取 SC Rooms
            DbPmsManagerFlashItemBO scRoomsBO = managerFlashService.getScRooms(propertyDTO, Long.parseLong(dataDate));

            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                DbPmsMarketCodeStatisticsBO bo = new DbPmsMarketCodeStatisticsBO();
                LocalDate localDate = DateTimeUtils.strToLocalDate(dataDate, BaseConstant.DATE_FORMAT_YYYYMMDD);
                bo.setDateStr(localDate.format(DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD)));

                DbPmsMarketCodeStatisticsDataBO dataBO = convert2Bo(inputStreamReader, scRoomsBO, roundingMode);
                bo.setData(dataBO);
                return bo;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Database parse Market Code Statistics Shiji report error", e);
            }
        }

        /**
         * 转换为BO
         *
         * @param inputStreamReader 文件流
         * @param scRoomsBO         SC Rooms
         * @param roundingMode      舍入模式
         * @return PmsMarketCodeStatisticsDataBO
         * @author zc
         * @date 2025/12/15
         */
        private DbPmsMarketCodeStatisticsDataBO convert2Bo(InputStreamReader inputStreamReader, DbPmsManagerFlashItemBO scRoomsBO,
                                                           RoundingMode roundingMode) throws IOException {
            // 获取CSV数据迭代器
            Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
            Iterator<CSVRecord> iterator = iterable.iterator();
            // 跳过标题行
            iterator.next();

            // 解析数据为父子结构
            List<DbPmsMarketCodeStatisticsParentGroupBO> parentGroup = parseParentAndSubGroups(iterator);

            // 计算每个父级的小计
            IDbPmsMarketCodeStatisticsParseService.calculateParentSubtotals(parentGroup, scRoomsBO, roundingMode);

            // 计算总计
            DbPmsMarketCodeStatisticsDataBO bo = IDbPmsMarketCodeStatisticsParseService.calculateTotals(parentGroup, scRoomsBO, roundingMode);
            bo.setMarketCode(parentGroup);

            return bo;
        }

        /**
         * 解析父子结构数据
         *
         * @param iterator CSV记录迭代器
         * @return 父级组列表
         * @author zc
         * @date 2025/12/15
         */
        private List<DbPmsMarketCodeStatisticsParentGroupBO> parseParentAndSubGroups(Iterator<CSVRecord> iterator) {
            List<DbPmsMarketCodeStatisticsParentGroupBO> parentGroup = Lists.newArrayList();
            DbPmsMarketCodeStatisticsParentGroupBO currentParent = null;

            while (iterator.hasNext()) {
                CSVRecord record = iterator.next();

                // 若 C 列为空则表示是父级，反之是子级
                String roomsStr = ShijiFileCheckUtils.getTrim(record, "C");

                if (StringUtils.isBlank(roomsStr)) {
                    // 父级 Market Segment
                    currentParent = new DbPmsMarketCodeStatisticsParentGroupBO();
                    List<DbPmsMarketCodeStatisticsSubGroupBO> subGroup = Lists.newArrayList();
                    currentParent.setRateCode(subGroup);

                    String marketSegmentRatePlanStr = ShijiFileCheckUtils.getTrim(record, "A");
                    if (StringUtils.isNotBlank(marketSegmentRatePlanStr)) {
                        String[] marketSegmentArr = marketSegmentRatePlanStr.split("\\s+", 2);
                        currentParent.setCode(marketSegmentArr.length > 0 ? marketSegmentArr[0] : "");
                        currentParent.setDesc(marketSegmentArr.length > 1 ? marketSegmentArr[1] : "");
                    }

                    parentGroup.add(currentParent);
                } else if (currentParent != null) {
                    // 子级 Market Segment
                    DbPmsMarketCodeStatisticsSubGroupBO subGroupBO = convert2SubBo(record);
                    currentParent.getRateCode().add(subGroupBO);
                }
            }

            return parentGroup;
        }

        /**
         * 转换为 Sub Group BO
         *
         * @param record CSVRecord
         * @return PmsMarketCodeStatisticsSubGroupBO
         * @author zc
         * @date 2025/12/15
         */
        private DbPmsMarketCodeStatisticsSubGroupBO convert2SubBo(CSVRecord record) {
            DbPmsMarketCodeStatisticsSubGroupBO subGroupBO = new DbPmsMarketCodeStatisticsSubGroupBO();
            subGroupBO.setCode(ShijiFileCheckUtils.getTrim(record, "A"));
            subGroupBO.setDesc(ShijiFileCheckUtils.getTrim(record, "B"));

            subGroupBO.setRmsDay(Integer.parseInt(ShijiFileCheckUtils.getTrim(record, "C")
                    .replace(",", "")));
            subGroupBO.setRmRevDay(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "D")
                    .replace(",", "")));
            subGroupBO.setAdrDay(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "E")
                    .replace(",", "")));
            subGroupBO.setOccDay(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "G")
                    .replace("%", "").replace(",", "")));
            subGroupBO.setGuestDay(Arrays.stream(ShijiFileCheckUtils.getTrim(record, "H")
                    .split("/")).map(Integer::parseInt).reduce(Integer::sum).orElse(0));

            subGroupBO.setRmsMtd(Integer.parseInt(ShijiFileCheckUtils.getTrim(record, "K")
                    .replace(",", "")));
            subGroupBO.setRmRevMtd(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "L")
                    .replace(",", "")));
            subGroupBO.setAdrMtd(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "M")
                    .replace(",", "")));
            subGroupBO.setOccMtd(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "O")
                    .replace("%", "").replace(",", "")));
            subGroupBO.setGuestMtd(Arrays.stream(ShijiFileCheckUtils.getTrim(record, "P")
                    .split("/")).map(Integer::parseInt).reduce(Integer::sum).orElse(0));

            subGroupBO.setRmsYtd(Integer.parseInt(ShijiFileCheckUtils.getTrim(record, "S")
                    .replace(",", "")));
            subGroupBO.setRmRevYtd(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "T")
                    .replace(",", "")));
            subGroupBO.setAdrYtd(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "U")
                    .replace(",", "")));
            subGroupBO.setOccYtd(new BigDecimal(ShijiFileCheckUtils.getTrim(record, "W")
                    .replace("%", "").replace(",", "")));
            subGroupBO.setGuestYtd(Arrays.stream(ShijiFileCheckUtils.getTrim(record, "X")
                    .split("/")).map(Integer::parseInt).reduce(Integer::sum).orElse(0));

            return subGroupBO;
        }

    }