#!/usr/bin/env Python
# coding=utf-8

from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth import authenticate, login, logout
from .forms import User_Login_Form, User_Register_Form, Forget_Password_Form, Modify_Password_Form, \
    Editor_UserForm, Editor_UserProfileForm
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib.auth.hashers import make_password
from .models import EmailVerifyRecord, UserProfile
from utils.email_send import send_register_email
from django.contrib.auth.decorators import login_required


def login_view(request):
    if request.method != 'POST':
        form = User_Login_Form()
    else:
        form = User_Login_Form(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                # return redirect('user:login')  # 跳转至登录界面
                return redirect('user:center')  # 跳转至个人中心
            else:
                return HttpResponse('账号或密码错误!!!')
        else:
            pass
    return render(request, 'user/login.html', {'form': form})


def register_view(request):
    if request.method != 'POST':
        form = User_Register_Form()
    else:
        form = User_Register_Form(request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.set_password(form.cleaned_data.get('password'))
            new_user.username = form.cleaned_data.get('email')
            new_user.save()
            send_register_email(form.cleaned_data.get('email'), 'register')  # 邮件发送
            return redirect('user:login')
        else:
            pass
    return render(request, 'user/register.html', {'form': form})


class OwnBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


# 修改用户状态, 比对链接验证码
def active_user(request, active_code):
    all_records = EmailVerifyRecord.objects.filter(code=active_code)
    if all_records:
        for record in all_records:
            email = record.email
            user = User.objects.get(email=email)
            user.is_staff = True
            user.save()
    else:
        return HttpResponse('错误链接')
    return redirect('user:login')


def forget_pwd(request):
    if request.method != "POST":
        form = Forget_Password_Form()
    else:
        form = Forget_Password_Form(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            exists = User.objects.filter(email=email).exists()
            if exists:
                # 发送邮件
                send_register_email(email, 'forget')
                return HttpResponse('邮件已经发送到你的邮箱里,请注意查收...')
            else:
                return HttpResponse('该邮箱未注册...')
        else:
            pass

    return render(request, 'user/forget_pwd.html', {'form': form})


def forget_pwd_url(request, active_code):
    if request.method != 'POST':
        form = Modify_Password_Form()
    else:
        form = Modify_Password_Form(request.POST)
        if form.is_valid():
            record = EmailVerifyRecord.objects.get(code=active_code)
            email = record.email
            user = User.objects.get(email=email)
            user.username = email
            user.password = make_password(form.cleaned_data.get('password'))
            user.save()
            return HttpResponse('修改成功...')
        else:
            return HttpResponse('修改失败...')

    return render(request, 'user/reset_pwd.html', {'form': form})

# 用户个人中心
@login_required(login_url='user:login')
def user_profile(request):
    user = User.objects.get(username=request.user)
    return render(request, 'user/user_profile.html', {'user': user})


def logout_operation(request):
    logout(request)
    return redirect('user:login')

# 修改用户信息
@login_required(login_url='user:login')
def editor(request):
    user = User.objects.get(id=request.user.id)
    if request.method == "POST":
        try:
            user_profile = user.userprofile
            form = Editor_UserForm(request.POST, instance=user)
            user_profile_form = Editor_UserProfileForm(request.POST, request.FILES, instance=user_profile)
            if form.is_valid() and user_profile_form.is_valid():
                form.save()
                user_profile_form.save()
                return redirect('user:center')
            # else:
            #     return redirect('user:center')
        except UserProfile.DoesNotExist as e:
            form = Editor_UserForm(request.POST, instance=user)
            user_profile_form = Editor_UserProfileForm(request.POST, request.FILES)
            if form.is_valid() and user_profile_form.is_valid():
                form.save()
                # user_profile_form.save()
                new_user_profile = user_profile_form.save(commit=False)
                new_user_profile.owner = request.user
                new_user_profile.save()
                return redirect('user:center')
    else:
        try:
            user_profile = user.userprofile
            form = Editor_UserForm(instance=user)
            user_profile_form = Editor_UserProfileForm(instance=user_profile)
        except UserProfile.DoesNotExist as e:
            form = Editor_UserForm(instance=user)
            user_profile_form = Editor_UserProfileForm()

    return render(request, 'user/editor_user.html', locals())
