# coding=utf8
from datetime import datetime, timedelta
from django.db import connection
from django.db.models import Sum, Count
from django.db.models.query_utils import Q
from django.db.models.functions import TruncDate
from django.shortcuts import render_to_response
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from django.http.response import HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login as login_, logout as logout_
from django.contrib.auth import login, logout
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
from rest_framework.decorators import action
from core.framework.manageviews import TemplateHTMLRendererView, ManageResponseView
from core.framework.response import MangeAPIResponse
from core.framework.permissions import IsAuthManager, IsManager
from core.framework.exceptions import ManageAPIException
from apps.manage.rules import Rules


@csrf_exempt
def login(request, pre_url=None, template_name='manage/login.html'):
    message = ''
    next_url = request.GET.get('next') or request.POST.get('next')
    if not next_url:
        next_url = pre_url
    if next_url is None:
        next_url = reverse('manage_home')

    if request.method != 'POST':
        return render_to_response(template_name, {'next_url': next_url })

    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)

        if user is not None and user.is_authenticated:
            if not user.is_staff:
                message = u'该账号未授权登陆！'
            else:
                if not user.is_active:
                    message = u'该账号已冻结！'
                else:
                    login_(request, user)
                    return HttpResponseRedirect(next_url)
        else:
            message = u'账号不存在或者密码错误！'
    return render_to_response(template_name, {'next_url': next_url,
                                              'message': message})


@csrf_exempt
def first_login(request, pre_url=None, template_name='manage/first_login.html'):
    old_password = request.POST.get('old_password')
    new_password_1 = request.POST.get('new_password1')
    new_password_2 = request.POST.get('new_password2')

    user = request.user
    if not user:
        return login(request, pre_url)

    next_url = request.GET.get('next') or request.POST.get('next')
    if not next_url:
        next_url = pre_url
    if next_url is None:
        next_url = reverse('manage_home')

    if old_password:
        if user.check_password(old_password):
            if new_password_1 != new_password_2:
                message = u'两次输入的密码不正确'
            else:
                user.set_password(new_password_1)
                user.save(update_fields=['password', ])
                user.manager.is_reset_password = True
                user.manager.save(update_fields=['is_reset_password', ])
                auth_user = authenticate(username=user.username, password=new_password_1)
                if auth_user is not None and auth_user.is_authenticated and auth_user.is_staff and auth_user.is_active:
                    login_(request, auth_user)
                return HttpResponseRedirect(next_url)
        else:
            message = u'旧密码不正确'
    else:
        message = ''

    return render_to_response(template_name, {'next_url': next_url, 'message': message})


class ManageLoginView(TemplateHTMLRendererView):
    template_name = 'manage/login.html'

    @csrf_exempt
    def post(self, request):
        return login(request)


class ManageLogOutView(TemplateHTMLRendererView):
    template_name = 'manage/login.html'

    def get(self, request):
        logout(request)
        return Response()


class ManageHomeView(TemplateHTMLRendererView):
    template_name = 'manage/home.html'

    def get(self, request):
        return Response()


class ManageDashboardView(TemplateHTMLRendererView):
    template_name = 'manage/apps/dashboard/index.html'

    def get(self, request):
        return Response()


class ManageResetPasswordView(TemplateHTMLRendererView):
    template_name = 'manage/reset_password.html'
    permission_classes = [IsManager]

    def get(self, request):
        return Response()


class ManageResetPasswordAPIView(ManageResponseView):
    permission_classes = [IsAuthManager]

    def post(self, request):
        user = request.user
        old_password = request.POST.get('old_password')
        if not user.check_password(old_password):
            raise ManageAPIException(errmsg='旧密码不正确')
        new_password = request.POST.get('new_password')
        new_password2 = request.POST.get('new_password2')
        if not new_password or not new_password2:
            raise ManageAPIException(errmsg='密码不能为空')
        if new_password != new_password2:
            raise ManageAPIException(errmsg='两次密码不正确')
        user.set_password(new_password)
        user.save(update_fields=['password'])
        return MangeAPIResponse()


class ManageRules(ManageResponseView):
    permission_classes = [IsManager]

    def get(self, request):
        user = request.user
        if user.is_superuser:
            rules = Rules
        else:
            manager = user.manager
            rules = manager.get_menus()
        return MangeAPIResponse(data=rules)
