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

import logging

from django.conf import settings
from django.db import transaction
from django_redis_connector import connector
from django_six import CompatibilityBaseCommand, close_old_connections
from django_we.models import SubscribeUserInfo
from pywe_storage import RedisStorage
from pywe_user import get_user_info

from account.models import UserInfo
from mch.models import BrandInfo
from utils.redis.rkeys import SUBSCRIBE_USERINFO_LIST


r1 = connector(settings.REDIS.get('db1', {}))


WECHAT = settings.WECHAT


logger = logging.getLogger('console')


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

        logger.info('SubscribeUserInfo is dealing')

        brands = BrandInfo.objects.filter(status=True)
        subscribe_keys = [SUBSCRIBE_USERINFO_LIST % brand.brand_id for brand in brands]

        while True:
            # r.rpushjson('SUBSCRIBE_USERINFO_LIST', {
            #    'brand_id': 'brand_id',
            #    'openid': 'openid',
            # })
            k, v = r1.blpopjson(subscribe_keys, 60)
            if not v:
                continue

            logger.info(v)

            brand_id, openid = v.get('brand_id', ''), v.get('openid', '')

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

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

            userinfo = get_user_info(openid, appid=appid, secret=secret, storage=RedisStorage(r1))

            close_old_connections()

            with transaction.atomic():
                subscribe, unionid, openid = userinfo.get('subscribe', ''), userinfo.get('unionid', ''), userinfo.get('openid', '')
                if subscribe:
                    SubscribeUserInfo.objects.update_or_create(extraid=brand_id, openid=openid, defaults={
                        'unionid': unionid,
                        'nickname': userinfo.get('nickname', ''),
                        'sex': userinfo.get('sex', ''),
                        'headimgurl': userinfo.get('headimgurl', ''),
                        'country': userinfo.get('country', ''),
                        'province': userinfo.get('province', ''),
                        'city': userinfo.get('city', ''),
                        'subscribe': userinfo.get('subscribe', ''),
                        'subscribe_time': userinfo.get('subscribe_time', ''),
                        'subscribe_scene': userinfo.get('subscribe_scene', ''),
                        'groupid': userinfo.get('groupid', ''),
                        'tagid_list': userinfo.get('tagid_list', ''),
                        'qr_scene': userinfo.get('qr_scene', ''),
                        'qr_scene_str': userinfo.get('qr_scene_str', ''),
                        'language': userinfo.get('language', ''),
                        'remark': userinfo.get('remark', ''),
                    })
                    UserInfo.objects.filter(unionid=unionid).update(openid=openid)
                else:
                    SubscribeUserInfo.objects.filter(extraid=brand_id, openid=openid).update(subscribe=subscribe)

            close_old_connections()
