from flask import Blueprint, request, jsonify
from extensions import db
from models import User, Role, Permission, SystemDict, SystemNotification
from middlewares.auth import permission_required

admin_bp = Blueprint('admin', __name__, url_prefix='/api/admin')

# --- 角色管理 ---
@admin_bp.route('/roles', methods=['GET'])
@permission_required('manage_rbac')
def get_roles():
    roles = Role.query.all()
    return jsonify({
        "roles": [{
            "id": r.id,
            "name": r.name,
            "description": r.description,
            "permissions": [p.name for p in r.permissions]
        } for r in roles]
    })

@admin_bp.route('/roles', methods=['POST'])
@permission_required('manage_rbac')
def save_role():
    data = request.json
    role_id = data.get('id')
    
    if role_id:
        role = Role.query.get(role_id)
        if not role: return jsonify({"error": "角色不存在"}), 404
        role.name = data['name']
        role.description = data.get('description')
    else:
        role = Role(name=data['name'], description=data.get('description'))
        db.session.add(role)
    
    if 'permissions' in data:
        perms = Permission.query.filter(Permission.name.in_(data['permissions'])).all()
        role.permissions = perms
        
    db.session.commit()
    return jsonify({"message": "角色保存成功"})

@admin_bp.route('/roles/delete', methods=['POST'])
@permission_required('manage_rbac')
def delete_role():
    data = request.json
    role = Role.query.get(data.get('id'))
    if role:
        if role.name == '超级管理员':
            return jsonify({"error": "不能删除超级管理员角色"}), 400
        db.session.delete(role)
        db.session.commit()
        return jsonify({"message": "角色删除成功"})
    return jsonify({"error": "角色不存在"}), 404

# --- 权限管理 ---
@admin_bp.route('/permissions', methods=['GET'])
@permission_required('manage_rbac')
def get_permissions():
    perms = Permission.query.all()
    return jsonify({
        "permissions": [{"name": p.name, "description": p.description} for p in perms]
    })

# --- 用户角色分配 ---
@admin_bp.route('/users', methods=['GET'])
@permission_required('manage_users')
def get_users():
    users = User.query.all()
    return jsonify({
        "users": [{
            "id": u.id,
            "phone": u.phone,
            "role": u.role.name if u.role else "未分配"
        } for u in users]
    })

@admin_bp.route('/users/assign', methods=['POST'])
@permission_required('manage_users')
def assign_role():
    data = request.json
    user = User.query.get(data['user_id'])
    role = Role.query.get(data['role_id'])
    if user and role:
        user.role = role
        db.session.commit()
        return jsonify({"message": "角色分配成功"})
    return jsonify({"error": "用户或角色不存在"}), 404

# --- 字典管理 ---
@admin_bp.route('/dicts', methods=['GET'])
@permission_required('manage_dicts')
def get_dicts():
    dict_type = request.args.get('type')
    query = SystemDict.query
    if dict_type:
        query = query.filter_by(dict_type=dict_type)
    dicts = query.order_by(SystemDict.dict_type, SystemDict.sort_order.desc()).all()
    return jsonify({
        "dicts": [{
            "id": d.id,
            "dict_type": d.dict_type,
            "label": d.label,
            "value": d.value,
            "cost": d.cost,
            "is_active": d.is_active,
            "sort_order": d.sort_order
        } for d in dicts]
    })

@admin_bp.route('/dicts', methods=['POST'])
@permission_required('manage_dicts')
def save_dict():
    data = request.json
    dict_id = data.get('id')
    
    if dict_id:
        d = SystemDict.query.get(dict_id)
        if not d: return jsonify({"error": "记录不存在"}), 404
    else:
        d = SystemDict()
        db.session.add(d)
        
    d.dict_type = data['dict_type']
    d.label = data['label']
    d.value = data['value']
    d.cost = data.get('cost', 0)
    d.is_active = data.get('is_active', True)
    d.sort_order = data.get('sort_order', 0)
    
    db.session.commit()
    return jsonify({"message": "保存成功"})

@admin_bp.route('/dicts/delete', methods=['POST'])
@permission_required('manage_dicts')
def delete_dict():
    data = request.json
    d = SystemDict.query.get(data.get('id'))
    if d:
        db.session.delete(d)
        db.session.commit()
        return jsonify({"message": "删除成功"})
    return jsonify({"error": "记录不存在"}), 404

# --- 通知管理 ---
@admin_bp.route('/notifications', methods=['GET'])
@permission_required('manage_notifications')
def get_notifications():
    notifs = SystemNotification.query.order_by(SystemNotification.created_at.desc()).all()
    return jsonify({
        "notifications": [{
            "id": n.id,
            "title": n.title,
            "content": n.content,
            "is_active": n.is_active,
            "created_at": n.created_at.strftime('%Y-%m-%d %H:%M')
        } for n in notifs]
    })

@admin_bp.route('/notifications', methods=['POST'])
@permission_required('manage_notifications')
def save_notification():
    data = request.json
    notif_id = data.get('id')
    
    if notif_id:
        n = SystemNotification.query.get(notif_id)
        if not n: return jsonify({"error": "通知不存在"}), 404
    else:
        n = SystemNotification()
        db.session.add(n)
        
    n.title = data['title']
    n.content = data['content']
    n.is_active = data.get('is_active', True)
    
    db.session.commit()
    return jsonify({"message": "通知保存成功"})

@admin_bp.route('/notifications/delete', methods=['POST'])
@permission_required('manage_notifications')
def delete_notification():
    data = request.json
    n = SystemNotification.query.get(data.get('id'))
    if n:
        db.session.delete(n)
        db.session.commit()
        return jsonify({"message": "通知删除成功"})
    return jsonify({"error": "通知不存在"}), 404