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

from utils.permission import IsAdministratorUser, permission_required
from .serializers import ConfigSerializer
from utils.custom_modelviewset import CustomModelViewSet
from .models import Config
from .filters import ConfigFilter
from utils.exceptions import CustomError
from apps.tenant import tenant_log
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

    @permission_required('config.set_config')
    def create(self, request):
        data = json.loads(request.POST.get('data'))
        keys = ['repairs_person', 'send_order_type']
        with transaction.atomic():
            for item in data:
                config = Config.objects.filter(property=item['key'], tenant=self.request.user.employee.tenant).first()
                if item['key'] not in keys:
                    raise CustomError(u'系统设置属性[%s]不存在' % item['key'])
                if config:
                    config.value = item['value']
                    config.save()
                else:
                    Config.objects.create(tenant=self.request.user.employee.tenant, property=item['key'],
                                                   value=item['value'])

            tenant_log(self.request.user.employee, BizLog.INSERT, u'修改系统设置', data)
        return response_ok()
