MealOrderServiceImpl.java 22.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
package com.infoloop.tianting.service.impl;

import com.infoloop.tianting.context.LoginContextHolder;
import com.infoloop.tianting.enums.QueryMealOrderStatusEnum;
import com.infoloop.tianting.exception.ClientEndExceptions;
import com.infoloop.tianting.exception.ErrorCodeEnum;
import com.infoloop.tianting.mealorderservice.*;
import com.infoloop.tianting.model.common.CreatedResult;
import com.infoloop.tianting.model.dto.MealOrderDTO;
import com.infoloop.tianting.model.dto.OrderSubscriptionMessageDTO;
import com.infoloop.tianting.model.vo.DeliveryRuleVO;
import com.infoloop.tianting.model.vo.DinerMealSuspensionRecordVO;
import com.infoloop.tianting.model.vo.MealOrderVO;
import com.infoloop.tianting.service.MealOrderService;
import com.infoloop.tianting.service.client.ClientInventoryServiceRpcClient;
import com.infoloop.tianting.service.client.DeliveryRuleServiceRpcClient;
import com.infoloop.tianting.service.client.MealOrderServiceRpcClient;
import com.infoloop.tianting.utils.DateUtil;
import com.infoloop.tianting.service.SuspensionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.infoloop.tianting.constant.ConfigConstants.MINI_PROGRAM_ORDER_REMINDER_TEMPLATE_ID;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MealOrderServiceImpl implements MealOrderService {

    private final MealOrderServiceRpcClient mealOrderServiceRpcClient;

    private final ClientInventoryServiceRpcClient clientInventoryServiceRpcClient;

    private final DeliveryRuleServiceRpcClient deliveryRuleServiceRpcClient;

    private final SuspensionService suspensionService;

    @Value(MINI_PROGRAM_ORDER_REMINDER_TEMPLATE_ID)
    private String templateId;

    @Override
    public List<MealOrderVO> queryMealOrders(MealOrderDTO.QueryMealOrderDTO queryMealOrderDTO) {
        final var loginInfo = LoginContextHolder.getLoginInfo();
        var mealOrderRpcResponses = mealOrderServiceRpcClient.queryMealOrdersByCondition(loginInfo.getEnterpriseId(), List.of(loginInfo.getId()), null, null);
        final var today = LocalDate.now();
        final var lastWeekStart = today.minusWeeks(1).with(DayOfWeek.MONDAY).atStartOfDay().atZone(DateUtil.CHINA_ZONE).toInstant().toEpochMilli();
        final var lastWeekEnd = today.minusWeeks(1).with(DayOfWeek.SUNDAY).atTime(LocalTime.MAX).atZone(DateUtil.CHINA_ZONE).toInstant().toEpochMilli();
        final var thisWeekStart = today.with(DayOfWeek.MONDAY).atStartOfDay().atZone(DateUtil.CHINA_ZONE).toInstant().toEpochMilli();
        final var thisWeekEnd = today.with(DayOfWeek.SUNDAY).atTime(LocalTime.MAX).atZone(DateUtil.CHINA_ZONE).toInstant().toEpochMilli();
        if (queryMealOrderDTO.getStatus() == QueryMealOrderStatusEnum.COMPLETED) {
            mealOrderRpcResponses = mealOrderRpcResponses.stream()
                    .filter(e -> e.getReserveDate() < lastWeekStart)
                    .toList();
        } else if (queryMealOrderDTO.getStatus() == QueryMealOrderStatusEnum.UNDER_WAY) {
            mealOrderRpcResponses = mealOrderRpcResponses.stream()
                    .filter(e -> e.getReserveDate() >= lastWeekStart && e.getReserveDate() <= lastWeekEnd)
                    .toList();
        } else if (queryMealOrderDTO.getStatus() == QueryMealOrderStatusEnum.BE_BOOKED) {
            mealOrderRpcResponses = mealOrderRpcResponses.stream()
                    .filter(e -> e.getReserveDate() >= thisWeekStart && e.getReserveDate() <= thisWeekEnd)
                    .toList();
        }
        return mealOrderRpcResponses.stream()
                .map(this::getMealOrderById)
                .toList();
    }

    @Override
    public CreatedResult<MealOrderVO> createMealOrder(MealOrderDTO.CreateMealOrderDTO createMealOrderDTO) {
        final var loginInfo = LoginContextHolder.getLoginInfo();
        final var deliveryRule = this.getDeliveryRule();
        final var now = LocalDateTime.now();
        final var nowWithinRange = isNowWithinRange(deliveryRule, now);
        if (!nowWithinRange) {
            throw ClientEndExceptions.IncorrectRequestValue.build(ErrorCodeEnum.MEAL_ORDER_TIME_NOT_IN_RANGE);
        }

        // 1. 获取订餐人信息
        final var dinerById = mealOrderServiceRpcClient.getDinerById(loginInfo.getEnterpriseId(), createMealOrderDTO.getDinerId());
        if (dinerById == null) {
            throw ClientEndExceptions.IncorrectRequestValue.build(ErrorCodeEnum.DINER_NOT_FOUND);
        }

        // 2. 校验订餐人关联关系
        final var mpAccountDinerRefs = mealOrderServiceRpcClient.queryMpAccountDinerRefsByCondition(loginInfo.getEnterpriseId(), Collections.singletonList(loginInfo.getId()), Collections.singletonList(createMealOrderDTO.getDinerId()));
        if (mpAccountDinerRefs.size() != 1) {
            throw ClientEndExceptions.IncorrectRequestValue.build(ErrorCodeEnum.DINER_NOT_FOUND);
        }

        // 3. 校验客户状态
        final var clientById = clientInventoryServiceRpcClient.getClientById(loginInfo.getEnterpriseId(), dinerById.getClientId());
        if (clientById.getClient().getStatus() != 1) {
            throw ClientEndExceptions.IncorrectRequestValue.build(ErrorCodeEnum.CLIENT_NOT_ENABLED);
        }

        // 4. 校验班级信息
        final var gradeClassById = mealOrderServiceRpcClient.getGradeClassById(loginInfo.getEnterpriseId(), dinerById.getClassId());
        if (gradeClassById == null) {
            throw ClientEndExceptions.IncorrectRequestValue.build(ErrorCodeEnum.GRADE_CLASS_NOT_FOUND);
        }

        // 5. 校验停餐记录(学校/班级/学生三个维度最新记录的多段并集区间)
        final var intervals = suspensionService.getSuspensionIntervalsForDiner(
                loginInfo.getEnterpriseId(),
                dinerById.getClientId(),
                dinerById.getClassId(),
                dinerById.getId()
        );
        if (intervals != null && !intervals.isEmpty()) {
            // 校验每个订餐日期是否在停餐时间段内
            for (var meal : createMealOrderDTO.getMeals()) {
                final long mealDateMs = DateUtil.parseDate(meal.getDate()).getTime();
                final boolean inSuspension = intervals.stream()
                        .anyMatch(i -> mealDateMs >= i.startAt && mealDateMs <= i.endAt);
                if (inSuspension) {
                    throw ClientEndExceptions.IncorrectRequestValue.build(ErrorCodeEnum.DINER_MEAL_SUSPENDED);
                }
            }
        }

        // 6. 校验菜单信息
        final var latestMealMenuRecords = mealOrderServiceRpcClient.queryLatestMealMenuRecordsByClientIds(loginInfo.getEnterpriseId(), Collections.singletonList(dinerById.getClientId()));
        if (latestMealMenuRecords.isEmpty()) {
//            throw ClientEndExceptions.IncorrectRequestValue.build(ErrorCodeEnum.MEAL_MENU_NOT_FOUND);
        }

        // 7. 校验是否已预订
        final var reserveDinerMealOrders = mealOrderServiceRpcClient.queryReserveMealOrdersByDinerIds(loginInfo.getEnterpriseId(), Collections.singletonList(createMealOrderDTO.getDinerId()));
        if (!reserveDinerMealOrders.isEmpty()) {
            throw ClientEndExceptions.IncorrectRequestValue.build(ErrorCodeEnum.DINER_ALREADY_RESERVED);
        }

        // 8. 创建订单
        final var mealOrder = mealOrderServiceRpcClient.createMealOrder(loginInfo, MealOrderCreation.newBuilder()
                .setClientId(dinerById.getClientId())
                .setMenuId(latestMealMenuRecords.isEmpty() ? 0 : latestMealMenuRecords.get(0).getId())
                .setAccountId(loginInfo.getId())
                .setOrderMethod(MealOrderOrderMethodEnum.MEAL_ORDER_METHOD_MICRO)
                .setDinerId(createMealOrderDTO.getDinerId())
                .setDinerName(dinerById.getName())
                .setClientName(clientById.getClient().getName())
                .setGradeName(gradeClassById.getGradeName())
                .setClassName(gradeClassById.getClassName())
                .setStudentNo(dinerById.getStudentNo())
                .setReserveDate(now.atZone(DateUtil.CHINA_ZONE).toInstant().toEpochMilli())
                .addAllMeals(createMealOrderDTO.getMeals().stream().map(e -> MenuSchedule.newBuilder()
                        .setDate(e.getDate())
                        .setMenu(e.getMenu())
                        .build()).toList())
                .build());
        return CreatedResult.<MealOrderVO>builder().id(mealOrder.getId()).isCreated(mealOrder.getIsCreated()).build();
    }

    @Override
    public MealOrderVO getMealOrderById(SingleMealOrderRpcResponse mealOrder) {
        return MealOrderVO.builder()
                .id(mealOrder.getId())
                .clientId(mealOrder.getClientId())
                .menuId(mealOrder.getMenuId())
                .accountId(mealOrder.getAccountId())
                .orderMethod(mealOrder.getOrderMethod())
                .dinerId(mealOrder.getDinerId())
                .dinerName(mealOrder.getDinerName())
                .clientName(mealOrder.getClientName())
                .gradeName(mealOrder.getGradeName())
                .className(mealOrder.getClassName())
                .studentNo(mealOrder.getStudentNo())
                .reserveDate(DateUtil.formatDate(mealOrder.getReserveDate()))
                .meals(mealOrder.getMealsList().stream().map(e -> MealOrderVO.Meals.builder().date(e.getDate()).menu(e.getMenu()).build()).toList())
                .build();
    }

    @Override
    public DeliveryRuleVO getDeliveryRule() {
        final var rule = deliveryRuleServiceRpcClient.getDefaultDeliveryTemplateAndRule(LoginContextHolder.getEnterpriseId()).getRule();
        if (rule.getConfigJson().getRulesList().isEmpty()) {
            return DeliveryRuleVO.builder().build();
        }
        return DeliveryRuleVO.builder()
                .startTime(rule.getConfigJson().getRules(0).getStartTime())
                .endTime(rule.getConfigJson().getRules(0).getEndTime())
                .monday(rule.getConfigJson().getRules(0).getMonday())
                .tuesday(rule.getConfigJson().getRules(0).getTuesday())
                .wednesday(rule.getConfigJson().getRules(0).getWednesday())
                .thursday(rule.getConfigJson().getRules(0).getThursday())
                .friday(rule.getConfigJson().getRules(0).getFriday())
                .saturday(rule.getConfigJson().getRules(0).getSaturday())
                .sunday(rule.getConfigJson().getRules(0).getSunday())
                .build();
    }

    private static boolean isNowWithinRange(DeliveryRuleVO rule, LocalDateTime now) {
        if (rule == null || rule.getStartTime() == null || rule.getEndTime() == null) {
            return false;
        }
        final var startTime = LocalTime.parse(rule.getStartTime(), DateUtil.HH_MM_SS);
        final var endTime = LocalTime.parse(rule.getEndTime(), DateUtil.HH_MM_SS);
        final var enabledDays = new ArrayList<DayOfWeek>();
        if (Boolean.TRUE.equals(rule.getMonday())) enabledDays.add(DayOfWeek.MONDAY);
        if (Boolean.TRUE.equals(rule.getTuesday())) enabledDays.add(DayOfWeek.TUESDAY);
        if (Boolean.TRUE.equals(rule.getWednesday())) enabledDays.add(DayOfWeek.WEDNESDAY);
        if (Boolean.TRUE.equals(rule.getThursday())) enabledDays.add(DayOfWeek.THURSDAY);
        if (Boolean.TRUE.equals(rule.getFriday())) enabledDays.add(DayOfWeek.FRIDAY);
        if (Boolean.TRUE.equals(rule.getSaturday())) enabledDays.add(DayOfWeek.SATURDAY);
        if (Boolean.TRUE.equals(rule.getSunday())) enabledDays.add(DayOfWeek.SUNDAY);
        if (enabledDays.isEmpty()) {
            return false;
        }
        final var minDay = Collections.min(enabledDays);
        final var maxDay = Collections.max(enabledDays);
        final var today = now.toLocalDate();
        final var startDateTime = getThisWeekDate(today, minDay).atTime(startTime);
        final var endDateTime = getThisWeekDate(today, maxDay).atTime(endTime);
        return !now.isBefore(startDateTime) && !now.isAfter(endDateTime);
    }

    private static LocalDate getThisWeekDate(LocalDate now, DayOfWeek day) {
        LocalDate monday = now.with(DayOfWeek.MONDAY);
        return monday.plusDays(day.getValue() - 1L); // MONDAY 是 1,SUNDAY 是 7
    }

    @Override
    public List<DinerMealSuspensionRecordVO> queryDinerMealSuspensionRecordsByCondition() {
        final var loginInfo = LoginContextHolder.getLoginInfo();

        // 1. 获取当前登录用户关联的所有订餐人
        var mpAccountDinerRefs = mealOrderServiceRpcClient.queryMpAccountDinerRefsByCondition(
                loginInfo.getEnterpriseId(),
                Collections.singletonList(loginInfo.getId()),
                Collections.emptyList()
        );

        if (mpAccountDinerRefs.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 获取所有订餐人ID
        var dinerIds = mpAccountDinerRefs.stream()
                .map(SingleMpAccountDinerRefRpcResponse::getDinerId)
                .toList();

        // 3. 获取所有订餐人信息
        var diners = mealOrderServiceRpcClient.getDinersByIds(loginInfo.getEnterpriseId(), dinerIds);

        // 4. 使用公共停餐服务:批量计算每个订餐人的多段停餐区间
        Map<Integer, SingleDinerRpcResponse> dinerIdToDiner = diners.stream()
                .collect(Collectors.toMap(SingleDinerRpcResponse::getId, Function.identity()));

        Map<Integer, List<SuspensionService.SuspensionInterval>> dinerIdToIntervals =
                suspensionService.getSuspensionIntervalsForDiners(loginInfo.getEnterpriseId(), diners);

        List<DinerMealSuspensionRecordVO> result = new ArrayList<>();
        for (Map.Entry<Integer, List<SuspensionService.SuspensionInterval>> entry : dinerIdToIntervals.entrySet()) {
            Integer dinerId = entry.getKey();
            SingleDinerRpcResponse dinerInfo = dinerIdToDiner.get(dinerId);
            if (dinerInfo == null) {
                continue;
            }
            List<SuspensionService.SuspensionInterval> intervals = entry.getValue();
            if (intervals == null || intervals.isEmpty()) {
                continue;
            }
            List<DinerMealSuspensionRecordVO.Interval> voIntervals = intervals.stream()
                    .map(i -> DinerMealSuspensionRecordVO.Interval.builder()
                            .startAt(new Date(i.startAt))
                            .endAt(new Date(i.endAt))
                            .comment("")
                            .build())
                    .toList();

            result.add(DinerMealSuspensionRecordVO.builder()
                    .enterpriseId(Long.valueOf(dinerInfo.getEnterpriseId()))
                    .clientId(Long.valueOf(dinerInfo.getClientId()))
                    .classId(Long.valueOf(dinerInfo.getClassId()))
                    .dinerId(Long.valueOf(dinerInfo.getId()))
                    .dinerName(dinerInfo.getName())
                    .studentNo(dinerInfo.getStudentNo())
                    .intervals(voIntervals)
                    .build());
        }
        return result;
    }

    /**
     * 将RPC响应转换为VO对象
     */
    // 已改为统一从 SuspensionService 获取并集窗口,不再需要单条转换

    @Override
    public void createOrderSubscriptionMessage(OrderSubscriptionMessageDTO.CreateOrderSubscriptionMessageDTO dto) {
        final var enterpriseId = LoginContextHolder.getEnterpriseId();
        final var openId = LoginContextHolder.getOpenId();

        if (openId == null || openId.isBlank()) {
            throw new IllegalStateException("当前登录用户 openId 为空,无法创建订阅提醒");
        }
        if (dto.getJumpPath() == null || dto.getJumpPath().isBlank()) {
            throw new IllegalArgumentException("jumpPath 不能为空");
        }

        // 1. 处理就餐人 ID:如果为空,从关联关系推断
        int dinerId = dto.getDinerId() != null ? dto.getDinerId() : getDefaultDinerId(enterpriseId, openId);

        // 2. 处理模板 ID:如果为空,使用配置的默认值
        String finalTemplateId = (dto.getTemplateId() != null && !dto.getTemplateId().isBlank()) 
                ? dto.getTemplateId() 
                : templateId;
        if (finalTemplateId == null || finalTemplateId.isBlank()) {
            throw new IllegalStateException("订阅消息模板ID未配置,无法创建订阅提醒");
        }

        // 3. 先根据订餐规则配置,计算本次"订餐周期"的开始/结束时间
        final var period = resolveOrderPeriod(enterpriseId);

        // 打印所有参数,用于检查库服务版本是否匹配
        log.info("创建订阅消息 - 调用库服务参数: enterpriseId={}, dinerId={}, openId={}, templateId={}, orderPeriodStartDate={}, jumpPath={}, orderPeriodEndDate={}",
                enterpriseId,
                dinerId,
                openId,
                finalTemplateId,
                period.startAt,
                dto.getJumpPath(),
                period.endAt);

        mealOrderServiceRpcClient.createOrderSubscriptionMessage(
                enterpriseId,
                dinerId,
                openId,
                finalTemplateId,
                period.startAt,
                dto.getJumpPath(),
                period.endAt
        );
    }

    /**
     * 如果前端未传就餐人 ID,从当前用户的关联关系中推断默认值
     * 如果只有一个关联的就餐人,返回该就餐人 ID;如果有多个或没有,返回 0
     */
    private int getDefaultDinerId(int enterpriseId, String openId) {
        final var loginInfo = LoginContextHolder.getLoginInfo();
        final var mpAccountDinerRefs = mealOrderServiceRpcClient.queryMpAccountDinerRefsByCondition(
                enterpriseId,
                Collections.singletonList(loginInfo.getId()),
                Collections.emptyList()
        );
        if (mpAccountDinerRefs.size() == 1) {
            return mpAccountDinerRefs.get(0).getDinerId();
        }
        return 0;
    }

    private static final class Period {
        final long startAt;
        final Long endAt;

        private Period(long startAt, Long endAt) {
            this.startAt = startAt;
            this.endAt = endAt;
        }
    }

    /**
     * 根据订餐规则配置推导"最近的未来订餐周期"的开始/结束时间。
     *
     * 规则说明:
     * - 使用 DeliveryRuleServiceRpc.getDefaultDeliveryTemplateAndRule 的 configJson.rules[0]
     * - 该规则包含:startTime / endTime(HH:mm:ss)以及 monday~sunday 开关
     * - 从"当前时刻"开始,向未来查找最近的一个启用日 + startTime 作为周期开始时间
     * - 周期结束时间暂定为:该周最后一个启用日 + endTime(如果滚到了下一周,则用下一周的最后启用日)
     */
    private Period resolveOrderPeriod(int enterpriseId) {
        final var response = deliveryRuleServiceRpcClient.getDefaultDeliveryTemplateAndRule(enterpriseId);
        final var rule = response.getRule();
        if (rule == null || rule.getConfigJson().getRulesList().isEmpty()) {
            throw new IllegalStateException("订餐规则未配置,无法创建订阅提醒");
        }

        final var cfg = rule.getConfigJson().getRules(0);
        final String startTimeStr = cfg.getStartTime();
        final String endTimeStr = cfg.getEndTime();
        if (startTimeStr == null || endTimeStr == null) {
            throw new IllegalStateException("订餐规则时间配置不完整,无法创建订阅提醒");
        }

        final List<DayOfWeek> enabledDays = new ArrayList<>();
        if (cfg.getMonday()) enabledDays.add(DayOfWeek.MONDAY);
        if (cfg.getTuesday()) enabledDays.add(DayOfWeek.TUESDAY);
        if (cfg.getWednesday()) enabledDays.add(DayOfWeek.WEDNESDAY);
        if (cfg.getThursday()) enabledDays.add(DayOfWeek.THURSDAY);
        if (cfg.getFriday()) enabledDays.add(DayOfWeek.FRIDAY);
        if (cfg.getSaturday()) enabledDays.add(DayOfWeek.SATURDAY);
        if (cfg.getSunday()) enabledDays.add(DayOfWeek.SUNDAY);
        if (enabledDays.isEmpty()) {
            throw new IllegalStateException("订餐规则未启用任何星期,无法创建订阅提醒");
        }

        final var startTime = LocalTime.parse(startTimeStr, DateUtil.HH_MM_SS);
        final var endTime = LocalTime.parse(endTimeStr, DateUtil.HH_MM_SS);

        final ZoneId zone = DateUtil.CHINA_ZONE;
        final var now = java.time.ZonedDateTime.now(zone);

        // 从当前时间起,向后最多检查 14 天,找到最近的"启用日 + startTime"
        LocalDate periodStartDate = null;
        DayOfWeek lastEnabledDay = Collections.max(enabledDays);

        for (int i = 0; i < 14; i++) {
            LocalDate candidateDate = now.toLocalDate().plusDays(i);
            DayOfWeek dow = candidateDate.getDayOfWeek();
            if (!enabledDays.contains(dow)) {
                continue;
            }
            var candidateStart = candidateDate.atTime(startTime).atZone(zone);
            if (!candidateStart.isBefore(now)) {
                periodStartDate = candidateDate;
                break;
            }
        }

        if (periodStartDate == null) {
            throw new IllegalStateException("根据订餐规则无法找到未来的订餐周期开始时间");
        }

        // 周期结束时间:使用"同一周内最后一个启用日 + endTime"
        // 这里以 periodStartDate 所在周的周一为基准
        LocalDate monday = periodStartDate.with(DayOfWeek.MONDAY);
        LocalDate lastEnabledDate = monday.plusDays(lastEnabledDay.getValue() - 1L);
        var endDateTime = lastEnabledDate.atTime(endTime).atZone(zone);

        long startMs = periodStartDate.atTime(startTime).atZone(zone).toInstant().toEpochMilli();
        long endMs = endDateTime.toInstant().toEpochMilli();

        return new Period(startMs, endMs);
    }
}