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.filters import TechDocFilterset

from apps.mtm.models import Material, Process, RecordForm, RecordFormField, Step, SubprodctionMaterial, TechDoc, UsedStep, SubProduction
from apps.mtm.serializers import InputMaterialSerializer, InputMaterialUpdateSerializer, MaterialDetailSerializer, MaterialSerializer, MaterialSimpleSerializer, OtherMaterialSerializer, OutputMaterialSerializer, OutputMaterialUpdateSerializer, ProcessSerializer, RecordFormCreateSerializer, RecordFormDetailSerializer, RecordFormFieldCreateSerializer, RecordFormFieldSerializer, RecordFormFieldUpdateSerializer, RecordFormSerializer, RecordFormUpdateSerializer, StepDetailSerializer, StepSerializer, SubProductionSerializer, SubprodctionMaterialListSerializer, TechDocCreateSerializer, TechDocListSerializer, TechDocUpdateSerializer, UsedStepCreateSerializer, UsedStepListSerializer, UsedStepUpdateSerializer
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


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', 'type']
    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, ModelViewSet):
    """
    子工序-增删改查
    """
    perms_map = {'*':'*'}
    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 SubProductionViewSet(CreateUpdateModelAMixin, ModelViewSet):
    """
    产品生产分解增删改查
    """
    perms_map={'*':'*'}
    queryset = SubProduction.objects.select_related('process').all()
    filterset_fields = ['product', 'process']
    search_fields = ['name']
    serializer_class = SubProductionSerializer
    ordering = ['sort']

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

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

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

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

class OtherMaterialViewSet(CreateUpdateModelAMixin, ListModelMixin, DestroyModelMixin, CreateModelMixin, GenericViewSet):
    """
    其他物料-增删改查
    """
    perms_map = {'*':'*'}
    queryset = SubprodctionMaterial.objects.select_related('material').filter(type=SubprodctionMaterial.SUB_MA_TYPE_TOOL)
    serializer_class = OutputMaterialSerializer
    filterset_fields = ['subproduction']
    ordering = ['sort', '-create_time']

    def get_serializer_class(self):
        if self.action == 'list':
            return SubprodctionMaterialListSerializer
        return OtherMaterialSerializer

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

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

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

    def get_serializer_class(self):
        if self.action =='create':
            return RecordFormCreateSerializer
        elif self.action == 'update':
            return RecordFormUpdateSerializer
        elif self.action == 'retrieve':
            return RecordFormDetailSerializer
        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']
    ordering = 'id'
    ordering_fields = ['sort', 'id']

    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_class = TechDocFilterset
    search_fields = ['name']
    ordering = ['-id']

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