# coding=utf-8

import traceback

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

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

from django.contrib.auth import get_user_model
from django.db import transaction

from apps.customer.serializers import WechatLoginSerializer, WechatBindSerializer
from apps.activity.models import Activity
from apps.customer.models import Customer, CustomerWechat

User = get_user_model()


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 = [IsCustomerUser, ]

    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')
        try:
            customer = request.customer
            customer_wechat = CustomerWechat.objects.filter(openid=openid, customer=customer).first()
            if not customer_wechat:
                raise CustomError(u'未找到相应的微信客户！')

            if customer_wechat.customer and customer_wechat.customer.id != customer.id:
                raise CustomError(u'该微信已同步其他客户！')
            if not customer_wechat.customer:
                customer_wechat.customer = customer
                customer_wechat.save()
            pc = WXBizDataCrypt(appid, customer_wechat.session_key)
            result = pc.decrypt(encryptedData, iv)
            with transaction.atomic():
                if customer.name == customer.tel:
                    customer.name = result['nickName']
                customer.gender = result['gender']
                customer.face = result['avatarUrl']
                customer.save()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            traceback.print_exc()
            return response_error(u'保存失败！')
        return response_ok({'face':customer.face,'name':customer.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] + ']')
