-- =====================================================
-- 同步现有订单的快递单号到物流追踪表
-- =====================================================
-- 执行时间：2026-04-07
-- 说明：将 zyt_tcm_prescription_order 表中已有的快递单号同步到 zyt_express_tracking 表
-- =====================================================

-- 插入现有订单的快递单号到物流追踪表
-- 只插入有快递单号且不为空的订单
INSERT INTO `zyt_express_tracking` (
    `order_id`,
    `order_type`,
    `tracking_number`,
    `express_company`,
    `recipient_phone`,
    `recipient_name`,
    `recipient_address`,
    `auto_update`,
    `update_interval`,
    `next_update_time`,
    `create_time`,
    `update_time`
)
SELECT 
    o.`id` AS `order_id`,
    'prescription' AS `order_type`,
    o.`tracking_number`,
    CASE 
        WHEN o.`express_company` = '' OR o.`express_company` IS NULL THEN 'auto'
        ELSE o.`express_company`
    END AS `express_company`,
    o.`recipient_phone`,
    o.`recipient_name`,
    o.`shipping_address` AS `recipient_address`,
    1 AS `auto_update`,
    600 AS `update_interval`,
    UNIX_TIMESTAMP() AS `next_update_time`,
    UNIX_TIMESTAMP() AS `create_time`,
    UNIX_TIMESTAMP() AS `update_time`
FROM `zyt_tcm_prescription_order` o
WHERE o.`tracking_number` IS NOT NULL 
    AND o.`tracking_number` != ''
    AND o.`delete_time` IS NULL
    AND NOT EXISTS (
        -- 避免重复插入
        SELECT 1 FROM `zyt_express_tracking` t 
        WHERE t.`tracking_number` = o.`tracking_number`
    );

-- 显示同步结果
SELECT 
    COUNT(*) AS '已同步的快递单号数量'
FROM `zyt_express_tracking`
WHERE `delete_time` IS NULL;

-- 显示待更新的快递单号（未签收的）
SELECT 
    COUNT(*) AS '待自动更新的快递单号数量'
FROM `zyt_express_tracking`
WHERE `auto_update` = 1
    AND `is_signed` = 0
    AND `delete_time` IS NULL;
