from rest_framework import permissions
from rest_framework.permissions import SAFE_METHODS
from django.utils import timezone
from .models import Data, KnowledgeBase, Permission


class DataPermission(permissions.BasePermission):
    """数据访问权限控制"""
    
    def has_permission(self, request, view):
        # 未认证用户无权限
        if not request.user.is_authenticated:
            return False
            
        # 管理员有全部权限
        if request.user.role == 'admin':
            return True
            
        # GET请求检查
        if request.method in SAFE_METHODS:
            return True
            
        # POST请求权限检查
        if request.method == 'POST':
            data_type = request.data.get('type')
            if data_type == 'admin' and request.user.role != 'admin':
                return False
            if data_type == 'leader' and request.user.role not in ['admin', 'leader']:
                return False
            return True
            
        return True

    def has_object_permission(self, request, view, obj):
        user = request.user
        
        # 管理员有全部权限
        if user.role == 'admin':
            return True
            
        # 对象所有者有全部权限
        if obj.user_id == str(user.id):
            return True
            
        # 组长可以访问本部门数据
        if user.role == 'leader' and user.department == obj.department:
            return True
            
        # 其他情况只允许只读访问
        return request.method in SAFE_METHODS


class KnowledgeBasePermission(permissions.BasePermission):
    """知识库权限控制"""
    
    def has_permission(self, request, view):
        if not request.user.is_authenticated:
            return False
            
        # GET请求允许访问
        if request.method in permissions.SAFE_METHODS:
            return True
            
        return True

    def has_object_permission(self, request, view, obj):
        user = request.user
        
        # admin类型: 所有人都可以操作
        if obj.type == 'admin':
            return True
            
        # leader类型: 管理员和本部门组长可以操作
        if obj.type == 'leader':
            if user.role == 'admin':
                return True
            if user.role == 'leader' and user.department == obj.department:
                return True
            return False
            
        # member类型: 管理员、本部门组长可以操作，本部门组员可以查看
        if obj.type == 'member':
            if user.role == 'admin':
                return True
            if user.role == 'leader' and user.department == obj.department:
                return True
            if user.role == 'member' and user.department == obj.department:
                return request.method in permissions.SAFE_METHODS
            return False
            
        # private类型: 创建者可以操作，其他人需要申请权限
        if obj.type == 'private':
            # 创建者可以操作
            if str(obj.user_id) == str(user.id):
                return True
            # 其他人需要申请权限
            return Permission.objects.filter(
                resource_type='knowledge',
                resource_id=str(obj.id),
                applicant=user,
                status='approved',
                expires_at__gt=timezone.now()
            ).exists()
            
        return False


class PermissionRequestPermission(permissions.BasePermission):
    """权限申请的权限控制"""
    
    def has_permission(self, request, view):
        return request.user.is_authenticated

    def has_object_permission(self, request, view, obj):
        user = request.user
        
        # 申请人可以查看自己的申请
        if obj.applicant == user:
            return True
            
        # 审批人可以处理权限申请
        if obj.approver == user:
            return True
            
        # 管理员可以查看所有申请
        if user.role == 'admin':
            return True
            
        return False


class ResourceCRUDPermission(permissions.BasePermission):
    """资源CRUD权限控制"""
    
    def has_permission(self, request, view):
        if not request.user.is_authenticated:
            return False
            
        if request.user.role == 'admin':
            return True
            
        if request.method in SAFE_METHODS:
            return True
            
        return True

    def has_object_permission(self, request, view, obj):
        user = request.user
        
        if user.role == 'admin':
            return True
            
        if hasattr(obj, 'user_id') and str(obj.user_id) == str(user.id):
            return True
            
        if hasattr(obj, 'department') and user.role == 'leader' and user.department == obj.department:
            return True
            
        return request.method in SAFE_METHODS

