from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.services.trans_service import TransService
import traceback

trans_bp = Blueprint('transactions', __name__, url_prefix='/transactions')


# --- 借库接口 ---
@trans_bp.route('/borrow', methods=['POST'])
@jwt_required()
def create_borrow():
    data = request.get_json()
    try:
        no = TransService.create_borrow(data)
        return jsonify({'code': 200, 'msg': '借用成功', 'data': {'borrow_no': no}})
    except Exception as e:
        return jsonify({'code': 400, 'msg': str(e)}), 400


# --- 还库辅助：扫码查找借出记录 ---
@trans_bp.route('/return/scan', methods=['GET'])
@jwt_required()
def scan_borrowed_item():
    barcode = request.args.get('barcode')
    if not barcode:
        return jsonify({'code': 400, 'msg': '无条码'}), 400

    res = TransService.scan_for_return(barcode)
    if res:
        return jsonify({'code': 200, 'data': res})
    else:
        return jsonify({'code': 404, 'msg': '未找到该物品的未还记录'}), 404


# --- 还库提交 ---
@trans_bp.route('/return', methods=['POST'])
@jwt_required()
def submit_return():
    data = request.get_json()
    user = get_jwt_identity()  # 库管
    try:
        TransService.process_return(data, operator_name=user)
        return jsonify({'code': 200, 'msg': '还库成功'})
    except Exception as e:
        return jsonify({'code': 400, 'msg': str(e)}), 400


# --- 记录列表 ---
@trans_bp.route('/records', methods=['GET'])
@jwt_required()
def get_records():
    status = request.args.get('status', 'all')
    page = int(request.args.get('page', 1))
    keyword = request.args.get('keyword', '')

    res = TransService.get_records(page=page, limit=10, status=status, keyword=keyword)
    return jsonify({'code': 200, 'data': res})