# HotelKpiMetricsSelloutEfficiencyService.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.DateTimeUtils;
    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.entity.hotelkpi.*;
    import cloud.wconnect.workperformance.pojo.dto.gmwr.internal.SelloutEfficiencyInternalDTO;
    import cloud.wconnect.workperformance.pojo.dto.gmwr.internal.SelloutEfficiencyOccInternalDTO;
    import cloud.wconnect.workperformance.pojo.dto.gmwr.selloutefficiency.GmwrOccSelloutConfigDTO;
    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.originkpi.HotelKpiOriginDetailDTO;
    import cloud.wconnect.workperformance.service.gmwr.internal.IGmwrInternalService;
    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.DayOfWeek;
    import java.time.LocalDate;
    import java.time.YearMonth;
    import java.time.ZoneId;
    import java.time.temporal.TemporalAdjusters;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.stream.Collectors;

    /**
     * @author zc
     * @date 2025/09/13
     */
    @Service
    @DS("work_performance")
    public class HotelKpiMetricsSelloutEfficiencyService implements IHotelKpiMetricsService {

        @Resource
        private IHotelKpiService hotelKpiService;
        @Resource
        private IHotelKpiWeeklyService weeklyService;
        @Resource
        private IHotelKpiMonthlyService monthlyService;
        @Resource
        private IHotelKpiQuarterlyService quarterlyService;
        @Resource
        private IHotelKpiYearlyService yearlyService;
        @Resource
        private IHotelKpiMetricsConfigService metricsConfigService;
        @Resource
        private IHotelKpiWeekStartDayService weekStartDayService;
        @Resource
        private IGmwrInternalService gmwrInternalService;
        @Resource
        private ObjectMapper objectMapper;

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

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

        /**
         * 初始化
         *
         * @param propertyDTO  资产
         * @param nowLocalDate 当前时间
         * @author zc
         * @date 2025/9/11
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void initData(PropertyDTO propertyDTO, LocalDate nowLocalDate) {
            HotelKpiMetricsConfig metricsConfig = metricsConfigService.getMetricsConfigByTypeForUpdate(propertyDTO.getId(), METRICS_TYPE);
            if (Objects.isNull(metricsConfig)) {
                return;
            }
            initWeekly(propertyDTO, nowLocalDate);
            initMonthly(propertyDTO, nowLocalDate);
            initQuarterly(propertyDTO, nowLocalDate);
            initYearly(propertyDTO, nowLocalDate);
        }

        /**
         * 初始化 for Weekly
         *
         * @param propertyDTO  资产
         * @param nowLocalDate 当前时间
         * @author zc
         * @date 2025/9/11
         */
        private void initWeekly(PropertyDTO propertyDTO, LocalDate nowLocalDate) {
            // 当前日期若是周起始日，则生成上一周期的数据
            DayOfWeek dayOfWeek = weekStartDayService.getWeekStartDay(propertyDTO.getId());
            if (nowLocalDate.getDayOfWeek().compareTo(dayOfWeek) != 0) {
                return;
            }
            // 获取上一周期的起始日期
            LocalDate lastWeekStartLocalDate = nowLocalDate.minusDays(7);
            // 设置数据
            setWeekly(propertyDTO, lastWeekStartLocalDate, lastWeekStartLocalDate);
        }

        /**
         * 初始化 for Monthly
         *
         * @param propertyDTO  资产
         * @param nowLocalDate 当前时间
         * @author zc
         * @date 2025/9/11
         */
        private void initMonthly(PropertyDTO propertyDTO, LocalDate nowLocalDate) {
            // 获取当前日期，如果不是当月第一天，则不处理
            if (nowLocalDate.getDayOfMonth() != 1) {
                return;
            }
            // 当前时间生成上一周期数据，需要减去一个月
            LocalDate lastMonthLocalDate = nowLocalDate.minusMonths(1);
            // 设置数据
            setMonthly(propertyDTO, lastMonthLocalDate, lastMonthLocalDate);
        }

        /**
         * 初始化 for Quarterly
         *
         * @param propertyDTO  资产
         * @param nowLocalDate 当前时间
         * @author zc
         * @date 2025/9/11
         */
        private void initQuarterly(PropertyDTO propertyDTO, LocalDate nowLocalDate) {
            LocalDate firstLocalDateOfQuarter = LocalDate.of(nowLocalDate.getYear(),
                    nowLocalDate.getMonth().firstMonthOfQuarter(), 1);
            // 获取当前日期，若不是季度的第一天，则不处理
            if (!firstLocalDateOfQuarter.isEqual(nowLocalDate)) {
                return;
            }
            // 当前时间生成上一周期数据，需要减去3个月
            LocalDate lastQuarterLocalDate = nowLocalDate.minusMonths(3);
            // 设置数据
            setQuarterly(propertyDTO, lastQuarterLocalDate, lastQuarterLocalDate);
        }

        /**
         * 初始化 for Yearly
         *
         * @param propertyDTO  资产
         * @param nowLocalDate 当前时间
         * @author zc
         * @date 2025/9/11
         */
        private void initYearly(PropertyDTO propertyDTO, LocalDate nowLocalDate) {
            // 获取当前日期，如果不是当月第一天，则不处理
            if (nowLocalDate.getDayOfMonth() != 1) {
                return;
            }
            // 当前时间生成截至到上个月的 YTD 数据，需要减去一个月
            LocalDate lastMonthLocalDate = nowLocalDate.minusMonths(1);
            // 设置数据
            setYearly(propertyDTO, lastMonthLocalDate, lastMonthLocalDate);
        }

        /**
         * 触发设置数据
         *
         * @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.SELLOUT_EFFICIENCY == triggerType) {
                LocalDate startLocalDate = DateTimeUtils.strToLocalDate(String.valueOf(startDate),
                        BaseConstant.DATE_FORMAT_YYYYMMDD);
                // 指标计算最小时间维度是 MTD，统计维度有重叠，结束日期需设置为该月份的月底
                LocalDate endLocalDate = DateTimeUtils.strToLocalDate(String.valueOf(endDate),
                        BaseConstant.DATE_FORMAT_YYYYMMDD).with(TemporalAdjusters.lastDayOfMonth());

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

        /**
         * 设置数据
         *
         * @param propertyDTO    资产
         * @param dateType       日期类型
         * @param startLocalDate 起始日期
         * @param endLocalDate   结束日期
         * @author zc
         * @date 2025/9/11
         */
        @Override
        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.WEEKLY == dateType) {
                setWeekly(propertyDTO, startLocalDate, endLocalDate);
            } else if (HotelKpiDateTypeCons.MONTHLY == dateType) {
                setMonthly(propertyDTO, startLocalDate, endLocalDate);
            } else if (HotelKpiDateTypeCons.QUARTERLY == dateType) {
                setQuarterly(propertyDTO, startLocalDate, endLocalDate);
            } else if (HotelKpiDateTypeCons.YEARLY == dateType) {
                setYearly(propertyDTO, startLocalDate, endLocalDate);
            }
        }

        /**
         * 设置数据 for Weekly
         *
         * @param propertyDTO    资产
         * @param startLocalDate 起始日期
         * @param endLocalDate   结束日期
         * @author zc
         * @date 2025/9/11
         */
        private void setWeekly(PropertyDTO propertyDTO, LocalDate startLocalDate, LocalDate endLocalDate) {
            int propertyId = propertyDTO.getId();
            DayOfWeek dayOfWeek = weekStartDayService.getWeekStartDay(propertyId);
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            GmwrOccSelloutConfigDTO occSelloutConfig = gmwrInternalService.getOccSelloutConfig(propertyId);

            // 转换为周的开始日期
            LocalDate startWeekLocalDate = startLocalDate.with(TemporalAdjusters.previousOrSame(dayOfWeek));
            LocalDate endWeekLocalDate = endLocalDate.with(TemporalAdjusters.previousOrSame(dayOfWeek));

            // 获取 MTD Sellout Efficiency OCC 数据
            long startQueryDate = Long.parseLong(DateTimeUtils.localDateToStr(startWeekLocalDate.withDayOfMonth(1),
                    BaseConstant.DATE_FORMAT_YYYYMMDD));
            long endQueryDate = Long.parseLong(DateTimeUtils.localDateToStr(endWeekLocalDate.plusDays(6),
                    BaseConstant.DATE_FORMAT_YYYYMMDD));
            List<SelloutEfficiencyOccInternalDTO> occList = gmwrInternalService.listSelloutEfficiencyOcc(propertyId,
                    startQueryDate, endQueryDate);

            // 获取原始KPI数据
            long startWeekDate = Long.parseLong(DateTimeUtils.localDateToStr(startWeekLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
            long endWeekDate = Long.parseLong(DateTimeUtils.localDateToStr(endWeekLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
            Map<Long, String> date2OriginDetail = weeklyService.listByDateRangeAndMetricsType(propertyId,
                            startWeekDate, endWeekDate, METRICS_TYPE).stream()
                    .collect(Collectors.toMap(HotelKpiWeekly::getWeek, HotelKpiWeekly::getDetail));
            List<HotelKpiWeekly> saveList = Lists.newArrayList();
            for (LocalDate indexLocalDate = startWeekLocalDate; !indexLocalDate.isAfter(endWeekLocalDate); indexLocalDate = indexLocalDate.plusWeeks(1)) {
                long indexDate = Long.parseLong(DateTimeUtils.localDateToStr(indexLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));

                String originDetail = date2OriginDetail.get(indexDate);
                HotelKpiOriginDetailDTO originDetailDTO = hotelKpiService.convert2OriginDetailDTOList(originDetail);

                // 截取 Sellout Efficiency OCC 数据
                long indexStartDate = Long.parseLong(DateTimeUtils.localDateToStr(indexLocalDate.withDayOfMonth(1),
                        BaseConstant.DATE_FORMAT_YYYYMMDD));
                LocalDate endIndexLocalDate = indexLocalDate.plusDays(6);
                // MTD 取值规则，若跨月，则取当前月的最后一天
                if (endIndexLocalDate.getMonthValue() != indexLocalDate.getMonthValue()) {
                    endIndexLocalDate = indexLocalDate.with(TemporalAdjusters.lastDayOfMonth());
                }
                long indexEndDate = Long.parseLong(DateTimeUtils.localDateToStr(endIndexLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));

                List<SelloutEfficiencyOccInternalDTO> effectiveOccList = occList.stream().filter(item ->
                        item.getDate() >= indexStartDate && item.getDate() <= indexEndDate).toList();
                SelloutEfficiencyInternalDTO selloutEfficiency = gmwrInternalService.getSelloutEfficiency(occSelloutConfig, effectiveOccList);
                // 设置 actual
                setMetricsValue(originDetailDTO, selloutEfficiency, roundingMode);

                String detail = JsonUtils.convertObjToString(objectMapper, originDetailDTO);

                saveList.add(HotelKpiWeekly.builder()
                        .propertyId(propertyId)
                        .week(indexDate)
                        .metricsType(METRICS_TYPE)
                        .detail(detail)
                        .build());
            }
            weeklyService.insertOrUpdateBatch(saveList);
        }

        /**
         * 设置数据 for Monthly
         *
         * @param propertyDTO    资产
         * @param startLocalDate 起始日期
         * @param endLocalDate   结束日期
         * @author zc
         * @date 2025/9/11
         */
        private void setMonthly(PropertyDTO propertyDTO, LocalDate startLocalDate, LocalDate endLocalDate) {
            int propertyId = propertyDTO.getId();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            GmwrOccSelloutConfigDTO occSelloutConfig = gmwrInternalService.getOccSelloutConfig(propertyId);

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

            // 获取 Sellout Efficiency OCC 数据
            long startQueryDate = Long.parseLong(DateTimeUtils.localDateToStr(startLocalDate.withDayOfMonth(1),
                    BaseConstant.DATE_FORMAT_YYYYMMDD));
            long endQueryDate = Long.parseLong(DateTimeUtils.localDateToStr(endLocalDate.with(TemporalAdjusters.lastDayOfMonth()),
                    BaseConstant.DATE_FORMAT_YYYYMMDD));
            List<SelloutEfficiencyOccInternalDTO> occList = gmwrInternalService.listSelloutEfficiencyOcc(propertyId,
                    startQueryDate, endQueryDate);

            // 获取原始KPI数据
            long startMonth = YearMonthUtils.parseYearMonthToLong(startYearMonth);
            long endMonth = YearMonthUtils.parseYearMonthToLong(endYearMonth);
            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.get(indexMonth);
                HotelKpiOriginDetailDTO originDetailDTO = hotelKpiService.convert2OriginDetailDTOList(originDetail);

                // 截取 Sellout Efficiency OCC 数据
                long indexStartDate = Long.parseLong(DateTimeUtils.localDateToStr(indexYearMonth.atDay(1),
                        BaseConstant.DATE_FORMAT_YYYYMMDD));
                long indexEndDate = Long.parseLong(DateTimeUtils.localDateToStr(indexYearMonth.atEndOfMonth(),
                        BaseConstant.DATE_FORMAT_YYYYMMDD));
                List<SelloutEfficiencyOccInternalDTO> effectiveOccList = occList.stream().filter(item ->
                        item.getDate() >= indexStartDate && item.getDate() <= indexEndDate).toList();
                SelloutEfficiencyInternalDTO selloutEfficiency = gmwrInternalService.getSelloutEfficiency(occSelloutConfig, effectiveOccList);
                // 设置 actual
                setMetricsValue(originDetailDTO, selloutEfficiency, roundingMode);

                String detail = JsonUtils.convertObjToString(objectMapper, originDetailDTO);

                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   结束日期
         * @author zc
         * @date 2025/9/11
         */
        private void setQuarterly(PropertyDTO propertyDTO, LocalDate startLocalDate, LocalDate endLocalDate) {
            int propertyId = propertyDTO.getId();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            GmwrOccSelloutConfigDTO occSelloutConfig = gmwrInternalService.getOccSelloutConfig(propertyId);

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

            // 获取 Sellout Efficiency OCC 数据
            long startQueryDate = Long.parseLong(DateTimeUtils.localDateToStr(startYearMonthOfQuarter.atDay(1),
                    BaseConstant.DATE_FORMAT_YYYYMMDD));
            long endQueryDate = Long.parseLong(DateTimeUtils.localDateToStr(endYearMonthOfQuarter.plusMonths(2).atEndOfMonth(),
                    BaseConstant.DATE_FORMAT_YYYYMMDD));
            List<SelloutEfficiencyOccInternalDTO> occList = gmwrInternalService.listSelloutEfficiencyOcc(propertyId,
                    startQueryDate, endQueryDate);

            // 获取原始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);
                HotelKpiOriginDetailDTO originDetailDTO = hotelKpiService.convert2OriginDetailDTOList(originDetail);

                // 截取 Sellout Efficiency OCC 数据
                long indexStartDate = Long.parseLong(DateTimeUtils.localDateToStr(indexYearMonth.atDay(1),
                        BaseConstant.DATE_FORMAT_YYYYMMDD));
                long indexEndDate = Long.parseLong(DateTimeUtils.localDateToStr(indexYearMonth.plusMonths(2).atEndOfMonth(),
                        BaseConstant.DATE_FORMAT_YYYYMMDD));
                List<SelloutEfficiencyOccInternalDTO> effectiveOccList = occList.stream().filter(item ->
                        item.getDate() >= indexStartDate && item.getDate() <= indexEndDate).toList();
                SelloutEfficiencyInternalDTO selloutEfficiency = gmwrInternalService.getSelloutEfficiency(occSelloutConfig, effectiveOccList);
                // 设置 actual
                setMetricsValue(originDetailDTO, selloutEfficiency, roundingMode);

                String detail = JsonUtils.convertObjToString(objectMapper, originDetailDTO);

                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   结束日期
         * @author zc
         * @date 2025/9/11
         */
        private void setYearly(PropertyDTO propertyDTO, LocalDate startLocalDate, LocalDate endLocalDate) {
            int propertyId = propertyDTO.getId();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            GmwrOccSelloutConfigDTO occSelloutConfig = gmwrInternalService.getOccSelloutConfig(propertyId);
            // 获取上个月的日期
            YearMonth lastMonthYearMonth = YearMonth.now(ZoneId.of(propertyDTO.getTimezone())).minusMonths(1);

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

            // 获取 Sellout Efficiency OCC 数据
            long startQueryDate = Long.parseLong(DateTimeUtils.localDateToStr(YearMonth.of(startYear, 1).atDay(1),
                    BaseConstant.DATE_FORMAT_YYYYMMDD));
            long endQueryDate = Long.parseLong(DateTimeUtils.localDateToStr(YearMonth.of(endYear, 12).atEndOfMonth(),
                    BaseConstant.DATE_FORMAT_YYYYMMDD));
            List<SelloutEfficiencyOccInternalDTO> occList = gmwrInternalService.listSelloutEfficiencyOcc(propertyId,
                    startQueryDate, endQueryDate);

            // 获取原始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);
                HotelKpiOriginDetailDTO originDetailDTO = hotelKpiService.convert2OriginDetailDTOList(originDetail);

                int asOfMonth = indexYear < lastMonthYearMonth.getYear() ? 12 : lastMonthYearMonth.getMonthValue();

                // 截取 Sellout Efficiency OCC 数据
                long indexStartDate = Long.parseLong(DateTimeUtils.localDateToStr(YearMonth
                        .of(indexYear, 1).atDay(1), BaseConstant.DATE_FORMAT_YYYYMMDD));
                long indexEndDate = Long.parseLong(DateTimeUtils.localDateToStr(YearMonth
                        .of(indexYear, asOfMonth).atEndOfMonth(), BaseConstant.DATE_FORMAT_YYYYMMDD));
                List<SelloutEfficiencyOccInternalDTO> effectiveOccList = occList.stream().filter(item ->
                        item.getDate() >= indexStartDate && item.getDate() <= indexEndDate).toList();
                SelloutEfficiencyInternalDTO selloutEfficiency = gmwrInternalService.getSelloutEfficiency(occSelloutConfig, effectiveOccList);
                // 设置 actual
                setMetricsValue(originDetailDTO, selloutEfficiency, roundingMode);

                String detail = JsonUtils.convertObjToString(objectMapper, originDetailDTO);

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

        /**
         * 设置指标值
         *
         * @param originDetailDTO   原始数值
         * @param selloutEfficiency 数据
         * @param roundingMode      舍入模式
         * @author zc
         * @date 2025/9/13
         */
        private void setMetricsValue(HotelKpiOriginDetailDTO originDetailDTO, SelloutEfficiencyInternalDTO selloutEfficiency, RoundingMode roundingMode) {
            BigDecimal valueIndex1 = Objects.isNull(selloutEfficiency.getPerfectSell()) ? null :
                    new BigDecimal(selloutEfficiency.getPerfectSell().toString());
            if (Objects.nonNull(valueIndex1)) {
                valueIndex1 = valueIndex1.setScale(BaseConstant.DATA_PRECISION, roundingMode);
            }
            // 组装新的 Actual 计算因子 1
            HotelKpiOriginCalculationFactorDTO factorIndex1 = new HotelKpiOriginCalculationFactorDTO().setIndex(1).setCrawl(valueIndex1)
                    .setCrawlOrigin(List.of(HotelKpiOriginCrawlValueIndexDTO.builder().index(1).value(valueIndex1).build()));

            // 替换指标原始数值的 Actual 计算因子 1
            hotelKpiService.replaceOriginFactorList(originDetailDTO.getActual().getCalculationFactor(), factorIndex1);

            BigDecimal valueIndex2 = Objects.isNull(selloutEfficiency.getTechnicalSellout()) ? null :
                    new BigDecimal(selloutEfficiency.getTechnicalSellout().toString());
            if (Objects.nonNull(valueIndex2)) {
                valueIndex2 = valueIndex2.setScale(BaseConstant.DATA_PRECISION, roundingMode);
            }
            // 组装新的 Actual 计算因子 2
            HotelKpiOriginCalculationFactorDTO factorIndex2 = new HotelKpiOriginCalculationFactorDTO().setIndex(2).setCrawl(valueIndex2)
                    .setCrawlOrigin(List.of(HotelKpiOriginCrawlValueIndexDTO.builder().index(1).value(valueIndex2).build()));

            // 替换指标原始数值的 Actual 计算因子 2
            hotelKpiService.replaceOriginFactorList(originDetailDTO.getActual().getCalculationFactor(), factorIndex2);
        }

    }