# coding=utf-8
import json
from django.db import transaction
from rest_framework.views import APIView
from rest_framework.decorators import action
from utils import response_ok
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from apps.foundation.models import BizLog, Option, Config
from apps.account import tenant_log
from .filters import OptionFilter, ConfigFilter
from .serializers import OptionSerializer, ConfigSerializer

class OptionDictView(APIView):

    def get(self, request):
        ret = {
            'types':Option.TYPE_CHOICES,
        }
        return response_ok(ret)

class OptionViewSet(CustomModelViewSet):
    queryset = Option.objects.filter(delete=False)
    serializer_class = OptionSerializer

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

    def perform_create(self, serializer):
        super(OptionViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.INSERT, u'添加系统选项[%s]，id=%d' % (instance.name, instance.id),validated_data)

    def perform_update(self, serializer):
        super(OptionViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.UPDATE, u'修改系统选项[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            tenant_log(self.request.user, BizLog.DELETE, u'删除系统选项[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()

class OptionSearchSearch(APIView):
    def get(self, request):
        type = request.GET.get('type')
        keyword = request.GET.get('keyword')
        rows = Option.objects.filter(delete=False, enable=True, tenant=request.user.employee.tenant)
        if type:
            rows = rows.filter(type=int(type))

        if keyword:
            rows = rows.filter(name__icontains=keyword)

        data = []
        for row in rows:
            item ={
                'value': row.id,
                'id': row.id,
                'name': row.name,
                'notes': row.notes
            }
            data.append(item)

        return response_ok(data)


class ConfigViewSet(CustomModelViewSet):
    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

    #@action(methods=['post'], detail=True)
    def create(self, request):

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