package com.ruoyi.app.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.system.domain.PosOrder;
import com.ruoyi.system.domain.flash.FlashDeliveryOrder;
import com.ruoyi.system.mapper.flash.FlashDeliveryOrderMapper;
import com.ruoyi.system.service.IPosOrderService;
import org.springframework.stereotype.Service;

import static com.ruoyi.system.domain.flash.FlashDeliveryStatus.ACCEPTED;
import static com.ruoyi.system.domain.flash.FlashDeliveryStatus.PICKED_UP;

/** 统一判断急送订单与外卖、普通闪送之间的骑手独占规则。 */
@Service
public class RiderDeliveryExclusivityService {
    private static final String URGENT = "URGENT";

    private final IPosOrderService foodOrders;
    private final FlashDeliveryOrderMapper flashOrders;

    public RiderDeliveryExclusivityService(IPosOrderService foodOrders,
                                           FlashDeliveryOrderMapper flashOrders) {
        this.foodOrders = foodOrders;
        this.flashOrders = flashOrders;
    }

    public void assertCanAcceptFood(Long riderId) {
        if (hasActiveFlash(riderId, true)) throw conflict();
    }

    public void assertCanAcceptFlash(Long riderId, String deliveryType) {
        if (URGENT.equals(deliveryType)) {
            if (hasActiveFood(riderId) || hasActiveFlash(riderId, false)) throw conflict();
            return;
        }
        if (hasActiveFlash(riderId, true)) throw conflict();
    }

    private boolean hasActiveFood(Long riderId) {
        QueryWrapper<PosOrder> query = new QueryWrapper<PosOrder>()
                .eq("qs_id", riderId)
                .in("delivery_status", 1, 2)
                .in("state", 0, 1, 2)
                .eq("after_sale_status", 0);
        return foodOrders.count(query) > 0;
    }

    private boolean hasActiveFlash(Long riderId, boolean urgentOnly) {
        QueryWrapper<FlashDeliveryOrder> query = new QueryWrapper<FlashDeliveryOrder>()
                .eq("rider_id", riderId)
                .in("status", ACCEPTED, PICKED_UP);
        if (urgentOnly) query.eq("delivery_type", URGENT);
        return flashOrders.selectCount(query) > 0;
    }

    private ServiceException conflict() {
        return new ServiceException(MessageUtils.message("flash.delivery.rider.exclusive.conflict"));
    }
}
