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

import logging

from django.conf import settings
from django.db import transaction
from django_six import CompatibilityBaseCommand, close_old_connections
from pywe_membercard import get_userinfo
from pywe_storage import RedisStorage

from account.models import UserInfo
from utils.redis.connect import r
from utils.redis.rkeys import MEMBERCARD_USERINFO_LIST


WECHAT = settings.WECHAT


logger = logging.getLogger('console')


def get_phone(fields):
    for field in fields:
        name = field.get('name', '')
        if name == 'USER_FORM_INFO_FLAG_MOBILE':
            return field.get('value', '')
    return ''


class Command(CompatibilityBaseCommand):
    def handle(self, *args, **options):

        logger.info('MemberCard userinfo is dealing')

        while True:
            # r.rpushjson('MEMBERCARD_USERINFO_LIST', {
            #    'brand_id': 'brand_id',
            #    'card_id': 'card_id',
            #    'code': 'code',
            # })
            k, v = r.blpopjson(MEMBERCARD_USERINFO_LIST, 60)
            if not v:
                continue

            logger.info(v)

            brand_id, card_id, code = v.get('brand_id', ''), v.get('card_id', ''), v.get('code', '')

            if not (card_id and code):
                continue

            wxcfg = WECHAT.get('{}:JSAPI'.format(brand_id), {})

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

            userinfo = get_userinfo(card_id, code, appid=appid, secret=secret, storage=RedisStorage(r))

            logger.info(userinfo)

            userinfo = userinfo.get('user_info', {})
            if not userinfo:
                continue

            common_field_list = userinfo.get('common_field_list', [])
            phone = get_phone(common_field_list)

            if not phone:
                continue

            close_old_connections()

            with transaction.atomic():
                UserInfo.objects.select_for_update().filter(membercardid=card_id, memberusercardcode=code).update(phone=phone)

            close_old_connections()
