from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required
from . import inbound_bp
from app.schemas.stock_schema import stock_service_schema
from app.services.inbound.service_service import ServiceService
from app.utils.decorators import role_required


@inbound_bp.route('/service/search-base', methods=['GET'])
@jwt_required()
def search_base():
    """搜索基础物料"""
    keyword = request.args.get('keyword', '')
    try:
        data = ServiceService.search_base_material(keyword)
        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

@inbound_bp.route('/service', methods=['GET'])
@jwt_required()
def get_service_list():
    """获取服务权益列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    keyword = request.args.get('keyword', None)
    start_date = request.args.get('start_date', None)
    end_date = request.args.get('end_date', None)
    provider_name = request.args.get('provider_name', None)

    try:
        result = ServiceService.get_service_list(
            page=page,
            per_page=per_page,
            keyword=keyword,
            start_date=start_date,
            end_date=end_date,
            provider_name=provider_name
        )
        return jsonify({
            'code': 200,
            'msg': 'success',
            'data': result
        })
    except Exception as e:
        current_app.logger.error(f'获取服务列表失败: {str(e)}')
        return jsonify({'code': 500, 'msg': '内部服务器错误'}), 500


@inbound_bp.route('/service', methods=['POST'])
@jwt_required()
@role_required('admin,manager')
def create_service():
    """创建服务权益"""
    data = request.get_json()
    if not data:
        return jsonify({'code': 400, 'msg': '请求数据为空'}), 400
    errors = stock_service_schema.validate(data)
    if errors:
        return jsonify({'code': 400, 'msg': '数据校验失败', 'errors': errors}), 400
    try:
        service = ServiceService.create_service(data)
        return jsonify({
            'code': 201,
            'msg': '创建成功',
            'data': stock_service_schema.dump(service)
        }), 201
    except ValueError as e:
        return jsonify({'code': 400, 'msg': str(e)}), 400
    except Exception as e:
        current_app.logger.error(f'创建服务权益失败: {str(e)}')
        return jsonify({'code': 500, 'msg': '内部服务器错误'}), 500


@inbound_bp.route('/service/<int:service_id>', methods=['GET'])
@jwt_required()
def get_service(service_id):
    """获取单个服务权益详情"""
    try:
        service = ServiceService.get_service(service_id)
        return jsonify({
            'code': 200,
            'msg': 'success',
            'data': stock_service_schema.dump(service)
        })
    except ValueError as e:
        return jsonify({'code': 404, 'msg': str(e)}), 404
    except Exception as e:
        current_app.logger.error(f'获取服务权益详情失败: {str(e)}')
        return jsonify({'code': 500, 'msg': '内部服务器错误'}), 500


@inbound_bp.route('/service/<int:service_id>', methods=['PUT'])
@jwt_required()
@role_required('admin,manager')
def update_service(service_id):
    """更新服务权益"""
    data = request.get_json()
    if not data:
        return jsonify({'code': 400, 'msg': '请求数据为空'}), 400
    # 部分字段不允许更新，可在此过滤
    allowed_fields = {'sale_price', 'provider_name', 'description'}
    filtered_data = {k: v for k, v in data.items() if k in allowed_fields}
    if not filtered_data:
        return jsonify({'code': 400, 'msg': '无有效更新字段'}), 400
    try:
        service = ServiceService.update_service(service_id, filtered_data)
        return jsonify({
            'code': 200,
            'msg': '更新成功',
            'data': stock_service_schema.dump(service)
        })
    except ValueError as e:
        return jsonify({'code': 404, 'msg': str(e)}), 404
    except Exception as e:
        current_app.logger.error(f'更新服务权益失败: {str(e)}')
        return jsonify({'code': 500, 'msg': '内部服务器错误'}), 500


@inbound_bp.route('/service/<int:service_id>', methods=['DELETE'])
@jwt_required()
@role_required('admin,manager')
def delete_service(service_id):
    """删除服务权益"""
    try:
        ServiceService.delete_service(service_id)
        return jsonify({
            'code': 200,
            'msg': '删除成功'
        })
    except ValueError as e:
        return jsonify({'code': 404, 'msg': str(e)}), 404
    except Exception as e:
        current_app.logger.error(f'删除服务权益失败: {str(e)}')
        return jsonify({'code': 500, 'msg': '内部服务器错误'}), 500
