BEGIN;

ALTER TABLE public.ml_orders
    ADD COLUMN IF NOT EXISTS pay_expire_at TIMESTAMPTZ;

ALTER TABLE public.ml_orders
    DROP CONSTRAINT IF EXISTS chk_ml_order_status;

ALTER TABLE public.ml_orders
    DROP CONSTRAINT IF EXISTS chk_ml_payment_status;

ALTER TABLE public.ml_orders
    ADD CONSTRAINT chk_ml_order_status CHECK (order_status IN (1,2,3,4,5,6,7,8));

ALTER TABLE public.ml_orders
    ADD CONSTRAINT chk_ml_payment_status CHECK (payment_status IN (1,2,3,4,5));

COMMENT ON COLUMN public.ml_orders.pay_expire_at IS '支付截止时间，超过后订单进入已超时';

UPDATE public.ml_orders
SET pay_expire_at = created_at + INTERVAL '10 minutes'
WHERE pay_expire_at IS NULL
  AND order_status = 1
  AND payment_status = 1;

UPDATE public.ml_orders
SET order_status = 8,
    payment_status = 5,
    cancel_reason = CASE
        WHEN cancel_reason IS NULL OR cancel_reason = '' THEN '支付超时自动关闭'
        ELSE cancel_reason
    END,
    updated_at = NOW()
WHERE order_status = 1
  AND payment_status = 1
  AND pay_expire_at IS NOT NULL
  AND pay_expire_at <= NOW();

CREATE INDEX IF NOT EXISTS idx_ml_orders_pay_expire_at
ON public.ml_orders(pay_expire_at);

DROP VIEW IF EXISTS public.ml_orders_detail_view;

CREATE VIEW public.ml_orders_detail_view AS
SELECT 
    o.*,
    u.username as customer_name,
    u.phone as customer_phone,
    m.username as merchant_name,
    s.shop_name,
    CASE 
        WHEN o.order_status = 1 THEN '待付款'
        WHEN o.order_status = 2 THEN '待发货'
        WHEN o.order_status = 3 THEN '待收货'
        WHEN o.order_status = 4 THEN '已完成'
        WHEN o.order_status = 5 THEN '已取消'
        WHEN o.order_status = 6 THEN '退款中'
        WHEN o.order_status = 7 THEN '已退款'
        WHEN o.order_status = 8 THEN '已超时'
        ELSE '未知'
    END as order_status_name,
    CASE 
        WHEN o.payment_status = 1 THEN '未付款'
        WHEN o.payment_status = 2 THEN '已付款'
        WHEN o.payment_status = 3 THEN '部分退款'
        WHEN o.payment_status = 4 THEN '全额退款'
        WHEN o.payment_status = 5 THEN '已关闭'
        ELSE '未知'
    END as payment_status_name
FROM public.ml_orders o
LEFT JOIN public.ak_users u ON o.user_id = u.id
LEFT JOIN public.ak_users m ON o.merchant_id = m.id
LEFT JOIN public.ml_shops s ON o.merchant_id = s.merchant_id;

COMMENT ON VIEW public.ml_orders_detail_view IS '订单详情视图';

COMMIT;