from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import Standard, UnitType, ImplementRule
from .serializers import StandardSerializer, ImplementRuleSerializer, UnitTypeSerializer, ImplementRuleListSerializer
from apps.system.permission_data import RbacFilterSet
from apps.system.mixins import CreateUpdateCustomMixin, OptimizationMixin
# Create your views here.

class StandardViewSet(CreateUpdateCustomMixin, ModelViewSet):
    perms_map = {'get': '*', 'post': 'standard_create',
                 'put': 'standard_update', 'delete': 'standard_delete'}
    queryset = Standard.objects.all()
    serializer_class = StandardSerializer
    search_fields = ['name', 'code', 'status', 'implement_date']
    filterset_fields = ['status']
    ordering = ['-create_time']

class ImplementRuleViewSet(CreateUpdateCustomMixin, OptimizationMixin, ModelViewSet):
    perms_map = {'get': '*', 'post': 'implementrule_create',
                 'put': 'implementrule_update', 'delete': 'implementrule_delete'}
    queryset = ImplementRule.objects.all()
    serializer_class = ImplementRuleSerializer
    search_fields = ['name', 'code', 'cert_field']
    filterset_fields = ['pv_scope', 'cert_field', 'cert_field__code']
    ordering = ['-create_time']

    def get_serializer_class(self):
        # 根据请求类型动态变更serializer
        if self.action == 'list':
            return ImplementRuleListSerializer
        return ImplementRuleSerializer

class UnitTypedViewSet(CreateUpdateCustomMixin, OptimizationMixin, ModelViewSet):
    perms_map = {'get': '*', 'post': 'unittype_create',
                 'put': 'unittype_update', 'delete': 'unittype_delete'}
    queryset = UnitType.objects.all()
    serializer_class = UnitTypeSerializer
    search_fields = ['name']
    filterset_fields = ['name','implementrule']
    ordering = ['-create_time']

    def paginate_queryset(self, queryset):
        """
        如果查询参数里没有page且含有参数implementrule则不分页,否则请求分页
        """
        if ((not self.request.query_params.get('page', None)) and (self.request.query_params.get('implementrule', None))) or (self.paginator is None):
            return None
        return self.paginator.paginate_queryset(queryset, self.request, view=self)