from utils.custom_modelviewset import CustomModelViewSet
from rest_framework.views import APIView
from .models import Option
from .serializers import OptionSerializer
from .filters import OptionFilter
from apps.log.models import BizLog
from utils import response_ok
from utils.permission import isLogin, permission_required

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

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

class OptionViewSet(CustomModelViewSet):
    queryset = Option.objects.filter()
    serializer_class = OptionSerializer

    @permission_required('option.browse_option')
    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        f = OptionFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('option.add_option')
    def perform_create(self, serializer):
        super(OptionViewSet,self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加自定义项[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('option.add_option')
    def perform_update(self, serializer):
        super(OptionViewSet,self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改自定义项[%s]，id=%d' % (instance.name, instance.id), validated_data)
