-- ============================================================================
-- 派单失败诊断脚本
-- 执行时间: 2026-06-10
-- 目的: 诊断为什么派单返回 ALL_ELIGIBLE_STAFF_BUSY
-- ============================================================================

-- 1. 查看问题订单的详细信息
SELECT 
    id,
    order_no,
    status,
    payment_status,
    dispatch_status,
    dispatch_error_code,
    dispatch_error_message,
    service_lat,
    service_lng,
    dispatch_station_id,
    required_qualification_code,
    scheduled_start_at,
    scheduled_end_at,
    appointment_time,
    address_snapshot_json->>'latitude' as address_lat,
    address_snapshot_json->>'longitude' as address_lng,
    created_at
FROM public.hss_service_orders
WHERE id = 'so-1781054320183-35441'
  AND deleted_at IS NULL;

-- 2. 查看所有在线服务人员
SELECT 
    id,
    status,
    is_active,
    online_status,
    uid,
    station_id,
    current_lat,
    current_lng,
    dispatch_radius_km,
    last_dispatched_at
FROM public.ml_delivery_staff
WHERE deleted_at IS NULL
  AND status = 1
  AND COALESCE(is_active, TRUE) = TRUE
ORDER BY id;

-- 3. 查看服务人员的活跃派单记录（关键：哪些人员在忙）
SELECT 
    sa.id as assignment_id,
    sa.staff_id,
    sa.order_id,
    sa.status as assignment_status,
    sa.assigned_at,
    so.status as order_status,
    so.appointment_time,
    so.scheduled_start_at,
    so.scheduled_end_at
FROM public.hss_service_assignments sa
JOIN public.hss_service_orders so ON so.id = sa.order_id
WHERE sa.deleted_at IS NULL
  AND sa.status IN ('assigned', 'accepted', 'departed', 'arrived', 'serving', 'in_service')
ORDER BY sa.assigned_at DESC
LIMIT 20;

-- 4. 查看是否有服务人员在任何活跃任务中
SELECT 
    s.id as staff_id,
    s.online_status,
    COUNT(DISTINCT sa.id) as active_assignment_count
FROM public.ml_delivery_staff s
LEFT JOIN public.hss_service_assignments sa 
    ON sa.staff_id::TEXT = s.id::TEXT
    AND sa.deleted_at IS NULL
    AND sa.status IN ('assigned', 'accepted', 'departed', 'arrived', 'serving', 'in_service')
WHERE s.deleted_at IS NULL
  AND s.status = 1
  AND COALESCE(s.is_active, TRUE) = TRUE
  AND s.online_status = 'online'
GROUP BY s.id, s.online_status
ORDER BY active_assignment_count DESC;

-- 5. 修复建议：如果订单有地址经纬度，更新到订单主表
UPDATE public.hss_service_orders
SET 
    service_lat = (address_snapshot_json->>'latitude')::FLOAT,
    service_lng = (address_snapshot_json->>'longitude')::FLOAT,
    updated_at = clock_timestamp()
WHERE id = 'so-1781054320183-35441'
  AND (service_lat IS NULL OR service_lng IS NULL)
  AND address_snapshot_json->>'latitude' != '';

-- 6. 更新后验证
SELECT 
    id,
    service_lat,
    service_lng,
    address_snapshot_json->>'latitude' as address_lat,
    address_snapshot_json->>'longitude' as address_lng
FROM public.hss_service_orders
WHERE id = 'so-1781054320183-35441';
