# coding=utf-8

from django.db import transaction

from utils.permission import IsAdministratorUser
from utils.exceptions import CustomError
from utils import response_ok, response_error

from rest_framework import generics

from apps.log.models import BizLog
from apps.wechat.models import Wechat
from apps.wechat.serializers import WechatSerializer


class WechatViewSet(generics.RetrieveUpdateAPIView):
    '''查看修改小程序信息'''
    permission_classes = [IsAdministratorUser, ]
    serializer_class = WechatSerializer

    def get_object(self):
        instance = Wechat.objects.filter().first()
        if not instance:
            raise CustomError(u'未添加小程序！')
        return instance

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return response_ok(serializer.data)

    def update(self, request, *args, **kwargs):
        with transaction.atomic():
            super(WechatViewSet, self).update(request, *args, **kwargs)
        return response_ok()

    def perform_update(self, serializer):
        super(WechatViewSet, self).perform_update(serializer)
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE, u'修改小程序信息', validated_data)
