# HotelKpiMetricsFbTotalService.java

    package cloud.wconnect.workperformance.service.hotelkpi.impl.metrics;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.YearMonthUtils;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiDateTypeCons;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiTriggerTypeCons;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiValueCategoryCons;
    import cloud.wconnect.workperformance.entity.hotelkpi.HotelKpiMetricsConfig;
    import cloud.wconnect.workperformance.entity.hotelkpi.HotelKpiMonthly;
    import cloud.wconnect.workperformance.entity.hotelkpi.HotelKpiQuarterly;
    import cloud.wconnect.workperformance.entity.hotelkpi.HotelKpiYearly;
    import cloud.wconnect.workperformance.pojo.dto.hotelkpi.originkpi.HotelKpiOriginCalculationFactorDTO;
    import cloud.wconnect.workperformance.pojo.dto.hotelkpi.originkpi.HotelKpiOriginCrawlValueIndexDTO;
    import cloud.wconnect.workperformance.pojo.dto.hotelkpi.originkpiv2.HotelKpiV2OriginDetailDTO;
    import cloud.wconnect.workperformance.service.hotelkpi.*;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.YearMonth;
    import java.time.ZoneId;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.stream.Collectors;

    /**
     * @author zc
     * @date 2025/08/20
     */
    @Service
    @DS("work_performance")
    public class HotelKpiMetricsFbTotalService implements IHotelKpiMetricsService {

        @Resource
        private IHotelKpiService hotelKpiService;
        @Resource
        private IHotelKpiMonthlyService monthlyService;
        @Resource
        private IHotelKpiQuarterlyService quarterlyService;
        @Resource
        private IHotelKpiYearlyService yearlyService;
        @Resource
        private IHotelKpiMetricsConfigService metricsConfigService;
        @Resource
        private ObjectMapper objectMapper;

        private static final int METRICS_TYPE = HotelKpiMetricsEnum.FB_TOTAL.getMetricsType();

        /**
         * 支持的指标类型
         *
         * @param metricsType 指标类型
         * @return boolean
         * @author zc
         * @date 2025/8/20
         */
        @Override
        public boolean supports(int metricsType) {
            return METRICS_TYPE == metricsType;
        }

        /**
         * 初始化数据
         *
         * @param propertyDTO  资产
         * @param nowLocalDate 当前日期
         * @author zc
         * @date 2025/8/20
         */
        @Override
        public void initData(PropertyDTO propertyDTO, LocalDate nowLocalDate) {
            // 无需处理
        }

        /**
         * 触发设置数据
         *
         * @param propertyDTO 资产
         * @param triggerType 触发类型，不同类型的日期格式不同
         * @param startDate   开始日期(yyyyMMdd,yyyyMM,yyyy)
         * @param endDate     结束日期(yyyyMMdd,yyyyMM,yyyy)
         * @author zc
         * @date 2025/9/12
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void triggerSetData(PropertyDTO propertyDTO, int triggerType, long startDate, long endDate) {
            HotelKpiMetricsConfig metricsConfig = metricsConfigService.getMetricsConfigByTypeForUpdate(propertyDTO.getId(), METRICS_TYPE);
            if (Objects.isNull(metricsConfig)) {
                return;
            }
            if (HotelKpiTriggerTypeCons.M3_MONTH == triggerType) {
                LocalDate startLocalDate = YearMonthUtils.getYearMonth(String.valueOf(startDate)).atDay(1);
                LocalDate endLocalDate = YearMonthUtils.getYearMonth(String.valueOf(endDate)).atDay(1);

                setMonthly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
                setQuarterly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
                setYearly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
            } else if (HotelKpiTriggerTypeCons.BUDGET_DATABASE == triggerType) {
                LocalDate startLocalDate = YearMonth.of((int) startDate, 1).atDay(1);
                LocalDate endLocalDate = YearMonth.of((int) endDate, 12).atDay(1);

                setMonthly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
                setQuarterly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
                setYearly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
            }
        }

        /**
         * 设置数据
         *
         * @param propertyDTO    资产
         * @param dateType       日期类型
         * @param startLocalDate 起始日期
         * @param endLocalDate   结束日期
         * @author zc
         * @date 2025/9/11
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void setData(PropertyDTO propertyDTO, int dateType, LocalDate startLocalDate, LocalDate endLocalDate) {
            HotelKpiMetricsConfig metricsConfig = metricsConfigService.getMetricsConfigByTypeForUpdate(propertyDTO.getId(), METRICS_TYPE);
            if (Objects.isNull(metricsConfig)) {
                return;
            }
            if (HotelKpiDateTypeCons.MONTHLY == dateType) {
                setMonthly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
                setQuarterly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
                setYearly(propertyDTO, startLocalDate, endLocalDate, metricsConfig);
            }
        }

        /**
         * 设置数据 for Monthly
         *
         * @param propertyDTO    资产
         * @param startLocalDate 起始日期
         * @param endLocalDate   结束日期
         * @param metricsConfig  指标配置
         * @author zc
         * @date 2025/9/11
         */
        private void setMonthly(PropertyDTO propertyDTO, LocalDate startLocalDate, LocalDate endLocalDate, HotelKpiMetricsConfig metricsConfig) {
            int dateType = HotelKpiDateTypeCons.MONTHLY;
            int propertyId = propertyDTO.getId();
            String factorConfigStr = metricsConfig.getCalculationFactorConfig();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());

            YearMonth startYearMonth = YearMonth.of(startLocalDate.getYear(), startLocalDate.getMonthValue());
            YearMonth endYearMonth = YearMonth.of(endLocalDate.getYear(), endLocalDate.getMonthValue());

            long startMonth = YearMonthUtils.parseYearMonthToLong(startYearMonth);
            long endMonth = YearMonthUtils.parseYearMonthToLong(endYearMonth);

            List<Integer> relationalMetricsTypes = HotelKpiMetricsEnum.getRelationalMetricsTypesReverse(METRICS_TYPE, dateType);
            // 获取关联指标数据
            List<HotelKpiMonthly> relationMonthlyList = monthlyService.listByDateRangeAndMetricsTypes(propertyId,
                    startMonth, endMonth, relationalMetricsTypes);

            // 获取原始KPI数据
            Map<Long, String> date2OriginDetail = monthlyService.listByDateRangeAndMetricsType(propertyId,
                    startMonth, endMonth, METRICS_TYPE).stream().collect(Collectors.toMap(HotelKpiMonthly::getMonth, HotelKpiMonthly::getDetail));

            List<HotelKpiMonthly> saveList = Lists.newArrayList();
            for (YearMonth indexYearMonth = startYearMonth; !indexYearMonth.isAfter(endYearMonth); indexYearMonth = indexYearMonth.plusMonths(1)) {
                long indexMonth = YearMonthUtils.parseYearMonthToLong(indexYearMonth);

                String originDetail = date2OriginDetail.getOrDefault(indexMonth, null);
                List<HotelKpiV2OriginDetailDTO> originDetailDTOList = hotelKpiService.convert2V2OriginDetailDTOList(originDetail, dateType, factorConfigStr);

                // 截取 Month 数据
                List<HotelKpiMonthly> effectiveList = relationMonthlyList.stream().filter(item -> item.getMonth() == indexMonth).toList();

                BigDecimal totalActualValue = summaryMonthlyKpi(effectiveList, HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.ACTUAL);
                // 设置 total.actual
                setMetricsValue(originDetailDTOList, totalActualValue, HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.ACTUAL, roundingMode);

                BigDecimal totalBudgetValue = summaryMonthlyKpi(effectiveList, HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.BUDGET);
                // 设置 total.budget
                setMetricsValue(originDetailDTOList, totalBudgetValue, HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.BUDGET, roundingMode);

                BigDecimal totalLyValue = summaryMonthlyKpi(effectiveList, HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.LY);
                // 设置 total.ly
                setMetricsValue(originDetailDTOList, totalLyValue, HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.LY, roundingMode);

                String detail = JsonUtils.convertObjListToString(objectMapper, originDetailDTOList);

                saveList.add(HotelKpiMonthly.builder()
                        .propertyId(propertyId)
                        .month(indexMonth)
                        .metricsType(METRICS_TYPE)
                        .detail(detail)
                        .build());
            }
            monthlyService.insertOrUpdateBatch(saveList);
        }

        /**
         * 设置数据 for Quarterly
         *
         * @param propertyDTO    资产
         * @param startLocalDate 起始日期
         * @param endLocalDate   结束日期
         * @param metricsConfig  指标配置
         * @author zc
         * @date 2025/9/11
         */
        private void setQuarterly(PropertyDTO propertyDTO, LocalDate startLocalDate, LocalDate endLocalDate, HotelKpiMetricsConfig metricsConfig) {
            int dateType = HotelKpiDateTypeCons.QUARTERLY;
            int propertyId = propertyDTO.getId();
            String factorConfigStr = metricsConfig.getCalculationFactorConfig();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());

            YearMonth startYearMonthOfQuarter = YearMonth.of(startLocalDate.getYear(), startLocalDate.getMonth().firstMonthOfQuarter());
            YearMonth endYearMonthOfQuarter = YearMonth.of(endLocalDate.getYear(), endLocalDate.getMonth().firstMonthOfQuarter());

            // 获取 Monthly KPI 数据
            long startMonth = YearMonthUtils.parseYearMonthToLong(startYearMonthOfQuarter);
            long endMonth = YearMonthUtils.parseYearMonthToLong(startYearMonthOfQuarter.plusMonths(2));
            List<HotelKpiMonthly> monthlyList = monthlyService.listByDateRangeAndMetricsType(propertyId, startMonth, endMonth, METRICS_TYPE);

            // 获取原始KPI数据
            long startQuarterDate = YearMonthUtils.parseYearMonthToLong(startYearMonthOfQuarter);
            long endQuarterDate = YearMonthUtils.parseYearMonthToLong(endYearMonthOfQuarter);
            Map<Long, String> month2OriginDetail = quarterlyService.listByDateRangeAndMetricsType(propertyId,
                            startQuarterDate, endQuarterDate, METRICS_TYPE).stream()
                    .collect(Collectors.toMap(HotelKpiQuarterly::getMonth, HotelKpiQuarterly::getDetail));

            List<HotelKpiQuarterly> saveList = Lists.newArrayList();
            for (YearMonth indexYearMonth = startYearMonthOfQuarter; !indexYearMonth.isAfter(endYearMonthOfQuarter); indexYearMonth = indexYearMonth.plusMonths(3)) {
                long indexStartMonth = YearMonthUtils.parseYearMonthToLong(indexYearMonth);

                String originDetail = month2OriginDetail.get(indexStartMonth);
                List<HotelKpiV2OriginDetailDTO> originDetailDTOList = hotelKpiService.convert2V2OriginDetailDTOList(originDetail, dateType, factorConfigStr);

                // 截取数据
                long indexEndMonth = YearMonthUtils.parseYearMonthToLong(indexYearMonth.plusMonths(2));
                List<HotelKpiMonthly> effectiveMonthlyList = monthlyList.stream().filter(metricsKpi ->
                        metricsKpi.getMonth() >= startMonth && metricsKpi.getMonth() <= indexEndMonth).toList();

                BigDecimal totalActualValue = effectiveMonthlyList.stream().map(item ->
                                hotelKpiService.getEffectiveValueForKpiDetailV2(item.getDetail(),
                                        HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.ACTUAL))
                        .filter(Objects::nonNull).reduce(BigDecimal::add).orElse(null);
                // 设置 total.actual
                setMetricsValue(originDetailDTOList, totalActualValue, HotelKpiValueCategoryCons.CATEGORY_1,
                        HotelKpiValueCategoryCons.ACTUAL, roundingMode);

                BigDecimal totalBudgetValue = effectiveMonthlyList.stream().map(item ->
                                hotelKpiService.getEffectiveValueForKpiDetailV2(item.getDetail(),
                                        HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.BUDGET))
                        .filter(Objects::nonNull).reduce(BigDecimal::add).orElse(null);
                // 设置 total.budget
                setMetricsValue(originDetailDTOList, totalBudgetValue, HotelKpiValueCategoryCons.CATEGORY_1,
                        HotelKpiValueCategoryCons.BUDGET, roundingMode);

                BigDecimal totalLyValue = effectiveMonthlyList.stream().map(item ->
                                hotelKpiService.getEffectiveValueForKpiDetailV2(item.getDetail(),
                                        HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.LY))
                        .filter(Objects::nonNull).reduce(BigDecimal::add).orElse(null);
                // 设置 total.ly
                setMetricsValue(originDetailDTOList, totalLyValue, HotelKpiValueCategoryCons.CATEGORY_1,
                        HotelKpiValueCategoryCons.LY, roundingMode);

                String detail = JsonUtils.convertObjListToString(objectMapper, originDetailDTOList);

                saveList.add(HotelKpiQuarterly.builder()
                        .propertyId(propertyId)
                        .month(indexStartMonth)
                        .metricsType(METRICS_TYPE)
                        .detail(detail)
                        .build());
            }
            quarterlyService.insertOrUpdateBatch(saveList);
        }

        /**
         * 设置数据 for Yearly
         *
         * @param propertyDTO    资产
         * @param startLocalDate 起始日期
         * @param endLocalDate   结束日期
         * @param metricsConfig  指标配置
         * @author zc
         * @date 2025/9/11
         */
        private void setYearly(PropertyDTO propertyDTO, LocalDate startLocalDate, LocalDate endLocalDate, HotelKpiMetricsConfig metricsConfig) {
            int dateType = HotelKpiDateTypeCons.YEARLY;
            int propertyId = propertyDTO.getId();
            String factorConfigStr = metricsConfig.getCalculationFactorConfig();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            // 获取上个月的日期
            YearMonth lastMonthYearMonth = YearMonth.now(ZoneId.of(propertyDTO.getTimezone())).minusMonths(1);

            int startYear = startLocalDate.getYear();
            int endYear = endLocalDate.getYear();

            YearMonth startYearMonth = YearMonth.of(startYear, 1);
            YearMonth endYearMonth = YearMonth.of(endYear, 12);

            // 获取 Monthly KPI 数据
            long startMonth = YearMonthUtils.parseYearMonthToLong(startYearMonth);
            long endMonth = YearMonthUtils.parseYearMonthToLong(endYearMonth);
            List<HotelKpiMonthly> monthlyList = monthlyService.listByDateRangeAndMetricsType(propertyId, startMonth, endMonth, METRICS_TYPE);

            // 获取原始KPI数据
            Map<Long, String> year2OriginDetail = yearlyService.listByDateRangeAndMetricsType(propertyId,
                            startYear, endYear, METRICS_TYPE).stream()
                    .collect(Collectors.toMap(HotelKpiYearly::getYear, HotelKpiYearly::getDetail));

            List<HotelKpiYearly> saveList = Lists.newArrayList();
            for (int indexYear = startYear; indexYear <= endYear; indexYear++) {
                // 若年份大于当前上个月的年份，则跳过
                if (indexYear > lastMonthYearMonth.getYear()) {
                    continue;
                }
                String originDetail = year2OriginDetail.get((long) indexYear);
                List<HotelKpiV2OriginDetailDTO> originDetailDTOList = hotelKpiService.convert2V2OriginDetailDTOList(originDetail, dateType, factorConfigStr);

                int asOfMonth = indexYear < lastMonthYearMonth.getYear() ? 12 : lastMonthYearMonth.getMonthValue();
                long indexStartMonth = YearMonthUtils.parseYearMonthToLong(YearMonth.of(indexYear, 1));
                long indexEndMonth = YearMonthUtils.parseYearMonthToLong(YearMonth.of(indexYear, asOfMonth));

                // 截取数据
                List<HotelKpiMonthly> effectiveMonthlyList = monthlyList.stream().filter(metricsKpi ->
                        metricsKpi.getMonth() >= indexStartMonth && metricsKpi.getMonth() <= indexEndMonth).toList();

                BigDecimal totalActualValue = effectiveMonthlyList.stream().map(item ->
                                hotelKpiService.getEffectiveValueForKpiDetailV2(item.getDetail(),
                                        HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.ACTUAL))
                        .filter(Objects::nonNull).reduce(BigDecimal::add).orElse(null);
                // 设置 total.actual
                setMetricsValue(originDetailDTOList, totalActualValue, HotelKpiValueCategoryCons.CATEGORY_1,
                        HotelKpiValueCategoryCons.ACTUAL, roundingMode);

                BigDecimal totalBudgetValue = effectiveMonthlyList.stream().map(item ->
                                hotelKpiService.getEffectiveValueForKpiDetailV2(item.getDetail(),
                                        HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.BUDGET))
                        .filter(Objects::nonNull).reduce(BigDecimal::add).orElse(null);
                // 设置 total.budget
                setMetricsValue(originDetailDTOList, totalBudgetValue, HotelKpiValueCategoryCons.CATEGORY_1,
                        HotelKpiValueCategoryCons.BUDGET, roundingMode);

                BigDecimal totalLyValue = effectiveMonthlyList.stream().map(item ->
                                hotelKpiService.getEffectiveValueForKpiDetailV2(item.getDetail(),
                                        HotelKpiValueCategoryCons.CATEGORY_1, HotelKpiValueCategoryCons.LY))
                        .filter(Objects::nonNull).reduce(BigDecimal::add).orElse(null);
                // 设置 total.ly
                setMetricsValue(originDetailDTOList, totalLyValue, HotelKpiValueCategoryCons.CATEGORY_1,
                        HotelKpiValueCategoryCons.LY, roundingMode);

                String detail = JsonUtils.convertObjListToString(objectMapper, originDetailDTOList);

                saveList.add(HotelKpiYearly.builder()
                        .propertyId(propertyId)
                        .year((long) indexYear)
                        .metricsType(METRICS_TYPE)
                        .detail(detail)
                        .build());
            }
            yearlyService.insertOrUpdateBatch(saveList);
        }

        /**
         * 总结指标值
         *
         * @param monthlyList 月 KPI 集合
         * @param category    指标类别
         * @param titleIndex  指标标题索引
         * @return 指标值
         * @author zc
         * @date 2025/9/11
         */
        private BigDecimal summaryMonthlyKpi(List<HotelKpiMonthly> monthlyList, int category, int titleIndex) {
            Map<Integer, String> metricsType2Kpi = monthlyList.stream()
                    .collect(Collectors.toMap(HotelKpiMonthly::getMetricsType, HotelKpiMonthly::getDetail));

            String fbRestaurantKpiDetail = metricsType2Kpi.get(HotelKpiMetricsEnum.FB_RESTAURANT.getMetricsType());
            BigDecimal fbRestaurant = hotelKpiService.getEffectiveValueForKpiDetailV2(fbRestaurantKpiDetail, category, titleIndex);

            String fbBanquetKpiDetail = metricsType2Kpi.get(HotelKpiMetricsEnum.FB_BANQUET.getMetricsType());
            BigDecimal fbBanquet = hotelKpiService.getEffectiveValueForKpiDetailV2(fbBanquetKpiDetail, category, titleIndex);

            return Lists.newArrayList(fbRestaurant, fbBanquet).stream()
                    .filter(Objects::nonNull).reduce(BigDecimal::add).orElse(null);
        }

        /**
         * 设置指标值
         *
         * @param originDetailDTOList 原始数值
         * @param value               指标值
         * @param category            指标类别(1:Total 2:Transient 3:Group)
         * @param titleIndex          标题坐标(1:Actual 2:Budget 3:LY)
         * @param roundingMode        舍入模式
         * @author zc
         * @date 2025/8/25
         */
        private void setMetricsValue(List<HotelKpiV2OriginDetailDTO> originDetailDTOList, BigDecimal value, int category,
                                     int titleIndex, RoundingMode roundingMode) {
            if (Objects.nonNull(value)) {
                value = value.setScale(BaseConstant.DATA_PRECISION, roundingMode);
            }
            for (HotelKpiV2OriginDetailDTO originDetailDTO : originDetailDTOList) {
                if (Objects.equals(originDetailDTO.getCategory(), category)) {
                    // 组装新的计算因子 1
                    HotelKpiOriginCalculationFactorDTO factorIndex1 = new HotelKpiOriginCalculationFactorDTO()
                            .setIndex(1).setCrawl(value)
                            .setCrawlOrigin(List.of(HotelKpiOriginCrawlValueIndexDTO.builder().index(1).value(value).build()));

                    if (HotelKpiValueCategoryCons.ACTUAL == titleIndex) {
                        hotelKpiService.replaceOriginFactorList(originDetailDTO.getActual().getCalculationFactor(), factorIndex1);
                    } else if (HotelKpiValueCategoryCons.BUDGET == titleIndex) {
                        hotelKpiService.replaceOriginFactorList(originDetailDTO.getBudget().getCalculationFactor(), factorIndex1);
                    } else {
                        hotelKpiService.replaceOriginFactorList(originDetailDTO.getLy().getCalculationFactor(), factorIndex1);
                    }
                    return;
                }
            }
        }
    }