# coding=utf-8

import json

from django.db import transaction

from utils.custom_modelviewset import CustomModelViewSet
from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import IsEmployee

from apps.config.models import Config
from apps.config.serializers import ConfigSerializer
from apps.config.filters import ConfigFilter
from apps.log.models import BizLog


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

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)

    def create(self, request, *args,**kwargs):
        data = json.loads(request.POST.get('data'))
        keys = [
            'point_rule',
            'first_lv1', 'first_lv2', 'first_lv3', 'first_lv4', 'first_lv5',
            'again_lv1', 'again_lv2', 'again_lv3', 'again_lv4', 'again_lv5',
        ]
        with transaction.atomic():
            for item in data:
                config = Config.objects.filter(property=item['key']).first()
                if item['value']:
                    if item['key'] not in keys:
                        raise CustomError(u'综合设置属性[%s]不存在' % item['key'])
                    else:
                        item['value'] = item['value'].strip()

                    if config:
                        config.value = item['value']
                        config.save()
                    else:
                        Config.objects.create(property=item['key'], value=item['value'])
            BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'修改系统配置',data)
        return response_ok()

