# inventory-backend/app/api/v1/inbound/product.py
from flask import Blueprint, request, jsonify
from app.services.inbound.product_service import ProductInboundService
from app.utils.decorators import permission_required
import traceback

# === 这一行非常关键，绝对不能丢！===
inbound_product_bp = Blueprint('stock_product', __name__)

def get_current_user_permissions():
    from flask_jwt_extended import get_jwt
    from app.services.auth_service import AuthService
    claims = get_jwt()
    user_role = claims.get('role')
    if not user_role: return []
    if user_role.upper() == 'SUPER_ADMIN': return ['inbound_product:*']
    perm_dict = AuthService.get_user_permissions(user_role)
    return perm_dict.get('menus', []) + perm_dict.get('elements', [])

def filter_item_by_permissions(item_dict, user_permissions):
    field_to_perm = {
        'id': 'inbound_product:id', 'base_id': 'inbound_product:base_id', 'company_name': 'inbound_product:company_name',
        'material_name': 'inbound_product:material_name', 'category': 'inbound_product:category',
        'material_type': 'inbound_product:material_type', 'spec_model': 'inbound_product:spec_model',
        'unit': 'inbound_product:unit', 'sku': 'inbound_product:sku', 'inbound_date': 'inbound_product:inbound_date',
        'barcode': 'inbound_product:barcode', 'serial_number': 'inbound_product:serial_number',
        'status': 'inbound_product:status', 'quality_status': 'inbound_product:quality_status',
        'in_quantity': 'inbound_product:in_quantity', 'stock_quantity': 'inbound_product:stock_quantity',
        'available_quantity': 'inbound_product:available_quantity', 'warehouse_location': 'inbound_product:warehouse_location',
        'bom_code': 'inbound_product:bom_code', 'bom_version': 'inbound_product:bom_version',
        'work_order_code': 'inbound_product:work_order_code', 'order_id': 'inbound_product:order_id',
        'production_manager': 'inbound_product:production_manager', 'production_start_time': 'inbound_product:production_start_time',
        'production_end_time': 'inbound_product:production_end_time', 'raw_material_cost': 'inbound_product:raw_material_cost',
        'manual_cost': 'inbound_product:manual_cost', 'sale_price': 'inbound_product:sale_price',
        'product_photo': 'inbound_product:product_photo', 'quality_report_link': 'inbound_product:quality_report_link',
        'inspection_report_link': 'inbound_product:inspection_report_link', 'detail_link': 'inbound_product:detail_link',
    }
    if 'inbound_product:*' in user_permissions: return item_dict
    for field, perm_code in field_to_perm.items():
        if field in item_dict and perm_code not in user_permissions: item_dict[field] = None
    return item_dict

@inbound_product_bp.route('/search-base', methods=['GET'])
@permission_required('inbound_product')
def search_base():
    try:
        keyword = request.args.get('keyword', '')
        page = request.args.get('page', 1, type=int)
        result = ProductInboundService.search_base_material(keyword, page)
        user_permissions = get_current_user_permissions()
        if result.get('items'):
            result['items'] = [filter_item_by_permissions(item, user_permissions) for item in result['items']]
        return jsonify({"code": 200, "msg": "success", "data": result})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500

@inbound_product_bp.route('/search-bom', methods=['GET'])
@permission_required('inbound_product')
def search_bom():
    try:
        keyword = request.args.get('keyword', '')
        data = ProductInboundService.search_bom_options(keyword)
        return jsonify({"code": 200, "msg": "success", "data": data})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500

@inbound_product_bp.route('/list', methods=['GET'])
@permission_required('inbound_product')
def get_list():
    try:
        page = request.args.get('page', 1, type=int)
        limit = request.args.get('pageSize', 15, type=int)
        keyword = request.args.get('keyword', '')
        statuses_str = request.args.get('statuses', '')
        statuses = statuses_str.split(',') if statuses_str else []
        category = request.args.get('category', '')
        material_type = request.args.get('material_type', '')
        company = request.args.get('company', '')
        result = ProductInboundService.get_list(page, limit, keyword, statuses, category, material_type, company)
        user_permissions = get_current_user_permissions()
        if result.get('items'):
            result['items'] = [filter_item_by_permissions(item, user_permissions) for item in result['items']]
        return jsonify({"code": 200, "msg": "success", "data": result})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500

