# coding=utf-8

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
from apps.account import tenant_log
from .filters import OptionFilter
from .serializers import OptionSerializer

class OptionDictView(APIView):

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

class OptionViewSet(CustomModelViewSet):
    queryset = Option.objects.filter()
    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()
            tenant_log(self.request.user, BizLog.DELETE, u'删除系统选项[%s]，id=%d' % (instance.name, instance.id))
            instance.delete()
        return response_ok()

    def create_default(self, request):
        if not self.request.user.has_perm('option.add_option'):
            raise CustomError(u"您没有[系统选项-添加]权限，无法执行该操作，请联系管理员分配权限！")
        tenant = request.user.employee.tenant
        with transaction.atomic():
            for default in Option.DEFAULT_OPTION:
                default['tenant'] = tenant
                is_exist = Option.is_exist(tenant, default['type'], default['name'])
                if is_exist:
                    continue
                Option.objects.create(**default)
            tenant_log(self.request.user, BizLog.INSERT, u'添加默认系统选项')
        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)
