# coding=utf-8
from django.db import transaction
from rest_framework.views import APIView
from utils import response_ok
from utils.custom_modelviewset import CustomModelViewSet
from utils.permission import IsTenantUser, permission_required
from .models import Equipment
from .serializers import EquipmentSerializer
from .filters import EquipmentFilter
from apps.tenant import tenant_log
from apps.log.models import BizLog
from utils.exceptions import CustomError
from apps.tenant.option.serializers import OptionSerializer,Option

class DictView(APIView):
    permission_classes = [IsTenantUser, ]

    def get(self, request):
        tenant=request.user.employee.tenant
        ret = {
            'types': OptionSerializer(Option.objects.filter(delete=False,type=Option.EQUIPMENT_TYPE, enable=True, tenant=tenant), many=True).data,
            'suppliers': OptionSerializer(Option.objects.filter(delete=False,type=Option.EQUIPMENT_SUPPLIER, enable=True, tenant=tenant), many=True).data,
        }
        return response_ok(ret)

class EquipmentViewSet(CustomModelViewSet):
    permission_classes = [IsTenantUser, ]
    queryset = Equipment.objects.all()
    serializer_class = EquipmentSerializer

    @permission_required('equipment.browse_equipment')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(type__tenant=self.request.user.employee.tenant)
        f = EquipmentFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('equipment.add_equipment')
    def perform_create(self, serializer):
        super(EquipmentViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.INSERT, u'添加设备[%s]，id=%d' % (instance.name, instance.id),
                   validated_data)

    @permission_required('equipment.add_equipment')
    def perform_update(self, serializer):
        super(EquipmentViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.UPDATE, u'修改设备[%s]，id=%d' % (instance.name, instance.id),
                   validated_data)

    @permission_required('equipment.delete_equipment')
    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            with transaction.atomic():
                instance = self.get_object()
                if instance.type.tenant != request.user.employee.tenant:
                    raise CustomError(u'禁止跨租户操作！')
                super(EquipmentViewSet, self).destroy(self, request, *args, **kwargs)
            tenant_log(self.request.user.employee, BizLog.DELETE, u'删除设备[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()
