# coding=utf-8
import json
from utils.custom_modelviewset import CustomModelViewSet
from rest_framework.views import APIView
from rest_framework.decorators import action
from django.db import transaction


from apps.option.models import Option
from apps.option.serializers import OptionSerializer
from apps.option.filters import OptionFilter
from apps.log.models import BizLog
from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import IsEmployee


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

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


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

    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        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
        BizLog.objects.addnew(self.request.user, 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
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE, u'修改自定义项[%s]，id=%d' % (instance.name, instance.id), validated_data)




