package com.sckw.transport.model.enuma;

import com.sckw.core.model.enums.CarWaybillV1Enum;
import lombok.Getter;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 前端运单节点时间轴展示阶段；每一阶段内嵌关联若干 {@link CarWaybillV1Enum}（支持多对一）。
 * <p>
 * 展示顺序：已接单 → 到达装货点 → 已装货 → 已离场 → 已卸货
 */
@Getter
public enum WaybillTimelinePhaseEnum {

    ORDER_ACCEPTED(1, "已接单",
            EnumSet.of(CarWaybillV1Enum.PENDING_VEHICLE)),

    ARRIVED_LOADING_POINT(5, "到达装货点",
            EnumSet.of(CarWaybillV1Enum.REFUSE_TRAFFIC)),

    LOADED(15, "已装货",
            EnumSet.of(
                    CarWaybillV1Enum.EXIT_COMPLETED,
                    CarWaybillV1Enum.EMPTY_WAIT_LEAVE,
                    CarWaybillV1Enum.WAIT_LEAVE,
                    CarWaybillV1Enum.UNLOADING,
                    CarWaybillV1Enum.WAIT_RELEASE,
                    CarWaybillV1Enum.REPLENISHING,
                    CarWaybillV1Enum.REPLENISH_FINISH,
                    CarWaybillV1Enum.RELEASED_NOT_EXITED)),

    DEPARTED(20, "已离场",
            EnumSet.of(
                    CarWaybillV1Enum.WAIT_LOADING,
                    CarWaybillV1Enum.UNLOADING_POINT,
                    CarWaybillV1Enum.UNLOADING_WAIT_LEAVE,
                    CarWaybillV1Enum.UNLOADING_WAIT_RELEASE
//                    CarWaybillV1Enum.UNLOADING_RELEASED_WAIT_LEAVE
            )),

    UNLOADED(25, "已卸货",
            EnumSet.of(
                    CarWaybillV1Enum.COMPLETION_LOADING,
                    CarWaybillV1Enum.REVIEW_REJECTION,
                    CarWaybillV1Enum.CANCELLED));

    private final int phaseOrder;
    private final String phaseLabel;
    private final Set<CarWaybillV1Enum> mappedWaybillStatuses;

    WaybillTimelinePhaseEnum(int phaseOrder, String phaseLabel, Set<CarWaybillV1Enum> mappedWaybillStatuses) {
        this.phaseOrder = phaseOrder;
        this.phaseLabel = phaseLabel;
        this.mappedWaybillStatuses = Collections.unmodifiableSet(mappedWaybillStatuses);
    }

    private static final Map<Integer, WaybillTimelinePhaseEnum> STATUS_CODE_TO_PHASE;

    static {
        Map<Integer, WaybillTimelinePhaseEnum> map = new HashMap<>(32);
        for (WaybillTimelinePhaseEnum phase : values()) {
            for (CarWaybillV1Enum st : phase.mappedWaybillStatuses) {
                map.put(st.getCode(), phase);
            }
        }
        STATUS_CODE_TO_PHASE = Collections.unmodifiableMap(map);
    }

    /**
     * @param waybillStatusCode {@link CarWaybillV1Enum#getCode()}
     */
    public static Optional<WaybillTimelinePhaseEnum> resolve(Integer waybillStatusCode) {
        if (waybillStatusCode == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(STATUS_CODE_TO_PHASE.get(waybillStatusCode));
    }

    public List<Integer> mappedWaybillStatusCodes() {
        return mappedWaybillStatuses.stream().map(CarWaybillV1Enum::getCode).collect(Collectors.toList());
    }
}
