# coding=utf-8
import json
from django.db import transaction
from django.contrib.auth import get_user_model
from rest_framework_jwt.views import ObtainJSONWebToken, VerifyJSONWebToken, RefreshJSONWebToken
from rest_framework.serializers import ValidationError
from utils import response_error, response_ok
from rest_framework.views import APIView
from utils.permission import IsStaff
from apps.system.models import SysLog
from apps.staff.serializers import StaffUserJWTSerializer

User = get_user_model()

class StaffUserLoginView(ObtainJSONWebToken):
    serializer_class = StaffUserJWTSerializer

    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 StaffUserVerifyTokenView(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 StaffUserRefreshTokenView(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 ChangePasswordView(APIView):
    permission_classes = [IsStaff, ]

    def post(self, request):
        data = request.data

        new_password = data['new_password'].strip(' ')
        confirm_password = data['confirm_password'].strip(u' ')
        old_password = data['old_password'].strip(u' ')

        with transaction.atomic():
            request.user.change_password(new_password, confirm_password, old_password)
            request.user.save()
            SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'修改账户密码')
        return response_ok()
