from flask import Blueprint, request, jsonify, current_app
from app.services.bom_service import BomService
from app.models.base import MaterialBase
from flask_jwt_extended import jwt_required

bom_bp = Blueprint('bom', __name__)

@bom_bp.route('/<int:parent_id>', methods=['GET'])
@jwt_required()
def get_bom(parent_id):
    try:
        data = BomService.get_bom_with_stock(parent_id)
        return jsonify({
            'code': 200,
            'msg': 'success',
            'data': data
        })
    except Exception as e:
        current_app.logger.error(f'获取BOM失败: {str(e)}')
        return jsonify({'code': 500, 'msg': '内部服务器错误'}), 500

@bom_bp.route('', methods=['POST'])
@jwt_required()
def save_bom():
    try:
        req_data = request.get_json()
        parent_id = req_data.get('parent_id')
        child_list = req_data.get('children', [])
        if not parent_id or not isinstance(child_list, list):
            return jsonify({'code': 400, 'msg': '参数错误'}), 400
        BomService.create_or_update_bom(parent_id, child_list)
        return jsonify({
            'code': 200,
            'msg': '保存成功'
        })
    except Exception as e:
        current_app.logger.error(f'保存BOM失败: {str(e)}')
        return jsonify({'code': 500, 'msg': '内部服务器错误'}), 500

@bom_bp.route('/base/list', methods=['GET'])
@jwt_required()
def get_material_base_list():
    """获取所有基础物料列表，用于前端下拉框"""
    try:
        materials = MaterialBase.query.filter_by(is_enabled=True).order_by(MaterialBase.id.desc()).all()
        data = [item.to_dict() for item in materials]
        return jsonify({
            'code': 200,
            'msg': 'success',
            'data': data
        })
    except Exception as e:
        current_app.logger.error(f'获取基础物料列表失败: {str(e)}')
        return jsonify({'code': 500, 'msg': '内部服务器错误'}), 500
