# -*- coding: utf-8 -*-

from curtail_uuid import CurtailUUID
from django.conf import settings
from django.db import transaction
from ipaddr import client_ip
from logit import logit
from pywe_miniapp import get_userinfo
from TimeConvert import TimeConvert as tc

from account.models import UserInfo
from utils.error.response_utils import response
from utils.redis.rprofile import set_profile_info


WECHAT = settings.WECHAT


@logit
@transaction.atomic
def get_userinfo_api(request):
    wxcfg = WECHAT.get('MINIAPP', {})

    appid = wxcfg.get('appID')
    secret = wxcfg.get('appsecret')

    code = request.POST.get('code', '')
    encryptedData = request.POST.get('encryptedData', '')
    iv = request.POST.get('iv', '')

    # {u'avatarUrl': u'http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0',
    #  u'city': u'Guangzhou',
    #  u'country': u'CN',
    #  u'gender': 1,
    #  u'language': u'zh_CN',
    #  u'nickName': u'Band',
    #  u'openId': u'oGZUI0egBJY1zhBYw2KhdUfwVJJE',
    #  u'province': u'Guangdong',
    #  u'unionId': u'ocMvos6NjeKLIBqg5Mr9QjxrP1FA',
    #  u'watermark': {u'appid': u'wx4f4bc4dec97d474b', u'timestamp': 1477314187}}
    userinfo = get_userinfo(appid=appid, secret=secret, code=code, encryptedData=encryptedData, iv=iv)

    # Get or Create User
    user, created = UserInfo.objects.select_for_update().get_or_create(unionid=userinfo.get('unionId', ''))

    # Set User_id
    if created:
        user.user_id = CurtailUUID.uuid(UserInfo, 'user_id')

    # Set User Key's Value
    user.user_from = UserInfo.MINIAPP_USER
    user.openid_miniapp = userinfo.get('openId', '')
    user.sex = userinfo.get('gender', '')
    user.nickname = userinfo.get('nickName', '')
    user.avatar = userinfo.get('avatarUrl', '')
    user.country = userinfo.get('country', '')
    user.province = userinfo.get('province', '')
    user.city = userinfo.get('city', '')
    user.user_status = UserInfo.ACTIVATED
    user.signup_ip = client_ip(request)
    user.signup_at = tc.utc_datetime()
    user.save()

    set_profile_info(user)

    return response(200, 'Mini App Login Success', u'微信小程序登录成功', user.data)
