# coding=utf-8

from django.db import transaction
from django.conf import settings

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

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

from apps.customer.serializers import WechatLoginSerializer, WechatBindSerializer
from apps.customer.models import Customer


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 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')

        customer = Customer.objects.filter(openid=openid, app__appid=appid).first()
        if not customer:
            raise CustomError(u'未找到相应的微信客户！')
        user = request.user
        if customer.user and customer.user.id != user.id:
            raise CustomError(u'该微信已同步其他客户！')
        if not customer.user:
            customer.user = user
            customer.save()
        pc = WXBizDataCrypt(appid, customer.session_key)
        result = pc.decrypt(encryptedData, iv)
        with transaction.atomic():
            if result['gender'] == 1:
                user.gender = settings.MALE
            elif result['gender'] == 2:
                user.gender = settings.FEMALE
            else:
                user.gender = settings.UNKNOW
            user.name = result['nickName']
            user.face = result['avatarUrl']
            user.save()
        return response_ok()
