
from rest_framework.response import Response
from apps.opm.models import GasCheck, Operation, Opl, OplCate, OplWorker
from apps.opm.serializers import (GasCheckCreateUpdateSerializer, GasCheckSerializer,
                                  OperationCreateUpdateSerializer, OperationDetailSerializer,
                                  OplCateCreateUpdateSerializer, OplCateDetailSerializer, OplCateSerializer,
                                  OplCreateUpdateSerializer, OplDetailSerializer, OplListSerializer,
                                  OplWorkerCreateSerializer, OplWorkerSerializer, OplWorkerUpdateSerializer,
                                  OperationPartialUpdateSerializer)
from apps.opm.services import close_mtask, start_mtask
from apps.utils.viewsets import CustomGenericViewSet, CustomModelViewSet
from rest_framework.exceptions import ParseError
from rest_framework.mixins import CreateModelMixin, ListModelMixin, DestroyModelMixin
from rest_framework.decorators import action
from rest_framework.serializers import Serializer
from apps.wf.models import Ticket
from django.core.cache import cache
from django.db import transaction
from apps.opm.filters import OperationFilterset

# Create your views here.


class OplCateViewSet(CustomModelViewSet):
    queryset = OplCate.objects.all()
    create_serializer_class = OplCateCreateUpdateSerializer
    update_serializer_class = OplCateCreateUpdateSerializer
    retrieve_serializer_class = OplCateDetailSerializer
    serializer_class = OplCateSerializer
    prefetch_related_fields = ['measure_options', 'risk_options', 'close_options']
    ordering = 'sort'


class OperationViewSet(CustomModelViewSet):
    perms_map = {'get': 'operation.view', 'post': 'operation.create',
                 'put': 'operation.update', 'delete': 'operation.delete'}
    queryset = Operation.objects.all()
    create_serializer_class = OperationCreateUpdateSerializer
    update_serializer_class = OperationCreateUpdateSerializer
    partial_update_serializer_class = OperationPartialUpdateSerializer
    serializer_class = OperationDetailSerializer
    retrieve_serializer_class = OperationDetailSerializer
    select_related_fields = ['area', 'dept_bus', 'dept_ter', 'coordinator']
    prefetch_related_fields = ['cates']
    search_fields = ['name']
    filterset_class = OperationFilterset
    # data_filter = True

    def update(self, request, *args, **kwargs):
        obj = self.get_object()
        user = request.user
        if user.is_superuser:
            pass
        elif obj.state == Operation.OP_CREATE and user == obj.create_by:
            pass
        elif user == obj.create_by and kwargs['partial']:
            pass
        else:
            raise ParseError('该作业不可修改')
        return super().update(request, *args, **kwargs)

    @transaction.atomic
    def destroy(self, request, *args, **kwargs):
        obj = self.get_object()
        user = request.user
        if user.is_superuser:
            pass
        else:
            if obj.state != Operation.OP_CREATE:
                raise ParseError('非创建状态不可删除')
            if user != obj.create_by:
                raise ParseError('非创建人不可删除')
        Ticket.objects.filter(id__in=Opl.objects.filter(operation=obj).values_list('ticket', flat=True)).delete()  # 删除可能的工单
        obj.delete()
        return Response(status=204)


class OplViewSet(CustomModelViewSet):
    queryset = Opl.objects.all()
    create_serializer_class = OplCreateUpdateSerializer
    update_serializer_class = OplCreateUpdateSerializer
    serializer_class = OplListSerializer
    retrieve_serializer_class = OplDetailSerializer
    select_related_fields = ['cate', 'operation', 'dept_do', 'charger', 'monitor', 'ticket']
    prefetch_related_fields = ['close_imgs', 'audit_imgs', 'work_imgs', 'create_imgs']
    filterset_fields = ['operation', 'cate']

    @transaction.atomic
    def destroy(self, request, *args, **kwargs):
        obj = self.get_object()
        if obj.ticket and obj.ticket.state.type !=1:
            raise ParseError('许可证已处理不可删除')
        user = request.user
        if user == obj.create_by or user.is_superuser:
            pass
        else:
            raise ParseError('非创建人不可删除')
        if obj.ticket:
            obj.ticket.delete()
        obj.delete()
        return Response(status=204)

    def update(self, request, *args, **kwargs):
        obj = self.get_object()
        if obj.ticket and obj.ticket.state.type != 1:
            raise ParseError('许可证已处理不可编辑')
        user = request.user
        if user == obj.create_by or user.is_superuser:
            pass
        else:
            raise ParseError('非创建人不可编辑')
        return super().update(request, *args, **kwargs)

    @action(methods=['post'], detail=True, perms_map={'post': '*'},
            serializer_class=Serializer, logging_methods=['POST'])
    def start_mtask(self, request, pk=None):
        """
        开启作业监控

        开启作业监控
        """
        obj = self.get_object()
        if obj.operation.state == Operation.OP_DONE:
            raise ParseError('作业已关闭,不能开启监控')
        res = start_mtask(obj)
        return Response(res)

    @action(methods=['post'], detail=True, perms_map={'post': '*'},
            serializer_class=Serializer, logging_methods=['POST'])
    def stop_mtask(self, request, pk=None):
        """
        停止作业监控

        停止作业监控
        """
        obj = self.get_object()
        close_mtask(obj)
        return Response()


class OplWorkerViewSet(CustomModelViewSet):
    perms_map = {'get': '*', 'post': 'opl.update', 'put': 'opl.update', 'delete': 'opl.update'}
    queryset = OplWorker.objects.all()
    create_serializer_class = OplWorkerCreateSerializer
    update_serializer_class = OplWorkerUpdateSerializer
    serializer_class = OplWorkerSerializer
    filterset_fields = ['opl']

    # def get_queryset(self):
    #     if self.request.query_params.get('opl', None):
    #         raise ParseError('请指定查询许可证')
    #     return super().get_queryset()

    def destroy(self, request, *args, **kwargs):
        obj = self.get_object()
        ticket = obj.opl.ticket
        if ticket and ticket.state.type !=1:
            raise ParseError('许可证已处理不可删除')
        return super().destroy(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):
        obj = self.get_object()
        ticket = obj.opl.ticket
        if ticket and ticket.state.type !=1:
            raise ParseError('许可证已处理不可编辑')
        return super().update(request, *args, **kwargs)


class GasCheckViewSet(CreateModelMixin, ListModelMixin, DestroyModelMixin, CustomGenericViewSet):
    perms_map = {'get': '*', 'post': 'opl.update', 'delete': 'opl.update'}
    queryset = GasCheck.objects.all()
    create_serializer_class = GasCheckCreateUpdateSerializer
    serializer_class = GasCheckSerializer
    filterset_fields = ['opl']

    def destroy(self, request, *args, **kwargs):
        obj = self.get_object()
        ticket = obj.opl.ticket
        if ticket and ticket.state.type != 1:
            raise ParseError('许可证已处理不可删除')
        obj.delete()
        return Response(status=204)
