#!/usr/bin/env python3
"""
批量更新所有待采购订单的推送状态为"是"
"""

import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

import asyncio
import logging
from sqlalchemy import select, update, and_, func
from app.core.database import get_db
from app.models.procurement_orders import ProcurementOrder, ProcurementStatus

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def update_all_push_status():
    """将所有待采购订单的推送状态更新为'是'"""
    
    async for db in get_db():
        try:
            # 首先统计当前的推送状态
            print("\n=== 更新前的统计 ===")
            
            # 统计待采购且未推送的订单
            count_query = select(func.count(ProcurementOrder.id)).where(
                and_(
                    ProcurementOrder.procurement_status == ProcurementStatus.PENDING,
                    ProcurementOrder.已推送 == '否'
                )
            )
            result = await db.execute(count_query)
            unpushed_count = result.scalar()
            
            # 统计待采购且已推送的订单
            pushed_query = select(func.count(ProcurementOrder.id)).where(
                and_(
                    ProcurementOrder.procurement_status == ProcurementStatus.PENDING,
                    ProcurementOrder.已推送 == '是'
                )
            )
            result = await db.execute(pushed_query)
            pushed_count = result.scalar()
            
            print(f"待采购未推送订单: {unpushed_count} 条")
            print(f"待采购已推送订单: {pushed_count} 条")
            
            if unpushed_count == 0:
                print("\n没有需要更新的订单，所有待采购订单都已标记为已推送。")
                return True
            
            # 确认是否执行更新
            print(f"\n准备将 {unpushed_count} 条待采购订单的推送状态更新为'是'")
            confirm = input("确认执行？(yes/y 确认，其他取消): ")
            
            if confirm.lower() not in ['yes', 'y']:
                print("操作已取消")
                return False
            
            # 执行批量更新
            update_stmt = update(ProcurementOrder).where(
                and_(
                    ProcurementOrder.procurement_status == ProcurementStatus.PENDING,
                    ProcurementOrder.已推送 == '否'
                )
            ).values(已推送='是')
            
            result = await db.execute(update_stmt)
            await db.commit()
            
            updated_rows = result.rowcount
            print(f"\n✅ 成功更新 {updated_rows} 条订单的推送状态为'是'")
            
            # 再次统计确认结果
            print("\n=== 更新后的统计 ===")
            
            # 统计更新后的状态
            count_query = select(func.count(ProcurementOrder.id)).where(
                and_(
                    ProcurementOrder.procurement_status == ProcurementStatus.PENDING,
                    ProcurementOrder.已推送 == '否'
                )
            )
            result = await db.execute(count_query)
            unpushed_count = result.scalar()
            
            pushed_query = select(func.count(ProcurementOrder.id)).where(
                and_(
                    ProcurementOrder.procurement_status == ProcurementStatus.PENDING,
                    ProcurementOrder.已推送 == '是'
                )
            )
            result = await db.execute(pushed_query)
            pushed_count = result.scalar()
            
            print(f"待采购未推送订单: {unpushed_count} 条")
            print(f"待采购已推送订单: {pushed_count} 条")
            
            # 显示一些样本数据
            sample_query = select(
                ProcurementOrder.原始订单编号,
                ProcurementOrder.线上宝贝名称,
                ProcurementOrder.procurement_method,
                ProcurementOrder.已推送
            ).where(
                ProcurementOrder.procurement_status == ProcurementStatus.PENDING
            ).limit(5)
            
            result = await db.execute(sample_query)
            samples = result.all()
            
            if samples:
                print("\n=== 更新后的订单示例 ===")
                for s in samples:
                    product = s.线上宝贝名称[:40] + ".." if len(s.线上宝贝名称) > 40 else s.线上宝贝名称
                    print(f"订单号: {s.原始订单编号}, 商品: {product}, 方式: {s.procurement_method}, 已推送: {s.已推送}")
            
            return True
            
        except Exception as e:
            logger.error(f"更新推送状态时出错: {e}", exc_info=True)
            await db.rollback()
            print(f"\n❌ 更新失败: {e}")
            return False
        finally:
            await db.close()
            break

if __name__ == "__main__":
    print("批量更新待采购订单推送状态工具")
    print("=" * 50)
    asyncio.run(update_all_push_status())