from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from apps.qm.serializers import StandardCreateUpdateSerializer, StandardSerializer, TestItemCreateUpdateSerializer, TestItemSerializer, TestRecordCreateSerializer, TestRecordDetailSerializer, TestRecordListSerializer
from apps.qm.models import Standard, TestItem, TestRecord, TestRecordItem
from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from apps.system.mixins import CreateUpdateModelAMixin
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework import status
from django.db import transaction
# Create your views here.
class StandardViewSet(CreateUpdateModelAMixin, ModelViewSet):
    """
    标准规范-增删改查
    """
    perms_map = {'*': '*'}
    queryset = Standard.objects.select_related('file').all()
    serializer_class = StandardSerializer
    search_fields = ['name', 'number']
    filterset_fields = []
    ordering_fields = ['number']
    ordering = ['id']

    def get_serializer_class(self):
        if self.action in ['create', 'update']:
            return StandardCreateUpdateSerializer
        return StandardSerializer

class TestItemViewSet(CreateUpdateModelAMixin, ModelViewSet):
    """
    检验项目增删改查
    """
    perms_map = {'*': '*'}
    queryset = TestItem.objects.select_related('standard').all()
    serializer_class = TestItemSerializer
    search_fields = ['name', 'standard__name', 'standard__number']
    filterset_fields = ['standard']
    ordering_fields = ['id']
    ordering = ['id']

    def get_serializer_class(self):
        if self.action in ['create', 'update']:
            return TestItemCreateUpdateSerializer
        return TestItemSerializer

class TestRecordViewSet(ListModelMixin, RetrieveModelMixin, GenericViewSet):
    """
    检测记录
    """
    perms_map = {'*': '*'}
    queryset = TestRecord.objects.select_related('fifo_item', 'form').all()
    serializer_class = TestRecordListSerializer
    filterset_fields = ['wproduct', 'material', 'step', 'subproduction_plan', 'fifo_item', 'origin_test']
    ordering = ['-id']

    def get_serializer_class(self):
        if self.action == 'list':
            return TestRecordListSerializer
        elif self.action == 'retrieve':
            return TestRecordDetailSerializer
        return super().get_serializer_class()

    # def create(self, request, *args, **kwargs):
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     vdata = serializer.validated_data
    #     record_data = vdata.pop('record_data')
    #     if 'is_testok' not in vdata:
    #         raise APIException('未填写检测结论')
    #     with transaction.atomic():
    #         obj = serializer.save(create_by = self.request.user)
    #         tris = []
    #         for m in record_data: # 保存记录详情
    #             form_field = m['form_field']
    #             m['field_name'] = form_field.field_name
    #             m['field_key'] = form_field.field_key
    #             m['field_type'] = form_field.field_type
    #             m['field_value'] = m['field_value']
    #             m['sort'] = form_field.sort
    #             m['need_judge'] = form_field.need_judge
    #             m['is_testok'] = m['is_testok'] if 'is_testok' in m else True
    #             m['test_record'] = obj
    #             tris.append(TestRecordItem(**m))
    #         TestRecordItem.objects.bulk_create(tris)

    #         # 如果检测合格
    #         if obj.fifo_item:
    #             obj.fifo_item.is_testok = True if obj.is_testok else False
    #             obj.fifo_item.is_tested = True
    #             obj.fifo_item.save()

    #     return Response(status=status.HTTP_201_CREATED)