from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from utils.custom import CommonPagination, TreeAPIView
from ..permission import RbacPermission
from ..models import Organization
from ..serializers.organization_serializer import OrganizationSerializer, OrganizationUserTreeSerializer


class OrganizationViewSet(ModelViewSet):
    """
    组织机构：增删改查
    """
    perms_map = (
        {'get': 'organization_list'}, {'post': 'organization_create'},
        {'put': 'organization_update'}, {'delete': 'organization_delete'})
    queryset = Organization.objects.filter(is_delete=0).all()
    serializer_class = OrganizationSerializer
    pagination_class = None #不分页
    filter_backends = (SearchFilter, OrderingFilter)
    search_fields = ('^name',)
    ordering_fields = ('id',)
    
    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)

    # @action(methods=['get'], detail=False, permission_classes=[IsAuthenticated], pagination_class=None)
    # def all(self, request): #不分页,只要求登陆权限
    #     queryset = self.queryset
    #     serializer_class = self.serializer_class
    #     serializer = serializer_class(queryset,many=True)
    #     return Response(serializer.data)
    





class OrganizationTreeView(TreeAPIView):
    """
    组织架构树
    """
    queryset = Organization.objects.all()
    permission_classes = (IsAuthenticated,)


class OrganizationUserTreeView(APIView):
    """
    组织架构关联用户树
    """

    def get(self, request, format=None):
        organizations = Organization.objects.all()
        serializer = OrganizationUserTreeSerializer(organizations, many=True)
        tree_dict = {}
        tree_data = []
        for item in serializer.data:
            new_item = {
                'id': 'o' + str(item['id']),
                'label': item['label'],
                'pid': item['pid'],
                'children': item['children']
            }
            tree_dict[item['id']] = new_item
        for i in tree_dict:
            if tree_dict[i]['pid']:
                pid = tree_dict[i]['pid']
                parent = tree_dict[pid]
                parent['children'].append(tree_dict[i])
            else:
                tree_data.append(tree_dict[i])
        return Response(tree_data)
