# coding=utf-8
import json
from django.db import transaction

from utils.permission import IsAdministratorUser
from apps.tenant.config.serializers import ConfigSerializer
from utils.custom_modelviewset import CustomModelViewSet
from apps.tenant.config.models import Config
from apps.tenant.config.filters import ConfigFilter
from apps.log.models import BizLog
from utils import response_ok, response_error


class ConfigViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser, ]
    queryset = Config.objects.filter()
    serializer_class = ConfigSerializer

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

    def create(self, request, *args, **kwargs):
        data = json.loads(request.POST.get('data'))
        with transaction.atomic():
            for item in data:
                config = Config.objects.filter(property=item['key']).first()
                if config:
                    config.value = item['value']
                    config.save()
                else:
                    Config.objects.create(property=item['key'], value=item['value'])
            BizLog.objects.addnew(None, request.user, BizLog.INSERT, u'修改系统设置', data)
        return response_ok()
