# coding=utf-8

import traceback

from rest_framework import generics
from rest_framework.views import APIView

from django.conf import settings

from util import response_ok, response_error
from util.wx.wechat import WeChat
from util.permission import IsCustomerUser
from util.exceptions import CustomError

from apps.customer.activity.serializers import ActivitySerializer
from apps.activity.models import Activity
from apps.WechatApplet.models import WechatApplet


class ActivityDetailView(generics.RetrieveAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = Activity.objects.filter(enabled=True, delete=False, check_status=settings.PASS)
    serializer_class = ActivitySerializer

    def retrieve(self, request, *args, **kwargs):
        activity_id = request.GET.get('activity_id')

        instance = self.queryset.filter(id=activity_id).first()
        if not instance:
            raise CustomError(u'未找到相应活动信息！')
        serializer = self.get_serializer(instance)
        return response_ok(serializer.data)



class ActivityPosterView(APIView):
    '''必须登录才能生成海报'''
    permission_classes = [IsCustomerUser, ]

    def get(self, request):
        appid = request.GET.get('appid', None)
        activity_id = request.GET.get('activity_id', None)

        try:
            app = WechatApplet.getByAppid(appid)
            activity = Activity.getById(activity_id)
            wxCode = app.generateActivityCode(request.customer.id, activity.id)
            serializer = ActivitySerializer(activity)
            data = serializer.data
            data['wxCode'] = settings.MEDIA_URL + wxCode
            return response_ok(data)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            traceback.print_exc()
            return response_error(str(e))
