from django.shortcuts import render
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin
from rest_framework.decorators import action
from apps.qm.models import QuaStat, TestItem, Ftest, Ptest, FtestWork
from apps.qm.serializers import QuaStatSerializer, TestItemSerializer, QuaStatUpdateSerializer, FtestSerializer, PtestSerializer, \
    FtestWorkCreateUpdateSerializer, FtestWorkSerializer
from apps.qm.tasks import cal_quastat_sflog
from rest_framework.response import Response
from apps.utils.mixins import BulkCreateModelMixin, BulkUpdateModelMixin
import datetime

from apps.utils.viewsets import CustomGenericViewSet, CustomModelViewSet
from apps.wpm.models import SfLog
from apps.qm.filters import QuaStatFilter, TestItemFilter
# Create your views here.


class TestItemViewSet(ListModelMixin, CustomGenericViewSet):
    """
    list:质检项目

    质检项目
    """
    perms_map = {'get': '*'}
    queryset = TestItem.objects.all()
    serializer_class = TestItemSerializer
    filterset_class = TestItemFilter
    ordering = ['id']


class QuaStatViewSet(ListModelMixin, BulkUpdateModelMixin, CustomGenericViewSet):
    """
    list:质量数据统计

    质量数据统计
    """
    perms_map = {'get': '*', 'put': 'quastat.update'}
    queryset = QuaStat.objects.all()
    serializer_class = QuaStatSerializer
    update_serializer_class = QuaStatUpdateSerializer
    filterset_class = QuaStatFilter
    select_related_fields = ['belong_dept', 'material', 'testitem']
    ordering = ['belong_dept__sort', 'material__sort', 'testitem__sort']

    def after_bulk_update(self, objs):
        now = datetime.datetime.now()
        sflogIds = []
        for i in objs:
            sflogIds.append(i['sflog'])
        sflogIds = list(set(sflogIds))
        SfLog.objects.filter(id__in=sflogIds).update(
            last_test_time=now)  # 更新质检记录时间
        for sflogId in sflogIds:
            cal_quastat_sflog.delay(sflogId)


class FtestViewSet(CustomModelViewSet):
    """
    list:首件/成品检验

    首件/成品检验
    """
    queryset = Ftest.objects.all()
    serializer_class = FtestSerializer
    select_related_fields = ['test_user', 'check_user', 'ftest_work']
    filterset_fields = ['type', 'ftest_work']


class PtestViewSet(CustomModelViewSet):
    """
    list:性能测试

    性能测试
    """
    queryset = Ptest.objects.all()
    serializer_class = PtestSerializer
    select_related_fields = ['testitem']
    filterset_fields = ['testitem', 'test_date']


class FtestWorkViewSet(CustomModelViewSet):
    """
    list: 检验工作

    检验工作
    """
    queryset = FtestWork.objects.all()
    serializer_class = FtestWorkSerializer
    create_serializer_class = FtestWorkCreateUpdateSerializer
    update_serializer_class = FtestWorkCreateUpdateSerializer
    select_related_fields = ['material']
    filterset_fields = ['material', 'batch']
