# coding=utf-8

from django.db import transaction, IntegrityError
from django.db.models import F,ProtectedError
from rest_framework.views import APIView
from collections import OrderedDict
from utils import response_ok
from utils.permission import IsTenantUser, permission_required
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from apps.log.models import BizLog
from apps.tenant import tenant_log
from django.contrib.auth.models import Group, Permission
from apps.account.filters import GroupFilter
from .serializers import GroupSerializer, GroupDictSerializer
from .consts import PermissionMenu


class GroupsViewSet(CustomModelViewSet):
    permission_classes = [IsTenantUser, ]
    queryset = Group.objects.filter()
    serializer_class = GroupSerializer

    @permission_required('account.browse_group')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(tenant=self.request.user.employee.tenant)
        f = GroupFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('account.add_group')
    def perform_create(self, serializer):
        super(GroupsViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.INSERT, u'添加权限组[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.add_group')
    def perform_update(self, serializer):
        super(GroupsViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.UPDATE, u'修改权限组[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.delete_group')
    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            if instance.tenant != request.user.employee.tenant:
                raise CustomError(u'禁止跨租户操作！')

            # user_count = instance.user_set.all().count()
            # if user_count:
            #     raise CustomError(u'该权限组已分配给用户，禁止删除！')

            tenant_log(self.request.user.employee, BizLog.DELETE, u'删除权限组[%s]，id=%d' % (instance.name, instance.id))
            instance.delete()
        return response_ok()


class PermissionsListView(APIView):
    permission_classes = [IsTenantUser, ]

    def get(self, request):
        rows = Permission.objects.all().exclude(name__startswith='Can')
        perms_menus = PermissionMenu()
        rows = perms_menus.sort_perms(rows)
        menus = OrderedDict()
        for row in rows:
            item = {'id': row.id, 'name': row.name}
            mn = perms_menus.get_menuname_of_contenttype(row.content_type.app_label, row.content_type.model)
            if mn in menus:
                permissions = menus[mn]
            else:
                permissions = menus[mn] = OrderedDict()

            if row.content_type.name in permissions:
                if not item in permissions[row.content_type.name]:
                    permissions[row.content_type.name].append(item)
            else:
                permissions[row.content_type.name] = [item, ]
        return response_ok(menus)


class PermissionDictView(APIView):
    permission_classes = [IsTenantUser, ]
    def get(self, request):
        rows = Group.objects.filter(tenant=request.user.employee.tenant)
        serializer = GroupDictSerializer(rows, many=True)
        return response_ok(serializer.data)
