from django.shortcuts import render
from apps.em.models import Equipment, EcheckRecord, EInspect
from apps.utils.viewsets import CustomModelViewSet, CustomGenericViewSet
from apps.em.serializers import EquipmentSerializer, EcheckRecordSerializer, EInspectSerializer
from apps.em.filters import EquipFilterSet
from rest_framework.exceptions import ParseError
from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin
from dateutil.relativedelta import relativedelta
from rest_framework.decorators import action
from rest_framework.serializers import Serializer
from django.db import transaction
from apps.em.services import daoru_equipment
from rest_framework.response import Response
from django.conf import settings

# Create your views here.


class EquipmentViewSet(CustomModelViewSet):
    queryset = Equipment.objects.all()
    serializer_class = EquipmentSerializer
    select_related_fields = ['create_by', 'belong_dept', 'keeper', 'mgroup']
    search_fields = ['number', 'name']
    filterset_class = EquipFilterSet

    def filter_queryset(self, queryset):
        if not self.detail and not self.request.query_params.get('type', None):
            raise ParseError('请指定设备类型')
        return super().filter_queryset(queryset)

    @action(methods=['post'], detail=False, perms_map={'post': 'equipment.create'}, serializer_class=Serializer)
    @transaction.atomic
    def daoru(self, request, *args, **kwargs):
        """导入

        导入
        """
        daoru_equipment(settings.BASE_DIR + request.data.get('path', ''))
        return Response()



class EcheckRecordViewSet(ListModelMixin, CreateModelMixin, DestroyModelMixin, CustomGenericViewSet):
    """
    list:校准/检定记录

    校准/检定记录
    """
    perms_map = {'get': '*', 'post': 'echeckrecord.create',
                 'put': 'echeckrecord.update', 'delete': 'echeckrecord.delete'}
    queryset = EcheckRecord.objects.all()
    serializer_class = EcheckRecordSerializer
    select_related_fields = ['equipment', 'create_by']
    filterset_fields = ['equipment', 'result']

    def perform_create(self, serializer):
        instance = serializer.save()
        equipment = instance.equipment
        if equipment.cycle:
            equipment.check_date = instance.check_date
            equipment.next_check_date = instance.check_date + \
                relativedelta(months=equipment.cycle)
            equipment.save()

    def perform_destroy(self, instance):
        instance.delete()
        equipment = instance.equipment
        er = EcheckRecord.objects.filter(
            equipment=equipment).order_by('check_date').last()
        if er:
            equipment.check_date = instance.check_date
            equipment.next_check_date = instance.check_date + \
                relativedelta(months=equipment.cycle)
            equipment.save()
        else:
            equipment.check_date = None
            equipment.next_check_date = None
            equipment.save()


class EInspectViewSet(CustomModelViewSet):
    """
    list:巡检记录

    巡检记录
    """
    queryset = EInspect.objects.all()
    serializer_class = EInspectSerializer
    select_related_fields = ['equipment', 'inspect_user']
    filterset_fields = ['equipment']
