from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAuthenticated

from utils.custom import CommonPagination
from ..permission import RbacPermission
from ..models import Role
from ..serializers.role_serializer import RoleListSerializer, RoleModifySerializer
from rest_framework.response import Response
from rest_framework import status


class RoleViewSet(ModelViewSet):
    """
    角色管理：增删改查
    """
    perms_map = ({'get': 'role_list'}, {'post': 'role_create'}, {'put': 'role_update'},
                 {'delete': 'role_delete'})
    queryset = Role.objects.filter(is_delete=0).all().order_by('-id')
    serializer_class = RoleListSerializer
    pagination_class = None
    filter_backends = (SearchFilter, OrderingFilter)
    search_fields = ('name',)
    ordering_fields = ('id',)

    def get_serializer_class(self):
        if self.action == 'list':
            return RoleListSerializer
        return RoleModifySerializer
        
    def check_permissions(self, request):
        """
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        """
        if request.method == 'GET':
            pass
        else:
            for permission in self.get_permissions():
                if not permission.has_permission(request, self):
                    self.permission_denied(
                        request, message=getattr(permission, 'message', None)
                    )

    def destroy(self, request, *args, **kwargs): #逻辑删除
        instance = self.get_object()
        # self.perform_destroy(instance)
        instance.is_delete = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
