# coding=utf-8
from django.db import transaction
from rest_framework_jwt.views import ObtainJSONWebToken,VerifyJSONWebToken,RefreshJSONWebToken
from rest_framework.serializers import ValidationError
from utils.custom_modelviewset import CustomModelViewSet
from utils import response_error, response_ok
from .serializers import *
from .models import User
from apps.account import tenant_log
from apps.foundation.models import BizLog
from django.contrib.auth.decorators import login_required
from .filters import *

class LoginView(ObtainJSONWebToken):
    serializer_class = TenantJWTSerializer

    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])


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 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_error(u'登录状态失效，请重新登录[' + e.detail['error'][0] + ']')

class EmployeeViewSet(CustomModelViewSet):
    queryset = User.objects.filter()
    serializer_class = EmployeeSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        f = EmployeeFilter(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
        tenant_log(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
        tenant_log(self.request.user, BizLog.UPDATE, u'修改用户[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.status = User.DIMISSION
            instance.save()
            tenant_log(self.request.user, BizLog.DELETE, u'禁用用户[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()