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

import logging

from django.db import transaction
from django_six import CompatibilityBaseCommand, close_old_connections

from account.models import UserInfo
from api.hb_views import exec_clerk_send_jsapi_hb, exec_send_jsapi_hb
from logs.models import MchInfoEncryptLogInfo
from utils.redis.connect import r
from utils.redis.rkeys import REDPACK_WAITING_SEND_LIST


logger = logging.getLogger('console')


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

        logger.info('Redpack is dealing')

        while True:
            # r.rpushjson('REDPACK_WAITING_SEND_LIST', {
            #    'sn': 'sn',
            #    'user_id': 'user_id',
            #    'amount': amount,
            #    'is_clerk': 1,
            # })
            k, v = r.blpopjson(REDPACK_WAITING_SEND_LIST, 60)
            if not v:
                continue

            logger.info(v)

            close_old_connections()

            with transaction.atomic():
                try:
                    elog = MchInfoEncryptLogInfo.objects.select_for_update().get(sn=v.get('sn', ''))
                except MchInfoEncryptLogInfo.DoesNotExist:
                    logger.info('MchInfoEncryptLogInfo.DoesNotExist')
                    continue
                except MchInfoEncryptLogInfo.MultipleObjectsReturned:
                    logger.info('MchInfoEncryptLogInfo.MultipleObjectsReturned')
                    continue

                try:
                    user = UserInfo.objects.get(user_id=v.get('user_id', ''))
                except UserInfo.DoesNotExist:
                    logger.info('UserInfo.DoesNotExist')
                    continue

                if not user.openid:
                    logger.info('UserInfo.OpenID.DoesNotExist')
                    r.rpushjson(REDPACK_WAITING_SEND_LIST, v)
                    continue

                if v.get('user_id', '') == 1:
                    exec_clerk_send_jsapi_hb(user, elog, v.get('amount', 100))
                else:
                    exec_send_jsapi_hb(user, elog, v.get('amount', 100))

            close_old_connections()
