# coding=utf-8

from django.db import transaction
from django.contrib.auth import get_user_model
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.serializers import UserSerializer
from apps.staff.filters import UserFilter
from apps.system.models import SysLog
User = get_user_model()

class UserViewSet(CustomModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = User.objects.filter()
    serializer_class = UserSerializer

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

    def perform_create(self, serializer):
        super(UserViewSet, 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.username, instance.id), validated_data)

    def perform_update(self, serializer):
        super(UserViewSet, 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.username, instance.id), validated_data)
