# coding=utf-8

from django.db import transaction

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
from apps.account import tenant_log

from .filters import ActivityFilter
from .serializers import ActivitySerializer
from .models import Activity


class ActivityViewSet(CustomModelViewSet):
    queryset = Activity.objects.filter(is_deleted=False)
    serializer_class = ActivitySerializer

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

    def perform_create(self, serializer):
        super(ActivityViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.INSERT, u'添加活动[%s]，id=%d' % (instance.title, instance.id), validated_data)

    @action(methods=['post'], detail=True)
    def update_obj(self, request, pk):
        '''
        由于layui上传文件使用的是post方法，且不能改为put方法，所以不能通过重写update来实现更新实例
        '''
        obj = self.get_object()
        if obj.is_deleted:
            raise CustomError(u'该活动已删除，禁止操作！')

        with transaction.atomic():
            serializer = self.get_serializer(obj, data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            instance = serializer.instance
            validated_data = serializer.validated_data
            tenant_log(self.request.user, BizLog.UPDATE, u'修改活动[%s]，id=%d' % (instance.title, instance.id), validated_data)
        return response_ok()

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.is_deleted = True
            instance.save()
            tenant_log(self.request.user, BizLog.DELETE, u'删除活动[%s]，id=%d' % (instance.title, instance.id))
        return response_ok()
