from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response
from rest_framework.exceptions import ParseError

from apps.mtm.filters import GoalFilter, MaterialFilter, RouteFilter
from apps.mtm.models import Goal, Material, Mgroup, Shift, Team, Process, Route, TeamMember
from apps.mtm.serializers import (GoalSerializer, MaterialSerializer,
                                  MgroupGoalYearSerializer, MgroupSerializer,
                                  ShiftSerializer, TeamSerializer, ProcessSerializer, RouteSerializer, TeamMemberSerializer)
from apps.mtm.services import get_mgroup_goals
from apps.utils.viewsets import CustomGenericViewSet, CustomModelViewSet
from apps.utils.mixins import BulkCreateModelMixin, BulkDestroyModelMixin


# Create your views here.
class MaterialViewSet(CustomModelViewSet):
    """
    list:产品

    产品
    """
    queryset = Material.objects.all()
    serializer_class = MaterialSerializer
    filterset_class = MaterialFilter
    search_fields = ['name', 'code', 'number', 'specification']
    select_related_fields = ['process']
    ordering = ['sort', 'id']


class ShiftViewSet(ListModelMixin, CustomGenericViewSet):
    """
    list:班次

    班次
    """
    perms_map = {'get': '*'}
    queryset = Shift.objects.all()
    serializer_class = ShiftSerializer
    search_fields = ['name']
    ordering = ['id']


class MgroupViewSet(CustomModelViewSet):
    """
    list:测点集

    测点集
    """
    queryset = Mgroup.objects.all()
    serializer_class = MgroupSerializer
    select_related_fields = ['create_by', 'belong_dept', 'process']
    filterset_fields = {
        "belong_dept": ["exact"],
        "process": ["exact"],
        "cate": ["exact"],
        "belong_dept__name": ["exact", "contains"],
        "name": ["exact", "contains"]
    }
    search_fields = ['number']
    ordering = ['sort', 'create_time']


class TeamViewSet(CustomModelViewSet):
    """
    list:班组

    班组
    """
    queryset = Team.objects.all()
    serializer_class = TeamSerializer
    select_related_fields = ['belong_dept', 'leader']
    filterset_fields = ['belong_dept']
    search_fields = ['name']


class TeamMemberViewSet(ListModelMixin, BulkCreateModelMixin, BulkDestroyModelMixin, CustomGenericViewSet):
    """
    list: 班组成员

    班组成员
    """
    perms_map = {'get': '*', 'post': 'team.update', 'delete': 'team.delete'}
    queryset = TeamMember.objects.all()
    serializer_class = TeamMemberSerializer
    select_related_fields = ['mgroup', 'post', 'team', 'user']
    filterset_fields = ['mgroup', 'post', 'team']


class GoalViewSet(CustomModelViewSet):
    """
    list: 目标

    目标
    """
    queryset = Goal.objects.all()
    serializer_class = GoalSerializer
    select_related_fields = ['mgroup', 'goal_cate']
    filterset_class = GoalFilter
    search_fields = ['name']
    ordering = ['mgroup__sort', 'goal_cate__sort', 'goal_cate__create_time']

    @action(methods=['post'], detail=False, perms_map={'post': '*'}, serializer_class=MgroupGoalYearSerializer)
    def mgroup_goals_year(self, request, pk=None):
        """
        获取工段全年目标

        获取工段全年目标
        """
        sr = MgroupGoalYearSerializer(data=request.data)
        sr.is_valid(raise_exception=True)
        vdata = sr.validated_data
        res = get_mgroup_goals(vdata['mgroup'], vdata['year'], True)
        return Response(res)


class ProcessViewSet(CustomModelViewSet):
    queryset = Process.objects.all()
    serializer_class = ProcessSerializer
    select_related_fields = ['belong_dept']
    search_fields = ['name', 'cate']
    filterset_fields = ['cate']
    ordering = ['sort', 'create_time']

    def perform_destroy(self, instance):
        if Route.objects.filter(process=instance).exists():
            raise ParseError('存在使用的工艺路线!')
        return super().perform_destroy(instance)


class RouteViewSet(CustomModelViewSet):
    queryset = Route.objects.all()
    serializer_class = RouteSerializer
    filterset_class = RouteFilter
    ordering = ['sort', 'create_time']
    select_related_fields = ['material',
                             'process', 'material_in', 'material_out', 'mgroup']
