from django.shortcuts import render
from rest_framework.exceptions import APIException
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from rest_framework import serializers, status
from rest_framework.response import Response
from apps.em.models import Equipment,Equipmentrecord
from apps.em.serializers import DaqCreateSerializer, EquipmentSerializer,EquipmentrecordSerializer
from apps.system.mixins import CreateUpdateModelAMixin, OptimizationMixin


# Create your views here.
class EquipmentViewSet(CreateUpdateModelAMixin, OptimizationMixin, ModelViewSet):
    """
    设备台账-增删改查
    """
    perms_map = {'get': '*', 'post': 'equipment_create',
                 'put': 'equipment_update', 'delete': 'equipment_delete'}
    queryset = Equipment.objects.all()
    serializer_class = EquipmentSerializer
    search_fields = ['number', 'name','description']
    filterset_fields = ['belong_dept', 'keeper', 'type']
    ordering_fields = ['create_time']
    ordering = ['-create_time']


# Create your views here.
class EquipmentrecordViewSet(CreateUpdateModelAMixin, OptimizationMixin, ModelViewSet):
    """
    设备校准-增删改查
    """
    perms_map = {'get': '*', 'post': 'equipmentrecord_create',
                 'put': 'equipmentrecord_update', 'delete': 'equipmentrecord_delete'}
    queryset = Equipmentrecord.objects.all()
    serializer_class = EquipmentrecordSerializer
    filterset_fields = ['equipment']
    ordering_fields = ['create_time']
    ordering = ['-create_time']
   
    def create(self, request, *args, **kwargs):
       
        data = request.data
        if data.get('equipment', None):
            equipment = Equipment.objects.get(pk=data['equipment'])
            equipment.statedm = data['state']
            equipment.save()
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_200_OK)
    def update(self, request, *args, **kwargs):
        data = request.data
        if data.get('equipment', None):
            equipment = Equipment.objects.get(pk=data['equipment'])
            equipment.statedm = data['state']
            equipment.save()
        id = self.get_object()
        serializer = self.get_serializer(id, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_200_OK)

import uuid
import os
from django.conf import settings
from rest_framework.parsers import MultiPartParser
class DaqView(APIView):
    """
    数据采集
    """
    authentication_classes = []
    permission_classes = []
    parser_classes = [MultiPartParser]

    def post(self, request, format=None):
        data = request.data
        file = data.get('file', None)
        equip_num = data.get('equip_num', None)
        filename = str(uuid.uuid4())
        filepath = settings.BASE_DIR +'/temp/' + filename + os.path.splitext(file.name)[-1]
        with open(filepath, 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)
        return Response()
        # raise APIException('解析失败')