# coding=utf-8

from django.db import transaction
from django.contrib.auth import get_user_model

from rest_framework.decorators import action
from rest_framework.serializers import ValidationError

from rest_framework_jwt.views import ObtainJSONWebToken, RefreshJSONWebToken, VerifyJSONWebToken

from utils.permission import IsAdministratorUser
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from utils import response_error, response_ok

from apps.log.models import BizLog
from apps.account.serializers import JWTSerializer, UserSerializer
from apps.account.filters import UserFilter

User = get_user_model()


class LoginView(ObtainJSONWebToken):
    serializer_class = JWTSerializer

    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            ser.request = request
            if ser.is_valid(raise_exception=True):
                return response_ok(ser.validated_data)
        except ValidationError as e:
            return response_error(e.detail['error'][0])
        except CustomError as e:
            return response_error(str(e))


class RefreshTokenView(RefreshJSONWebToken):

    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                return response_ok({'token': ser.validated_data['token']})
        except ValidationError as e:
            return response_ok({'error':True})
        except CustomError as e:
            return response_error(str(e))


class VerifyTokenView(VerifyJSONWebToken):
    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                return response_ok({'token': ser.validated_data['token']})
        except ValidationError as e:
            return response_error(u'登录状态失效，请重新登录[' + e.detail['error'][0] + ']')


class EmployeeViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser, ]
    queryset = User.objects.filter(is_active=True, type=User.ADMINSTRATOR)
    serializer_class = UserSerializer

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

    def perform_create(self, serializer):
        super(EmployeeViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'添加用户[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def perform_update(self, serializer):
        super(EmployeeViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE, u'修改用户[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @action(methods=['post'], detail=False)
    def change_password(self, request):
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        old_password = request.POST.get('old_password')
        
        with transaction.atomic():
            request.user.change_password(new_password, confirm_password, old_password)
            request.user.save()
            BizLog.objects.addnew(request.user, BizLog.UPDATE, u"修改密码[%s],id=%d" % (request.user.username, request.user.id))
        return response_ok()
