# WMRevenueReservationStatisticsParseServiceByShiji.java

    package cloud.wconnect.rateshop.service.weeklymonthlyrevenue.reservationstatistics;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueCustomersRule;
    import cloud.wconnect.rateshop.pojo.bo.weeklymonthlyrevenue.WMRevenueReservationStatisticsBO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueCustomersRuleService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.MapUtils;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.stereotype.Component;

    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.*;
    import java.util.stream.Collectors;

    /**
     * 解析 SHiji 系统的 Reservation Statistics/Service 报告
     *
     * @author zc
     * @date 2025/07/07
     */
    @Slf4j
    @Component
    @DS("rate_shop")
    public class WMRevenueReservationStatisticsParseServiceByShiji implements IWMRevenueReservationStatisticsParseService {
        @Resource
        private IRevenueCustomersRuleService revenueCustomersRuleService;

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

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产
         * @param dateRange   数据时间范围（yyyyMMdd）
         * @return WMRevenueReservationStatisticsBO 集合
         * @author zc
         * @date 2025/7/7
         */
        @Override
        public List<WMRevenueReservationStatisticsBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) {
            Map<Integer, List<String>> type2RuleList = revenueCustomersRuleService.list(propertyDTO.getId()).stream()
                    .collect(Collectors.toMap(RevenueCustomersRule::getType, item ->
                            Arrays.stream(item.getRule().split(",")).toList()));
            if (MapUtils.isEmpty(type2RuleList)) {
                return Collections.emptyList();
            }
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            List<String> groupRules = type2RuleList.getOrDefault(RevenueCons.GROUP, Collections.emptyList());
            List<String> contractRules = type2RuleList.getOrDefault(RevenueCons.CONTRACT, Collections.emptyList());

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yy", Locale.ENGLISH);
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = iterable.iterator();
                // 跳过第一行标题
                iterator.next();

                // Market Code 索引
                Map<String, Integer> marketCode2ColIndex = Maps.newHashMap();
                // 取第二行 Market Code
                CSVRecord marketCodeRecord = iterator.next();
                int marketCodeColIndex = 0;
                for (String item : marketCodeRecord) {
                    if (StringUtils.isNotBlank(item) && !item.equals("Total")) {
                        marketCode2ColIndex.put(item, marketCodeColIndex);
                    }
                    marketCodeColIndex++;
                }

                // 跳过第三行标题
                iterator.next();

                List<WMRevenueReservationStatisticsBO> boList = Lists.newArrayList();
                // Date
                String dateStr = ShijiFileCheckUtils.get(iterator.next(), "A").split(" ")[1];
                LocalDate dataLocalDate = LocalDate.parse(dateStr, dateTimeFormatter);
                long targetDate = Long.parseLong(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                if (targetDate >= startDate && targetDate <= endDate) {
                    boList.add(convertBo(dataLocalDate, iterator, groupRules, contractRules, marketCode2ColIndex, roundingMode));
                }
                return boList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Weekly Monthly Revenue Reservation statistics Shiji report error.", e);
            }
        }

        /**
         * 转换为 BO
         *
         * @param dataLocalDate       数据日期
         * @param iterator            迭代器
         * @param groupRules          Group Market Code
         * @param contractRules       Contract Market Code
         * @param marketCode2ColIndex Market Code 列索引
         * @param roundingMode        舍入模式
         * @return WMRevenueReservationStatisticsBO
         * @author zc
         * @date 2025/7/7
         */
        private WMRevenueReservationStatisticsBO convertBo(LocalDate dataLocalDate, Iterator<CSVRecord> iterator,
                                                           List<String> groupRules, List<String> contractRules,
                                                           Map<String, Integer> marketCode2ColIndex,
                                                           RoundingMode roundingMode) {
            BigDecimal totalRevenue = null;
            BigDecimal groupRevenue = null;
            BigDecimal contractRevenue = null;
            Integer totalRoomsSold = null;
            Integer groupRoomsSold = null;
            Integer contractRoomsSold = null;
            // L4 ~ L20 范围为目标内容
            for (int i = 0; i < 16; i++) {
                CSVRecord record = iterator.next();
                String recordTitle = ShijiFileCheckUtils.get(record, "A");
                if (recordTitle.contains("Revenue - Room")) {
                    for (Map.Entry<String, Integer> entry : marketCode2ColIndex.entrySet()) {
                        String marketCode = entry.getKey();
                        String revenueStr = record.get(entry.getValue()).replace(",", "");
                        if (StringUtils.isNotBlank(revenueStr)) {
                            BigDecimal revenue = new BigDecimal(revenueStr);
                            // 累计 Total revenue
                            if (Objects.isNull(totalRevenue)) {
                                totalRevenue = BigDecimal.ZERO;
                            }
                            totalRevenue = totalRevenue.add(revenue);
                            if (groupRules.contains(marketCode)) {
                                // 累计 Group revenue
                                if (Objects.isNull(groupRevenue)) {
                                    groupRevenue = BigDecimal.ZERO;
                                }
                                groupRevenue = groupRevenue.add(revenue);
                            }
                            if (contractRules.contains(marketCode)) {
                                // 累计 Contract revenue
                                if (Objects.isNull(contractRevenue)) {
                                    contractRevenue = BigDecimal.ZERO;
                                }
                                contractRevenue = contractRevenue.add(revenue);
                            }
                        }
                    }
                } else if (recordTitle.contains("Rooms Sold")) {
                    for (Map.Entry<String, Integer> entry : marketCode2ColIndex.entrySet()) {
                        String marketCode = entry.getKey();
                        String roomSoldStr = record.get(entry.getValue()).replace(",", "");
                        if (StringUtils.isNotBlank(roomSoldStr)) {
                            int roomsSold = Integer.parseInt(roomSoldStr);
                            // 累计 Total room sold
                            if (Objects.isNull(totalRoomsSold)) {
                                totalRoomsSold = 0;
                            }
                            totalRoomsSold = totalRoomsSold + roomsSold;
                            if (groupRules.contains(marketCode)) {
                                // 累计 Group room sold
                                if (Objects.isNull(groupRoomsSold)) {
                                    groupRoomsSold = 0;
                                }
                                groupRoomsSold = groupRoomsSold + roomsSold;
                            }
                            if (contractRules.contains(marketCode)) {
                                // 累计 Contract room sold
                                if (Objects.isNull(contractRoomsSold)) {
                                    contractRoomsSold = 0;
                                }
                                contractRoomsSold = contractRoomsSold + roomsSold;
                            }
                        }
                    }
                }
            }
            WMRevenueReservationStatisticsBO bo = new WMRevenueReservationStatisticsBO();
            bo.setTheDay(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
            BigDecimal transientRevenue = Objects.isNull(totalRevenue) ? null :
                    totalRevenue.subtract(Objects.isNull(groupRevenue) ? BigDecimal.ZERO : groupRevenue)
                            .subtract(Objects.isNull(contractRevenue) ? BigDecimal.ZERO : contractRevenue);
            bo.setTransientRevenue(formatPrecision(transientRevenue, roundingMode));
            bo.setGroupRevenue(formatPrecision(groupRevenue, roundingMode));
            bo.setContractRevenue(formatPrecision(contractRevenue, roundingMode));
            bo.setTransientSold(Objects.isNull(totalRoomsSold) ? null :
                    totalRoomsSold - (Objects.isNull(groupRoomsSold) ? 0 : groupRoomsSold)
                            - (Objects.isNull(contractRoomsSold) ? 0 : contractRoomsSold));
            bo.setGroupSold(groupRoomsSold);
            bo.setContractSold(contractRoomsSold);

            return bo;
        }

        /**
         * 格式化精度
         *
         * @param value        数值
         * @param roundingMode 舍入模式
         * @return java.math.BigDecimal
         * @author zc
         * @date 2025/7/19
         */
        private BigDecimal formatPrecision(BigDecimal value, RoundingMode roundingMode) {
            if (Objects.isNull(value)) {
                return null;
            }
            return value.setScale(BaseConstant.DATA_PRECISION, roundingMode);
        }
    }