# coding=utf-8

import traceback
import json

from django.views.decorators.csrf import csrf_exempt
from django.db import transaction
from apps.exceptions import CustomError
from apps.foundation.models import BizLog
from libs.http import JSONResponse, JSONError, DataGridJSONResponse
from apps.account.decorators import permission_required, token_required
from models import Config
from serializers import  ConfigSerializer

@token_required
def get_value(request):
    property = request.GET.get('property')
    value = Config.getValue(property)

    return JSONResponse(value)

@csrf_exempt
@permission_required('config.edit_config')
def config_save(request):
    data = json.loads(request.POST.get('data'))

    try:
        with transaction.atomic():
            for item in data:
                if not item['value']:
                    continue

                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(request.user, BizLog.UPDATE, u"修改系统配置", data)
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        return JSONError(u'保存失败！')
    return JSONResponse()

@csrf_exempt
@token_required
def config_list(request):
    rows = Config.objects.filter()
    serializer = ConfigSerializer(rows, many=True)
    return JSONResponse(serializer.data)
