from django.contrib import auth
from rest_framework.views import APIView
from rest_framework.authtoken.models import Token
from rest_framework.authentication import BasicAuthentication, TokenAuthentication
from .serializers import UserRegisterSerializer

from django.middleware.csrf import get_token
from django.contrib.auth import login
from api.models import User
from django.contrib.auth.hashers import make_password , check_password

from api.utils import *

class UserRegisterAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request):
        csrf_token = get_token(request)
        response = Response({'csrftoken': csrf_token})
        # response["Access-Control-Allow-Origin"] = "*"
        return response

    def post(self, request):
        serializer = UserRegisterSerializer(data=request.data)
        if serializer.is_valid():
            newuser = serializer.save()
            token = Token.objects.create(user=newuser)
            # 注册完，同时将用户登录
            auth.login(request, newuser)
            return success(message="用户注册成功", data={
                "username": newuser.username,
                "displayname": newuser.displayname,
                "token": token.key,
                'identity': newuser.identity,
            },code=201)
        
        # 处理错误信息
        errors = {}
        for field, field_errors in serializer.errors.items():
            if isinstance(field_errors, list):
                errors[field] = field_errors[0]
                print(field_errors)
                if field_errors[0].code == 'unique':
                    errors[field] = str("用户名已存在")
            else:
                errors[field] = str(field_errors)
        
        return failed(message="注册失败", data=errors, code=400)

class UserLoginAPI(APIView):
    authentication_classes = []
    permission_classes = []
    
    def get(self, request):
        csrf_token = get_token(request)
        response = Response({'csrftoken': csrf_token})
        # response["Access-Control-Allow-Origin"] = "*"
        return response
    
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = auth.authenticate(request, username=username, password=password)
        if user:
            auth.login(request, user)
            if Token.objects.filter(user=user).exists():
                token = Token.objects.get(user=user).key
            else:
                token = Token.objects.create(user=user).key
            return success(message="登录成功", data={
                'username': user.username,
                'displayName': user.displayname,
                'token': token,
                'identity': user.identity,
            }, code=201)
        else:
            return failed(message="登录失败", data="用户名不存在，或密码错误", code=401)

class getDashboard(APIView):
    
    def post(self, request):
        return Response({
            'data': 'yes'
        })


#查询用户信息
class UserSelectAPI(APIView):
    def get(self, request):
        user = request.user
        return success(message="查询用户信息成功", data = {
                'username': user.username,
                'displayname': user.displayname,
                'createtime': user.create_time,
                'identity': user.identity,
                'lastlogin': user.last_login
            }, code=200)
    
#修改用户信息
class UserUpdateAPI(APIView):
    def post(self, request):
        try:
            user = request.user
            user.username = request.data.get('username')
            user.displayname = request.data.get('displayname')
            user.identity = request.data.get('identity')
            user.save()
            return success(message="修改用户信息成功", data = {
                'username': user.username,
                'displayname': user.displayname,
                'createtime': user.create_time,
                'identity': user.identity,
                'lastlogin': user.last_login
            }, code=200)
        except Exception as e:
            return failed(message="修改用户信息失败", code=400)
    
#修改用户密码
class PassUpdateAPI(APIView):
    def post(self, request):
        try:
            user = request.user
            password = make_password(
                request.data.get("oldPassword"),
                salt='vrviewer',
                hasher='pbkdf2_sha256'
            )
            if(check_password(request.data.get("oldPassword") , user.password)):
                user.password = make_password(
                request.data.get("newPassword"),
                salt='vrviewer',
                hasher='pbkdf2_sha256'
                )
                user.save()
                return success(message="用户密码修改成功", code=200)
            else:
                return failed(message="用户密码修改失败,原密码错误", code=400)
        except Exception as e:
            return failed(message="用户密码修改失败", code=400)
