# coding=utf-8

from django.db import transaction
from django.db.models import Sum

from rest_framework.views import APIView
from rest_framework_jwt.views import VerifyJSONWebToken,RefreshJSONWebToken
from rest_framework.serializers import ValidationError
from rest_framework.decorators import action

from utils import response_ok, response_error
from utils.permission import IsCustomer, IsEmployee
from utils.custom_modelviewset import CustomModelViewSet

from apps.customer.serializers import WechatLoginSerializer, WechatBindSerializer, CustomerSerializer
from apps.customer.models import Customer
from apps.customer.filters import CustomerFilter
from apps.log.models import BizLog
from apps.base import Formater


class WxLoginView(APIView):
    serializer_class = WechatLoginSerializer

    def post(self, request, *args, **kwargs):
        ser = self.serializer_class(data=request.data)
        if ser.is_valid():
            return response_ok(ser.validated_data)
        else:
            return response_error('参数错误')


class WxBindView(APIView):
    serializer_class = WechatBindSerializer

    def post(self, request, *args, **kwargs):
        ser = self.serializer_class(data=request.data)
        if ser.is_valid():
            return response_ok(ser.validated_data)
        else:
            return response_error('参数错误')


class SetUserInfoView(APIView):
    permission_classes = [IsCustomer, ]

    def post(self, request, *args, **kwargs):
        appid = request.POST.get('appid')
        openid = request.POST.get('openid')
        encryptedData = request.POST.get('encryptedData')
        iv = request.POST.get('iv')

        with transaction.atomic():
            face, name = request.customer.setInfo(appid, openid, encryptedData, iv)
        return response_ok({'face': face, 'name': name})


class CustomerRefreshTokenView(RefreshJSONWebToken):
    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                return response_ok({'token': ser.validated_data['token']})
        except ValidationError as e:
            return response_error(u'登录状态失效，请重新登录[' + e.detail['error'][0] + ']')


class CustomerVerifyTokenView(VerifyJSONWebToken):
    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                return response_ok({'token': ser.validated_data['token']})
        except ValidationError as e:
            return response_error(u'登录状态失效，请重新登录[' + e.detail['error'][0] + ']')


class CustomerViewSet(CustomModelViewSet):
    permission_classes = [IsEmployee, ]
    queryset = Customer.objects.filter()
    serializer_class = CustomerSerializer

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

    def list(self, request, *args, **kwargs):
        footer = {}
        queryset = self.filter_queryset(self.get_queryset())
        total_row = queryset.aggregate(
            balance=Sum('balance'), points=Sum('points'), success_count=Sum('success_count'),
            total_amount=Sum('total_amount'), total_point=Sum('total_point')
        )
        footer['total_balance'] = Formater.formatAmountShow(total_row['balance'] or 0)
        footer['total_points'] = str(total_row['points'] or 0)
        footer['total_success_count'] = str(total_row['success_count'] or 0)
        footer['all_total_amount'] = Formater.formatAmountShow(total_row['total_amount'] or 0)
        footer['all_total_point'] = str(total_row['total_point'] or 0)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response({'data': serializer.data, 'footer': footer})
        serializer = self.get_serializer(queryset, many=True)
        return response_ok({'data': serializer.data, 'footer': footer})

    @action(methods=['get'], detail=False)
    def export(self, request):
        queryset = self.filter_queryset(self.queryset)
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)
