from rest_framework.views import APIView
from apps import project
from django.shortcuts import render
from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.response import Response
from rest_framework import status
from .models import *
from .serializers import *
from apps.system.models import Dict
from apps.system.permission_data import RbacFilterSet
from apps.system.mixins import CreateUpdateCustomMixin, OptimizationMixin
import random
from rest_framework.decorators import action
from .filters import *
from utils.pagination import PageOrNot
from rest_framework.exceptions import ParseError, NotAuthenticated
from django.utils import timezone
# Create your views here.
class ApplicationViewSet(RbacFilterSet, ModelViewSet):
    """
    认证申请
    """
    perms_map = {'get': 'application_view', 'post':'application_create', 'put':'application_update','delete': 'application_delete'}
    queryset = Application.objects.all()
    serializer_class = ApplicationCreateSerializer
    ordering = ['-create_time']

    def get_serializer_class(self):
        if self.action == 'create':
            return ApplicationCreateSerializer
        else:
            return ApplicationUpdateSerializer
    
    def perform_create(self, serializer):
        serializer.save(create_by = self.request.user, belong_dept=self.request.user.dept, number=random.randrange(1000,2000))

class SubApplicationViewSet(RbacFilterSet, ModelViewSet):
    """
    子认证申请
    """
    perms_map = {'get': 'application_view', 'post':'application_create', 'put':'application_update','delete': 'application_delete'}
    queryset = SubApplication.objects.all()
    serializer_class = SubApplicationCreateSerializer
    filterset_fields = ['application']
    ordering = ['-create_time']

    def get_serializer_class(self):
        if self.action == 'create':
            return SubApplicationCreateSerializer
        else:
            return SubApplicationUpdateSerializer
    
    def create(self, request, *args, **kwargs):
        postdata = request.data
        postdata['number'] = random.randrange(1000,2000)
        serializer = self.get_serializer(data=postdata)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    
    def paginate_queryset(self, queryset):
       
        if ((not self.request.query_params.get('page', None)) and (self.request.query_params.get('application', None))) or (self.paginator is None):
            return None
        return self.paginator.paginate_queryset(queryset, self.request, view=self)

class CertappViewset(PageOrNot, RbacFilterSet, ModelViewSet):
    """
    申请受理
    """
    perms_map = {'get': 'certapp_view', 'post':'certapp_create', 'put':'certapp_update','delete': 'certapp_delete'}
    queryset = CertApp.objects.all()
    serializer_class = CertappSerializer
    ordering = ['-create_time']
    filterset_fields = ['status', 'project']
    # filterset_class = CertAppFilter


    def create(self, request, *args, **kwargs):
        postdata = request.data
        postdata['number'] = random.randrange(1000,2000)
        if postdata.get('field_code', None):
            postdata['cert_field'] = Dict.objects.get(code=postdata['field_code']).id
        serializer = self.get_serializer(data=postdata)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    
    @action(methods=['put'], detail=True, perms_map={'put':'complete_certapp'},
            url_name='complete_certapp')
    def complete(self, request, pk=None):
        """
        完成受理
        """
        obj = self.get_object()
        obj.status = '已受理'
        obj.save()
        return Response(status=status.HTTP_200_OK)

    @action(methods=['put'], detail=False, perms_map={'put':'review_certapp'},
            url_name='review_certapp')
    def review(self, request, pk=None):
        """
        完成评审
        """
        certapps = request.data['certapps']
        rlist = request.data['rlist']
        for i in rlist:
            instance = EvaluationDetail.objects.create(item=Evaluations.objects.get(id=i['id']), create_by=request.user, result=i['result'] if 'result' in i and i['result'] else None)
            instance.cert_app.add(*certapps)
        return Response(status=status.HTTP_200_OK)

class EvaluationDetailViewset(CreateUpdateCustomMixin, PageOrNot,ModelViewSet):
    """
    受理信息
    """
    perms_map = {'get': '*', 'post': 'EvaluationDetail_create',
                 'put': 'EvaluationDetail_update', 'delete': 'EvaluationDetail_delete'}
    queryset = EvaluationDetail.objects
    serializer_class = EvaluationDetailSerializer
    filterset_fields = ['cert_app']
    ordering = ['-create_time']
    


    

class UnitViewSet(RbacFilterSet, ModelViewSet):
    """
    产品单元
    """
    perms_map = {'get': 'certapp_view', 'post':'certapp_create', 'put':'certapp_update','delete': 'certapp_delete'}
    queryset = Unit.objects.all()
    serializer_class = UnitSerializer
    ordering = ['pk']
    filterset_fields = ['certapp']



class ProjectViewSet(RbacFilterSet, ModelViewSet):
    perms_map = {'get': 'project_view', 'post':'project_create', 'put':'project_update','delete': 'project_delete'}
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    ordering = ['pk']
    filterset_class = ProjectFilter
    search_fields = ['auditee__name', 'plan__name']
    
    def get_serializer_class(self):
        if self.action == 'update':
            return ProjectUpdateSerializer
        return ProjectSerializer

    def create(self, request, *args, **kwargs):
        postdata = request.data
        postdata['number'] = random.randrange(8000,9000)
        serializer = self.get_serializer(data=postdata)
        serializer.is_valid(raise_exception=True)
        if self.request.user is not None:
            instance = serializer.save(create_by = self.request.user, belong_dept=self.request.user.dept)
            if 'certapps' in postdata and postdata['certapps']:
                CertApp.objects.filter(pk__in = postdata['certapps']).update(project=instance, status='进行中')
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        else:
            return NotAuthenticated()
    
    @action(methods=['put'], detail=True, perms_map={'put':'project_next'},
            url_name='project_next')
    def next(self, request, pk=None):
        """
        项目流转
        """
        obj = self.get_object()
        if obj.status == '创建中':
            obj.status = '待策划'
            obj.save()
            return Response(status=status.HTTP_200_OK)
        elif obj.status == '策划中' and obj.can_paichai:
            obj.status = '待现场审核'
            obj.save()
            return Response(status=status.HTTP_200_OK)
        else:
            return Response('项目状态异常,操作失败', status=status.HTTP_400_BAD_REQUEST)


    @action(methods=['put'], detail=False, perms_map={'put':'project_plan'},
            url_name='project_plan')
    def plan(self, request, *args, **kwargs):
        """
        项目计划
        """
        projects = request.data['projects']
        plan = request.data['plan']
        if projects:
            objs = Project.objects.filter(pk__in=projects)
            for i in objs:
                i.plan=plan
                if i.status == '待策划':
                    i.status == '策划中'
                i.save()
        return Response(status=status.HTTP_200_OK)
    
    @action(methods=['put'], detail=True, perms_map={'put':'project_edate'},
            url_name='project_edate')
    def edate(self, request, *args, **kwargs):
        """
        制定预期审核时间
        """
        obj = self.get_object()
        obj.edate0 = request.data['edate0']
        obj.edate1 = request.data['edate1']
        obj.save()
        return Response(status=status.HTTP_200_OK)
