# coding=utf-8

from django.db import transaction
from rest_framework.viewsets import ReadOnlyModelViewSet
from utils.permission import IsAdministrator
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import SysLog

from apps.knowledge.models import KnowledgeBase, KnowledgeBaseFeedback
from apps.knowledge.filters import KnowledgeBaseFilter, KnowledgeBaseFeedbackFilter
from apps.knowledge.serializers import KnowledgeBaseSerializer, KnowledgeBaseFeedbackSerializer


class KnowledgeBaseViewSet(CustomModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = KnowledgeBase.objects.filter(delete=False)
    serializer_class = KnowledgeBaseSerializer

    def filter_queryset(self, queryset):
        f = KnowledgeBaseFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(KnowledgeBaseViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        SysLog.objects.addnew(self.request.user, SysLog.INSERT, u'添加知识[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def perform_update(self, serializer):
        super(KnowledgeBaseViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'修改知识[%s]，id=%d' % (instance.name, instance.id), validated_data)

        if 'feedback' in self.request.data and self.request.data['feedback']:
            feedback = KnowledgeBaseFeedback.getById(self.request.data['feedback'])
            feedback.process(self.request.user)
            feedback.save()
            SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'处理知识错误反馈，id=%d' % (feedback.id))

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            SysLog.objects.addnew(self.request.user, SysLog.DELETE, u'删除知识[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()

class KnowledgeBaseFeedbackViewSet(ReadOnlyModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = KnowledgeBaseFeedback.objects.filter().order_by('status', '-id')
    serializer_class = KnowledgeBaseFeedbackSerializer

    def filter_queryset(self, queryset):
        f = KnowledgeBaseFeedbackFilter(self.request.GET, queryset=queryset)
        return f.qs