# 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, audit_log
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', '')
        sku = request.args.get('sku', '')
        search_field = request.args.get('searchField', 'all')
        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', '')
        order_by_column = request.args.get('orderByColumn', '')
        is_asc = request.args.get('isAsc', '')
        advanced_filters_str = request.args.get('advancedFilters', '')

        # 准备额外筛选字典
        extra_filters = {}
        if company:
            extra_filters['company'] = company
        if category:
            extra_filters['category'] = category
        if material_type:
            extra_filters['material_type'] = material_type
        if order_by_column:
            extra_filters['order_by_column'] = order_by_column
        if is_asc:
            extra_filters['is_asc'] = is_asc
        if advanced_filters_str:
            try:
                import json
                advanced_filters = json.loads(advanced_filters_str)
                extra_filters['advanced_filters'] = advanced_filters
            except Exception:
                extra_filters['advanced_filters'] = []

        # 调用服务，传入所有参数
        result = ProductInboundService.get_list(
            page, limit, keyword, sku, search_field, statuses,
            category=extra_filters.get('category'),
            material_type=extra_filters.get('material_type'),
            company=extra_filters.get('company'),
            order_by_column=extra_filters.get('order_by_column'),
            is_asc=extra_filters.get('is_asc'),
            advanced_filters=extra_filters.get('advanced_filters')
        )
        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')
@audit_log(
    module='成品入库',
    action='新增',
    get_target_name_fn=lambda: request.get_json().get('material_name') if request.get_json() else None
)
def submit():
    try:
        data = request.get_json()
        if not data: return jsonify({"code": 400, "msg": "No data"}), 400
        
        # 库位必填校验（安全兜底）
        location = data.get('warehouse_location', '').strip()
        if not location:
            return jsonify({"code": 400, "msg": "入库失败：库位为必填项，不能为空！"}), 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')
@audit_log(
    module='成品入库',
    action='修改',
    get_target_id_fn=lambda: request.view_args.get('id'),
    get_target_name_fn=lambda: request.get_json().get('material_name') if request.get_json() else None
)
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')
@audit_log(
    module='成品入库',
    action='删除',
    get_target_id_fn=lambda: request.view_args.get('id')
)
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
