from utils.custom_modelviewset import CustomModelViewSet
from utils.permission import IsTenantUser, IsAdministratorUser
from rest_framework.views import APIView
from .models import Option
from .serializers import OptionSerializer
from .filters import OptionFilter
from apps.tenant import tenant_log
from apps.log.models import BizLog
from django.db import transaction
from utils import response_ok

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

    def get(self, request):
        ret = {
            'types':Option.TYPE_CHOICES,
        }
        return response_ok(ret)

class OptionViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser,]
    queryset = Option.objects.filter(delete=False)
    serializer_class = OptionSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(tenant=self.request.user.employee.tenant)
        f = OptionFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(OptionViewSet,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)

    def perform_update(self, serializer):
        super(OptionViewSet,self).perform_update(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)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            tenant_log(self.request.user.employee, BizLog.DELETE, u'删除系统选项[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()
