-- 验证待派单查询结果

-- 1. 按修复后的条件查询待派单订单（这是后端使用的条件）
SELECT 
    id,
    order_no,
    user_id,
    teacher_id,
    status,
    pay_status,
    service_date,
    create_time,
    update_time
FROM `order`
WHERE pay_status = 1 
  AND status = 0
  AND teacher_id IS NULL 
  AND deleted = 0
ORDER BY create_time DESC;

-- 2. 统计待派单订单数量
SELECT 
    COUNT(*) as pending_count,
    '这是后端返回的待派单数量' as note
FROM `order`
WHERE pay_status = 1 
  AND status = 0
  AND teacher_id IS NULL 
  AND deleted = 0;

-- 3. 检查订单306是否在待派单列表中
SELECT 
    CASE 
        WHEN COUNT(*) > 0 THEN '❌ 订单306仍在待派单列表中（异常）'
        ELSE '✅ 订单306不在待派单列表中（正常）'
    END as check_result
FROM `order`
WHERE id = 306
  AND pay_status = 1 
  AND status = 0
  AND teacher_id IS NULL 
  AND deleted = 0;

-- 4. 查看订单306的当前状态
SELECT 
    id,
    order_no,
    teacher_id,
    status,
    pay_status,
    update_time,
    CASE 
        WHEN teacher_id IS NOT NULL AND status = 1 THEN '✅ 已派单（正常）'
        WHEN teacher_id IS NULL AND status = 0 THEN '⚠️ 待派单（未派单）'
        ELSE '❌ 状态异常'
    END as current_status
FROM `order`
WHERE id = 306;

-- 5. 查看所有已派单但status不是1的订单（可能的异常数据）
SELECT 
    id,
    order_no,
    teacher_id,
    status,
    pay_status,
    update_time,
    '已派单但status不是1' as issue
FROM `order`
WHERE teacher_id IS NOT NULL 
  AND status != 1
  AND pay_status = 1
  AND deleted = 0
ORDER BY update_time DESC
LIMIT 20;

-- 6. 查看所有未派单但status不是0的订单（可能的异常数据）
SELECT 
    id,
    order_no,
    teacher_id,
    status,
    pay_status,
    update_time,
    '未派单但status不是0' as issue
FROM `order`
WHERE teacher_id IS NULL 
  AND status != 0
  AND status NOT IN (4, 5)  -- 排除已完成和已取消
  AND pay_status = 1
  AND deleted = 0
ORDER BY update_time DESC
LIMIT 20;

-- 7. 统计各状态的订单数量
SELECT 
    status,
    COUNT(*) as count,
    SUM(CASE WHEN teacher_id IS NULL THEN 1 ELSE 0 END) as no_teacher_count,
    SUM(CASE WHEN teacher_id IS NOT NULL THEN 1 ELSE 0 END) as has_teacher_count,
    CASE 
        WHEN status = 0 THEN '待派单'
        WHEN status = 1 THEN '已派单/待接单'
        WHEN status = 2 THEN '待服务'
        WHEN status = 3 THEN '服务中'
        WHEN status = 4 THEN '已完成'
        WHEN status = 5 THEN '已取消'
        ELSE '未知状态'
    END as status_name
FROM `order`
WHERE pay_status = 1 AND deleted = 0
GROUP BY status
ORDER BY status;