@inbound_product_bp.route('/submit', methods=['POST'])
@permission_required('inbound_product:operation')
def submit():
    try:
        data = request.get_json()
        if not data: return jsonify({"code": 400, "msg": "No data"}), 400
        user_permissions = get_current_user_permissions()
        if 'inbound_product:*' not in user_permissions:
            field_to_perm = {'id': 'inbound_product:id', 'base_id': 'inbound_product:base_id', 'company_name': 'inbound_product:company_name', 'material_name': 'inbound_product:material_name', 'category': 'inbound_product:category', 'material_type': 'inbound_product:material_type', 'spec_model': 'inbound_product:spec_model', 'unit': 'inbound_product:unit', 'sku': 'inbound_product:sku', 'inbound_date': 'inbound_product:inbound_date', 'barcode': 'inbound_product:barcode', 'serial_number': 'inbound_product:serial_number', 'status': 'inbound_product:status', 'quality_status': 'inbound_product:quality_status', 'in_quantity': 'inbound_product:in_quantity', 'stock_quantity': 'inbound_product:stock_quantity', 'available_quantity': 'inbound_product:available_quantity', 'warehouse_location': 'inbound_product:warehouse_location', 'bom_code': 'inbound_product:bom_code', 'bom_version': 'inbound_product:bom_version', 'work_order_code': 'inbound_product:work_order_code', 'order_id': 'inbound_product:order_id', 'production_manager': 'inbound_product:production_manager', 'production_start_time': 'inbound_product:production_start_time', 'production_end_time': 'inbound_product:production_end_time', 'raw_material_cost': 'inbound_product:raw_material_cost', 'manual_cost': 'inbound_product:manual_cost', 'sale_price': 'inbound_product:sale_price', 'product_photo': 'inbound_product:product_photo', 'quality_report_link': 'inbound_product:quality_report_link', 'inspection_report_link': 'inbound_product:inspection_report_link', 'detail_link': 'inbound_product:detail_link'}
            for field in list(data.keys()):
                perm_code = field_to_perm.get(field)
                if perm_code and perm_code not in user_permissions: data.pop(field, None)
        new_stock = ProductInboundService.handle_inbound(data)
        return jsonify({"code": 200, "msg": "入库成功", "data": new_stock.to_dict()})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500

@inbound_product_bp.route('/<int:id>', methods=['PUT'])
@permission_required('inbound_product:operation')
def update(id):
    try:
        data = request.get_json()
        user_permissions = get_current_user_permissions()
        if 'inbound_product:*' not in user_permissions:
            field_to_perm = {'id': 'inbound_product:id', 'base_id': 'inbound_product:base_id', 'company_name': 'inbound_product:company_name', 'material_name': 'inbound_product:material_name', 'category': 'inbound_product:category', 'material_type': 'inbound_product:material_type', 'spec_model': 'inbound_product:spec_model', 'unit': 'inbound_product:unit', 'sku': 'inbound_product:sku', 'inbound_date': 'inbound_product:inbound_date', 'barcode': 'inbound_product:barcode', 'serial_number': 'inbound_product:serial_number', 'status': 'inbound_product:status', 'quality_status': 'inbound_product:quality_status', 'in_quantity': 'inbound_product:in_quantity', 'stock_quantity': 'inbound_product:stock_quantity', 'available_quantity': 'inbound_product:available_quantity', 'warehouse_location': 'inbound_product:warehouse_location', 'bom_code': 'inbound_product:bom_code', 'bom_version': 'inbound_product:bom_version', 'work_order_code': 'inbound_product:work_order_code', 'order_id': 'inbound_product:order_id', 'production_manager': 'inbound_product:production_manager', 'production_start_time': 'inbound_product:production_start_time', 'production_end_time': 'inbound_product:production_end_time', 'raw_material_cost': 'inbound_product:raw_material_cost', 'manual_cost': 'inbound_product:manual_cost', 'sale_price': 'inbound_product:sale_price', 'product_photo': 'inbound_product:product_photo', 'quality_report_link': 'inbound_product:quality_report_link', 'inspection_report_link': 'inbound_product:inspection_report_link', 'detail_link': 'inbound_product:detail_link'}
            for field in list(data.keys()):
                perm_code = field_to_perm.get(field)
                if perm_code and perm_code not in user_permissions: data.pop(field, None)
        ProductInboundService.update_inbound(id, data)
        return jsonify({"code": 200, "msg": "更新成功"})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500

@inbound_product_bp.route('/<int:id>', methods=['DELETE'])
@permission_required('inbound_product:operation')
def delete(id):
    try:
        ProductInboundService.delete_inbound(id)
        return jsonify({"code": 200, "msg": "删除成功"})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500

@inbound_product_bp.route('/<int:id>/history', methods=['GET'])
@permission_required('inbound_product')
def get_history(id):
    try:
        data = ProductInboundService.get_outbound_history(id)
        return jsonify({"code": 200, "msg": "success", "data": data})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500

@inbound_product_bp.route('/suggestions/users', methods=['GET'])
@permission_required('inbound_product')
def get_user_suggestions():
    keyword = request.args.get('keyword', '')
    data = ProductInboundService.search_system_users(keyword)
    return jsonify({"code": 200, "msg": "success", "data": data})

@inbound_product_bp.route('/options', methods=['GET'])
@permission_required('inbound_product')
def get_options():
    try:
        data = ProductInboundService.get_filter_options()
        return jsonify({"code": 200, "msg": "success", "data": data})
    except Exception as e:
        return jsonify({"code": 500, "msg": str(e)}), 500

@inbound_product_bp.route('/suggestions/managers', methods=['GET'])
@permission_required('inbound_product')
def get_manager_history():
    keyword = request.args.get('keyword', '')
    try:
        data = ProductInboundService.get_history_managers(keyword)
        return jsonify({"code": 200, "msg": "success", "data": data})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500

# ------------------------------------------------------------------
# 9. BOM 原材料成本自动核算 (新增)
# ------------------------------------------------------------------
@inbound_product_bp.route('/calculate-bom-cost', methods=['GET'])
@permission_required('inbound_product')
def calculate_bom_cost():
    try:
        bom_code = request.args.get('bom_code')
        bom_version = request.args.get('bom_version')
        if not bom_code or not bom_version:
            return jsonify({"code": 400, "msg": "bom_code和bom_version不能为空"}), 400
        cost = ProductInboundService.calculate_bom_cost(bom_code, bom_version)
        return jsonify({"code": 200, "msg": "success", "data": cost})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500