# coding=utf-8

import json

from django.db import transaction
from django.contrib.auth import get_user_model
from rest_framework.views import APIView
from rest_framework.serializers import ValidationError
from rest_framework_jwt.views import ObtainJSONWebToken, RefreshJSONWebToken

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

from apps.employee.serializers import JWTSerializer, EmployeeSerializer
from apps.employee.filters import EmployeeFilter
from apps.employee.models import Employee
from apps.log.models import BizLog

User = get_user_model()


class LoginView(ObtainJSONWebToken):
    serializer_class = JWTSerializer

    def post(self, request, *args, **kwargs):
        '''
        职工登录
        :param:
        :return:
        '''
        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):
                data = {
                    'token': ser.validated_data['token'],
                    'user_id': ser.validated_data['user'].id,
                    'username': ser.validated_data['user'].username
                }
                return response_ok(data)
        except ValidationError as e:
            return response_ok({'error': True})
        except CustomError as e:
            return response_error(str(e))


class ChangePasswrodView(APIView):
    permission_classes = [IsEmployee, ]

    def post(self, request):
        '''
        职工修改密码
        :param request:
        :return:
        '''
        data = json.loads(request.body)
        with transaction.atomic():
            request.user.change_password(data['new_password'], data['confirm_password'], data['old_password'])
            request.user.save()
            BizLog.objects.addnew(request.user, BizLog.INSERT, u'[%s]修改密码,IP[%s]' % (request.user.username, get_remote_addr(self.request)))
        return response_ok()


class EmployeeViewSet(CustomModelViewSet):
    permission_classes = [IsEmployee, ]
    queryset = Employee.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
        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)
