from rbac.permission import RbacPermission
from rbac.models import UserProfile
from crm.models import Consumer
from rest_framework.permissions import IsAuthenticated
from django.core.cache import cache
from django.utils import timezone
from datetime import datetime, timedelta
# 学员接口列表
ConsumerPerms = [
    'paper_view',
    'gen_monitest',
    'questioncat_view',
    'my_collects',
    'my_subjects',
    'my_examtest',
    'exercise',
    'down_material'
]

VistorPerms = [
    'gen_monitest',
    'questioncat_view',
    'my_examtest',
]
from .spider import getZs
def get_consumerperm_list(consumer):
    perms = list(consumer.role.perms.values_list('code', flat=True))
    if consumer.workscope: 
        if consumer.workscope.can_exam: # 如果是三类考试工作类别不做过期检测
            pass
        elif consumer.exceed_date and (consumer.exceed_date < datetime.date(timezone.now())):
            if consumer.name and consumer.ID_number1:
                candidates = getZs(consumer.name, consumer.ID_number1)
                if candidates:
                    perms.append('account_exceed')
                else:
                    # 未通过考试增加30天期限
                    newdate = datetime.date(timezone.now() + timedelta(days=30))
                    consumer.exceed_date = newdate
                    consumer.save()
            else:
                perms.append('account_exceed')
    cache.set('cperms_'+str(consumer.id), perms, 60*60)
    return perms

class MyPermission(RbacPermission):

    def has_permission(self, request, view):
        """
        权限校验逻辑
        :param request:
        :param view:
        :return:
        """
        perms = []
        # if 'perms' in request.session:
        #     perms = request.session['perms']
        if isinstance(request.user, UserProfile): # 如果是管理员表
            # perms = get_permission_list(request.user)
            return True
        elif isinstance(request.user, Consumer): # 如果是客户
            perms = cache.get('cperms_'+str(request.user.id), None)
            if not perms:
                perms = get_consumerperm_list(request.user)
        if perms:
            if 'account_exceed' in perms: # 账户过期
                if request.user.exceed_date and (request.user.exceed_date >= datetime.date(timezone.now())):
                    pass
                else:
                    perms = ['questioncat_view','my_examtest','down_material']
            if not hasattr(view, 'perms_map'):
                return True
            else:
                perms_map = view.perms_map
                _method = request._request.method.lower()
                for i in perms_map:
                    for method, alias in i.items():
                        if ((_method == method or method == '*') and alias in perms) or alias == '*':
                            return True
        return False