from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin, ListModelMixin, UpdateModelMixin, RetrieveModelMixin, DestroyModelMixin

from apps.mtm.models import InputMaterial, Material, OutputMaterial, Process, ProductProcess, RecordForm, RecordFormField, Step, TechDoc, UsedStep
from apps.mtm.serializers import InputMaterialListSerializer, InputMaterialSerializer, InputMaterialUpdateSerializer, MaterialDetailSerializer, MaterialSerializer, MaterialSimpleSerializer, OutputMaterialListSerializer, OutputMaterialSerializer, OutputMaterialUpdateSerializer, ProductProcessListSerializer, ProductProcessUpdateSerializer, ProcessSerializer, RecordFormCreateSerializer, RecordFormFieldCreateSerializer, RecordFormFieldSerializer, RecordFormFieldUpdateSerializer, RecordFormSerializer, RecordFormUpdateSerializer, StepDetailSerializer, StepSerializer, TechDocCreateSerializer, TechDocListSerializer, TechDocUpdateSerializer, UsedStepCreateSerializer, UsedStepListSerializer
from apps.system.mixins import CreateUpdateModelAMixin, OptimizationMixin
from rest_framework.decorators import action
from rest_framework.response import Response
from utils.pagination import PageOrNot
from rest_framework.exceptions import APIException


# Create your views here.
class MaterialViewSet(PageOrNot, CreateUpdateModelAMixin, ModelViewSet):
    """
    物料表-增删改查
    """
    perms_map = {'get': '*', 'post': 'material_create',
                 'put': 'material_update', 'delete': 'material_delete'}
    queryset = Material.objects.all()
    serializer_class = MaterialSerializer
    search_fields = ['name', 'number']
    filterset_fields = ['type']
    ordering_fields = ['number', 'sort_str']
    ordering = ['number']

    def get_serializer_class(self, *args, **kwargs):
        if self.action == 'retrieve':
            return MaterialDetailSerializer
        return MaterialSerializer

    # @action(methods=['get'], detail=True, perms_map={'get':'*'}, pagination_class=None, serializer_class=MaterialSimpleSerializer)
    # def processes(self, request, pk=None):
    #     """
    #     产品生产工艺流程
    #     """
    #     material = self.get_object()
    #     serializer = self.serializer_class(instance=Process.objects.filter(id__in=material.processes), many=True)
    #     return Response(serializer.data)


class ProcessViewSet(PageOrNot, CreateUpdateModelAMixin, ModelViewSet):
    """
    工序表-增删改查
    """
    perms_map = {'get': '*', 'post': 'process_create',
                 'put': 'process_update', 'delete': 'process_delete'}
    queryset = Process.objects.select_related('instruction', 'workshop').all()
    serializer_class = ProcessSerializer
    search_fields = ['name', 'number']
    filterset_fields = ['number', 'workshop']
    ordering_fields = ['number']
    ordering = ['number']

    @action(methods=['get'], detail=True, perms_map={'get':'process_update'}, pagination_class=None, serializer_class=StepDetailSerializer)
    def steps(self, request, pk=None):
        """
        工序下的子工序
        """
        process = self.get_object()
        serializer = self.serializer_class(instance=Step.objects.prefetch_related('equipments').filter(process=process, is_deleted=False), many=True)
        return Response(serializer.data)

class StepViewSet(OptimizationMixin, CreateUpdateModelAMixin, CreateModelMixin, UpdateModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet):
    """
    子工序-增删改查
    """
    perms_map = {'*':'process_update'}
    queryset = Step.objects.all()
    serializer_class = StepSerializer
    search_fields = ['name', 'number']
    filterset_fields = ['process']
    ordering = ['sort']

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return StepDetailSerializer
        return StepSerializer

# class ProductProcessViewSet(PageOrNot, CreateModelMixin, UpdateModelMixin, ListModelMixin, DestroyModelMixin, GenericViewSet):
#     """
#     产品生产工艺流程增删改查
#     """
#     perms_map={'*':'*'}
#     queryset = ProductProcess.objects.select_related('process', 'product').all()
#     filterset_fields = ['process', 'product']
#     serializer_class = ProductProcessListSerializer
#     ordering = ['sort']

