# 文件路径: app/api/v1/inbound/base.py
from flask import Blueprint, request, jsonify
from app.services.inbound.base_service import MaterialBaseService
import traceback

inbound_base_bp = Blueprint('stock_base', __name__)


# ==============================================================================
# 1. 搜索接口 (GET /api/v1/inbound/base/search)
# ==============================================================================
@inbound_base_bp.route('/search', methods=['GET'])
def search_base():
    try:
        keyword = request.args.get('keyword', '')
        data = MaterialBaseService.search_material(keyword)
        return jsonify({"code": 200, "msg": "success", "data": data})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500


# ==============================================================================
# 2. 列表接口 (GET /api/v1/inbound/base/list)
# ==============================================================================
@inbound_base_bp.route('/list', methods=['GET'])
def get_list():
    try:
        page = request.args.get('pageNum', 1, type=int)  # 前端传的是 pageNum
        limit = request.args.get('pageSize', 10, type=int)

        # 构造筛选条件
        filters = {
            'keyword': request.args.get('keyword', ''),
            'category': request.args.get('category', ''),
            'type': request.args.get('type', ''),
            'isEnabled': request.args.get('isEnabled', None)
        }

        result = MaterialBaseService.get_list(page, limit, filters)
        return jsonify({"code": 200, "msg": "success", "data": result})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500


# ==============================================================================
# 3. 新增接口 (POST /api/v1/inbound/base/)
# 注意：前端 material_base.ts 可能会请求 / 或 /add，这里统一匹配
# ==============================================================================
@inbound_base_bp.route('/', methods=['POST'])
def create():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"code": 400, "msg": "No data provided"}), 400

        MaterialBaseService.create_material(data)
        return jsonify({"code": 200, "msg": "新增成功"})
    except ValueError as e:
        # 捕获业务逻辑验证错误 (如名称为空)
        return jsonify({"code": 400, "msg": str(e)}), 400
    except Exception as e:
        # 捕获系统错误
        traceback.print_exc()
        return jsonify({"code": 500, "msg": f"系统错误: {str(e)}"}), 500


# ==============================================================================
# 4. 修改接口 (PUT /api/v1/inbound/base/<id>)
# ==============================================================================
@inbound_base_bp.route('/<int:id>', methods=['PUT'])
def update(id):
    try:
        data = request.get_json()
        MaterialBaseService.update_material(id, data)
        return jsonify({"code": 200, "msg": "修改成功"})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500


# ==============================================================================
# 5. 删除接口 (DELETE /api/v1/inbound/base/<id>)
# ==============================================================================
@inbound_base_bp.route('/<int:id>', methods=['DELETE'])
def delete(id):
    try:
        MaterialBaseService.delete_material(id)
        return jsonify({"code": 200, "msg": "删除成功"})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"code": 500, "msg": str(e)}), 500