# coding=utf-8

from django.db import transaction, IntegrityError
from django.db.models import F, ProtectedError
from rest_framework.views import APIView
from utils.permission import IsAdministrator
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from apps.staff.models import Department
from apps.staff.serializers import DepartmentSerializer
from apps.staff.filters import DepartmentFilter
from apps.system.models import SysLog


class DepartmentViewSet(CustomModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = Department.objects.filter()
    serializer_class = DepartmentSerializer

    def filter_queryset(self, queryset):
        f = DepartmentFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(DepartmentViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        SysLog.objects.addnew(self.request.user, SysLog.INSERT, u'添加部门[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                count = Department.objects.filter(parent_id=instance.id).count()
                if count:
                    raise CustomError(u'该部门存在子部门，不允许删除！')
                SysLog.objects.addnew(self.request.user, SysLog.DELETE, u'删除部门[%s]，id=%d' % (instance.name, instance.id))
                lft = instance.lft
                rgt = instance.rgt

                total = rgt - lft + 1
                instance.delete()
                Department.objects.filter(rgt__gt=lft).update(rgt=F('rgt') - total)
                Department.objects.filter(lft__gt=lft).update(rgt=F('lft') - total)

        except ProtectedError:
            return response_error(u'该部门已被引用，禁止删除！')
        except IntegrityError:
            return response_error(u'该部门已被引用，禁止删除！')
        return response_ok()

    def perform_update(self, serializer):
        super(DepartmentViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'修改部门[%s]，id=%d' % (instance.name, instance.id), validated_data)


def child_department_tree(parent_id,children):
    rows = Department.objects.filter(parent_id=parent_id)
    for row in rows:
        item = {
            'id': row.id,
            'value': row.id,
            'name': row.name,
            'notes': row.notes,
            'parent_id': row.parent_id,
            'children': []
        }
        child_department_tree(row.id, item['children'])
        children.append(item)


class DepartmentTreeView(APIView):
    permission_classes = [IsAdministrator, ]

    def get(self, request):
        result = []
        child_department_tree(None, result)
        return response_ok(result)