#     def get_serializer_class(self):
#         if self.action == 'update':
#             return ProductProcessUpdateSerializer
#         return super().get_serializer_class()

class InputMaterialViewSet(CreateUpdateModelAMixin, ModelViewSet):
    """
    输入物料-增删改查
    """
    perms_map = {'*':'*'}
    queryset = InputMaterial.objects.select_related('material').all()
    serializer_class = InputMaterialSerializer
    filterset_fields = ['process', 'material']
    ordering = ['sort', '-create_time']

    def get_serializer_class(self):
        if self.action == 'list':
            return InputMaterialListSerializer
        elif self.action == 'update':
            return InputMaterialUpdateSerializer
        return InputMaterialSerializer

class OutputMaterialViewSet(CreateUpdateModelAMixin, ModelViewSet):
    """
    输出物料-增删改查
    """
    perms_map = {'*':'*'}
    queryset = OutputMaterial.objects.select_related('material').all()
    serializer_class = OutputMaterialSerializer
    filterset_fields = ['process', 'material']
    ordering = ['sort', '-create_time']

    def get_serializer_class(self):
        if self.action == 'list':
            return OutputMaterialListSerializer
        elif self.action == 'update':
            return OutputMaterialUpdateSerializer
        return OutputMaterialSerializer

class UsedStepViewSet(OptimizationMixin, CreateUpdateModelAMixin, CreateModelMixin, DestroyModelMixin, ListModelMixin, GenericViewSet):
    """
    产品生产子工序表
    """
    perms_map = {'*':'*'}
    queryset = UsedStep.objects.all()
    filterset_fields = ['process', 'product', 'step']
    ordering = ['step__sort', '-step__create_time']

    def get_serializer_class(self):
        if self.action =='create':
            return UsedStepCreateSerializer
        return UsedStepListSerializer

class RecordFormViewSet(OptimizationMixin, CreateUpdateModelAMixin, ModelViewSet):
    """
    记录表格增删改查
    """
    perms_map = {'*':'*'}
    queryset = RecordForm.objects.all()
    filterset_fields = ['step', 'type']
    search_fields = ['name']

    def get_serializer_class(self):
        if self.action =='create':
            return RecordFormCreateSerializer
        elif self.action == 'update':
            return RecordFormUpdateSerializer
        return RecordFormSerializer
    
    @action(methods=['get'], detail=True, perms_map={'get':'*'}, pagination_class=None, serializer_class=RecordFormFieldSerializer)
    def fields(self, request, pk=None):
        """
        表格下的字段
        """
        instance = self.get_object()
        serializer = self.serializer_class(instance=RecordFormField.objects.filter(form=instance, is_deleted=False), many=True)
        return Response(serializer.data)


class RecordFormFieldViewSet(OptimizationMixin, CreateUpdateModelAMixin, ModelViewSet):
    """
    表格字段表 增删改查
    """
    perms_map = {'*':'*'}
    queryset = RecordFormField.objects.all()
    filterset_fields = ['field_type', 'form']
    search_fields = ['field_name', 'field_key']

    def get_serializer_class(self):
        if self.action =='create':
            return RecordFormFieldCreateSerializer
        elif self.action == 'update':
            return RecordFormFieldUpdateSerializer
        return RecordFormFieldSerializer

class TechDocViewSet(OptimizationMixin, CreateUpdateModelAMixin, ModelViewSet):
    """
    技术文件增删改查
    """
    perms_map = {'*':'*'}
    queryset = TechDoc.objects.select_related('file').all()
    filterset_fields = ['process', 'product']
    search_fields = ['name']
    ordering = ['-id']

    def get_serializer_class(self):
        if self.action =='create':
            return TechDocCreateSerializer
        elif self.action == 'update':
            return TechDocUpdateSerializer
        return TechDocListSerializer