from apps.am.models import Access, Area
from apps.am.serializers import AccessCreateSerializer, AccessSerializer, AreaCreateUpdateSerializer, AreaSerializer
from apps.am.tasks import cache_areas_info
from apps.utils.viewsets import CustomModelViewSet, CustomGenericViewSet
from django.db import transaction
from rest_framework.decorators import action
from rest_framework import serializers
from apps.third.xunxi import xxClient
from apps.third.tapis import xxapis
from rest_framework.response import Response
from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin


# Create your views here.
class AreaViewSet(CustomModelViewSet):
    queryset = Area.objects.all().order_by('number')
    create_serializer_class = AreaCreateUpdateSerializer
    update_serializer_class = AreaCreateUpdateSerializer
    serializer_class = AreaSerializer
    ordering = ['number']
    search_fields = ['number', 'name']

    def create(self, request, *args, **kwargs):
        ret = super().create(request, *args, **kwargs)
        cache_areas_info.delay()
        return ret

    def update(self, request, *args, **kwargs):
        ret = super().update(request, *args, **kwargs)
        cache_areas_info.delay()
        return ret

    @transaction.atomic
    @action(methods=['post'], detail=True, perms_map={'post': 'area.bind_rail'},
            serializer_class=serializers.Serializer)
    def bind_rail(self, request, pk=None):
        """
        绑定围栏

        绑定围栏
        """
        data = request.data
        obj = self.get_object()
        third_info = obj.third_info
        if 'xx_rail' in third_info:
            data['uuid'] = third_info['xx_rail']['id']
            _, res = xxClient.request(**xxapis['rail_update'], json={'rail': data})
            third_info['xx_rail']['detail'] = data
            obj.third_info = third_info
            obj.save()
        else:
            _, res = xxClient.request(**xxapis['rail_create'], json={'rail': data})
            rail_info = {'id': res, 'detail': data}
            third_info['xx_rail'] = rail_info
            obj.third_info = third_info
            obj.save()
        cache_areas_info.delay()
        return Response()


class AccessViewSet(ListModelMixin, CreateModelMixin, DestroyModelMixin, CustomGenericViewSet):
    perms_map = {'get': '*', 'post': 'access.create', 'delete': 'access.delete'}
    queryset = Access.objects.all()
    create_serializer_class = AccessCreateSerializer
    serializer_class = AccessSerializer
    filterset_fields = ['area', 'type', 'obj_cate', 'post', 'dept', 'employee']
    select_related_fields = ['area', 'post', 'dept', 'employee']
