-- 每日统计（UTC-5时间）
SELECT
    DATE(DATE_ADD(createdat, INTERVAL -5 HOUR)) AS day,
    COUNT(*) AS total_orders,
    SUM(CASE WHEN ReplaceStatus = 'N' THEN 1 ELSE 0 END) AS cancelled_orders,
    (SELECT COUNT(*)
     FROM label_scan_history
     WHERE DATE(DATE_ADD(createdat, INTERVAL -5 HOUR)) = DATE(DATE_ADD(lr.createdat, INTERVAL -5 HOUR))
    ) AS scan_count,
    (SELECT COUNT(*)
     FROM label_scan_history
     WHERE DATE(DATE_ADD(createdat, INTERVAL -5 HOUR)) = DATE(DATE_ADD(lr.createdat, INTERVAL -5 HOUR))
       AND Result = 0
    ) AS success_scan_count,
    (SELECT COUNT(*)
     FROM label_scan_history
     WHERE DATE(DATE_ADD(createdat, INTERVAL -5 HOUR)) = DATE(DATE_ADD(lr.createdat, INTERVAL -5 HOUR))
       AND Result != 0
    ) AS failed_scan_count,
    -- 每日集包数量
    (SELECT COUNT(DISTINCT btw.id)
     FROM bag_tags bt
     JOIN bag_tag_waybills btw ON bt.TagNumber = btw.TagNumber
     JOIN label_replace_requests lrr2 ON btw.FinalMileTrackingNumber = lrr2.FinalMileTrackingNumber
     WHERE DATE(DATE_ADD(btw.createdat, INTERVAL -5 HOUR)) = DATE(DATE_ADD(lr.createdat, INTERVAL -5 HOUR))
    ) AS bag_count,
    -- 集包扫描次数
    (SELECT COUNT(*)
     FROM order_logs
     WHERE DATE(DATE_ADD(createdat, INTERVAL -5 HOUR)) = DATE(DATE_ADD(lr.createdat, INTERVAL -5 HOUR))
       AND OperationType = '集包'
    ) AS bag_scan_count,
    -- 订单所有操作失败次数
    (SELECT COUNT(*)
     FROM order_logs
     WHERE DATE(DATE_ADD(createdat, INTERVAL -5 HOUR)) = DATE(DATE_ADD(lr.createdat, INTERVAL -5 HOUR))
       AND OperationResult = '失败'
    ) AS order_failed_operations
FROM label_replace_requests lr
GROUP BY day
ORDER BY day;