from flask import Blueprint, jsonify, request
from app.extensions import db
# ★★★ 修复点：必须引入 datetime，否则下方更新时间时会报错 500 ★★★
from datetime import datetime

# 导入模型
from app.models.inbound.buy import StockBuy
from app.models.inbound.stocktake import StocktakeDraft

# 尝试导入半成品和成品
try:
    from app.models.inbound.semi import StockSemi
except ImportError:
    StockSemi = None

try:
    from app.models.inbound.product import StockProduct
except ImportError:
    StockProduct = None

from app.services.print.network_print_service import NetworkPrintService

bp = Blueprint('stock_ops', __name__)


@bp.route('/all', methods=['GET'])
def get_all_stock():
    """
    获取所有库存 > 0 的物品
    """
    try:
        # 1. 采购件
        materials = []
        if StockBuy:
            materials = StockBuy.query.filter(StockBuy.stock_quantity > 0).all()

        # 2. 半成品
        semis = []
        if StockSemi:
            try:
                semis = StockSemi.query.filter(StockSemi.stock_quantity > 0).all()
            except Exception:
                semis = []

        # 3. 成品
        products = []
        if StockProduct:
            try:
                products = StockProduct.query.filter(StockProduct.stock_quantity > 0).all()
            except Exception:
                products = []

        return jsonify({
            "materials": [item.to_dict() for item in materials],
            "semis": [item.to_dict() for item in semis],
            "products": [item.to_dict() for item in products]
        }), 200
    except Exception as e:
        print(f"Error: {e}")
        return jsonify({"message": f"查询库存失败: {str(e)}"}), 500


# --- 草稿箱接口 ---

@bp.route('/draft/list', methods=['GET'])
def get_drafts():
    """获取当前用户的盘点进度"""
    user_id = request.args.get('user_id', 'admin')
    drafts = StocktakeDraft.query.filter_by(user_id=user_id).all()
    return jsonify([d.to_dict() for d in drafts]), 200


@bp.route('/draft/add', methods=['POST'])
def add_draft():
    """扫码同步 (支持更新数量)"""
    try:
        data = request.json
        user_id = data.get('user_id', 'admin')
        uuid = data.get('uuid')
        quantity = data.get('quantity', 1)

        # 查找是否已存在
        draft = StocktakeDraft.query.filter_by(user_id=user_id, uuid=uuid).first()

        if draft:
            # 如果已存在，更新数量和时间
            draft.quantity = quantity
            # ★ 修复点：这里需要 datetime 对象
            draft.scan_time = datetime.now()
        else:
            # 如果不存在，创建新的
            draft = StocktakeDraft(user_id=user_id, uuid=uuid, quantity=quantity)
            db.session.add(draft)

        db.session.commit()
        return jsonify({"message": "Saved"}), 200
    except Exception as e:
        print(f"Add Draft Error: {e}")
        return jsonify({"message": str(e)}), 500


@bp.route('/draft/clear', methods=['POST'])
def clear_draft():
    """清空进度"""
    data = request.json
    user_id = data.get('user_id', 'admin')

    StocktakeDraft.query.filter_by(user_id=user_id).delete()
    db.session.commit()
    return jsonify({"message": "Cleared"}), 200


# --- 打印接口 ---

@bp.route('/print/selection', methods=['POST'])
def print_selection():
    try:
        data = request.json
        items = data.get('items', [])
        if not items: return jsonify({"message": "未选择任何物品"}), 400
        printer = NetworkPrintService()
        success, msg = printer.print_outbound_selection(items)
        return jsonify({"message": "打印指令已发送" if success else msg}), 200 if success else 500
    except Exception as e:
        return jsonify({"message": str(e)}), 500


@bp.route('/print/stocktake', methods=['POST'])
def print_stocktake():
    try:
        data = request.json
        printer = NetworkPrintService()
        success, msg = printer.print_stocktake_report(data)
        return jsonify({"message": "盘点报告已发送" if success else msg}), 200 if success else 500
    except Exception as e:
        return jsonify({"message": str(e)}), 500