# coding=utf8

import json
from django.urls import reverse
from django.http import HttpResponse
from django.http.response import HttpResponseRedirect
from apps.manage.views import login, first_login


class ManageMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        user = request.user
        if user.is_superuser:
            return self.get_response(request)
        manager = getattr(user, 'manager', None)
        if request.path.startswith("/manage/first_login"):
            if user.is_authenticated and user.is_staff and manager:
                if manager.is_reset_password:
                    index_url = reverse("manage_home")
                    return HttpResponseRedirect(index_url)
        elif request.path != '/manage/login/' and request.path.startswith("/manage"):
            if user.is_authenticated and user.is_staff and manager:
                if not manager.is_reset_password:
                    return first_login(request, pre_url=request.path)
            else:
                if request.is_ajax():
                    return HttpResponse(json.dumps({'errcode': -1, 'errmsg': u'身份认证失效,请重新登录'}))
                return login(request, pre_url=request.path)
        return self.get_response(request)
