from django.shortcuts import render
import rest_framework
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
# Create your views here.

class ContactRecordViewSet(CreateUpdateCustomMixin, PageOrNot, ModelViewSet):
    """
    联系记录
    """
    perms_map = {'get': 'contactrecord_view', 'post':'contactrecord_create', 'put':'contactrecord_update','delete': 'contactrecord_delete'}
    queryset = ContactRecord.objects.all()
    serializer_class = ContactRecordSerializer
    ordering = ['-pk']
    filterset_fields = ['project', 'certapp']

class PlanViewSet(RbacFilterSet, PageOrNot, ModelViewSet):
    """
    计划
    """
    perms_map = {'get': 'plan_view', 'post':'plan_create', 'put':'plan_update','delete': 'plan_delete'}
    queryset = Plan.objects.all()
    serializer_class = PlanSerializer
    ordering = ['-pk']
    # filterset_fields = ['project', 'certapp']

class MemberViewSet(CreateUpdateCustomMixin, PageOrNot, ModelViewSet):
    """
    审核组成员
    """
    perms_map = {'get': '*', 'post':'member_create', 'put':'member_update','delete': 'member_delete'}
    queryset = Member.objects.all()
    serializer_class = MemberSerializer
    ordering = ['-is_leader', 'pk']
    filterset_fields = ['certapp']

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if Member.objects.filter(user = request.data['user'], certapp=request.data['certapp'], is_deleted=False).exists():
            return Response('已存在该成员', status= status.HTTP_400_BAD_REQUEST)
        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':'audit_days'},
            url_name='audit_days')
    def days(self, request, *args, **kwargs):
        """
        反馈审核员的人日数等
        """
        obj = self.get_object()
        obj.man_days = request.data['man_days']
        obj.days = request.data['days']
        obj.save()
        return Response(status=status.HTTP_200_OK)