#! -*- encoding:utf-8 -*-
# 私信推送问卷调查
from django.core.management import BaseCommand
import os
import sys
 
import logging
import json

from gm_types.push import AUTOMATED_PUSH
from api.models import Conversation, Message, User, Order
from rpc.context import get_rpc_remote_invoker
from django.db.models import Q
from message.utils.push_service import build_user_push_extra
from gm_types.msg import CONVERSATION_TYPE, MESSAGE_TYPE
from message.utils.db import write_msg_to_es
from django.utils import timezone
from message import signals as message_signals
from django.conf import settings
rpc_invoker = get_rpc_remote_invoker()

log_file = 'push_info.log'
#    logging config
logger = logging.getLogger(__name__)
handler = logging.FileHandler(log_file)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] [%(levelname)s] %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# <<<<<<<<<<<<<<<<<<<<<< config field =========================
# 通知栏消息提醒
alert_text = '所长想更深入地了解我的小可爱们，有奖问答→'
# 私信文案
content = {'text': u'为了让我们更好地了解您对变美的需求，并提供更优质的服务，请您耐心、如实回答。 戳此链接：  https://www.wjx.cn/jq/26387256.aspx       回答完成后，请联系「更美小队长」微信号（gmeidr），发送「更美用户名+问卷」，领取限量现金红包奖励和多份玻尿酸、护手霜、面膜抽奖机会！',
 'url': 'gengmei://common_webview?url=https://www.wjx.cn/jq/26387256.aspx'}  # 站长id
sender_id = 22
# 开始处理下标

user_file = 'user_id.record'
# begin_day
begin_day = '2017-07-25'
# end_day
end_day = '2018-07-25'
# ====================== config field >>>>>>>>>>>>>>>>>>>>>>>>




#    config process 
msg_type = MESSAGE_TYPE.TEXT_WITH_URL
body = json.dumps(content, ensure_ascii=False)
pure_content = content.get('text')
send_user = User.objects.get(id=sender_id)
msg = {
	    'user_id': send_user.id,
	    'type': msg_type,
	    'content': content,
	}


# ==========================  获取推送user_ids ===========================

def get_user_id_from_db():
    logger.info('[db]get user_ids from db')
    all_ids = list(Order.objects.filter(created_time__gte = begin_day, created_time__lte = end_day).values_list('user_id', flat=True).distinct())
    logger.info('[db] get total %s user_id' % len(all_ids))
    return all_ids



# ========================= 分批次处理 ===========================

def push_user_ids(user_ids):
    send_time = timezone.now().replace(microsecond=0)
    msg.update({'send_time': send_time})
    try:
        for user_id in user_ids:
            conversation = Conversation.objects.get_conversation(sender_id, user_id, conversation=CONVERSATION_TYPE.MESSAGE)
            logger.info('conversation_id:%s' % conversation.id)
            message = conversation.send_message(user=send_user, type_=msg_type, content=pure_content, body=body)
            msg_id = message.id
            logger.info('msg_id: %s' % msg_id)
            msg.update({'id': msg_id})
            extras = build_user_push_extra(msg_id, conversation_type=CONVERSATION_TYPE.MESSAGE, user_ids=conversation.user_ids())
            es_res = write_msg_to_es(msg_id=msg_id, user_id=send_user.id, conversation_id = conversation.id, conversation_extra={'conversation_type':CONVERSATION_TYPE.MESSAGE}, send_time=send_time, msg=msg)
            message_signals.post_send_message(conversation=conversation)
            rpc_invoker['push2/push/user/automated_push/uids'](user_ids=[user_id], push_type=AUTOMATED_PUSH.RECEIVED_A_PRIVATE_MESSAGE, alert=alert_text, extra=extras).unwrap()
    except:
        import traceback
        logger.error(traceback.format_exc())
        logger.error('failed for this batch push')


    
class Command(BaseCommand):
    
    def main(self):
        user_ids = []
        file_list = os.listdir('.')
        if user_file not in file_list:
            user_ids = get_user_id_from_db()
            with open(user_file, 'w') as file:
                json.dump(user_ids, file, ensure_ascii = False)
            logger.info('write user_id result in file[%s]' % user_file)

        if not user_ids:
            with open(user_file) as file:
                user_ids = json.load(file)
            logger.info('get user_ids from file[%s]' % user_file)

        length = len(user_ids)
        r_end = self.end
        step = self.step
        if not r_end or r_end > length:
            r_end = length
        for i in range(self.start, r_end, step):
            ids = user_ids[i:min(i+step, r_end)]
            logger.info('push ids from %s to %s:\n %s' % (i, min(i+step, r_end), ids))
            push_user_ids(ids)
        logger.info('push user_ids total from %s to %s' % (self.start, r_end))

    def add_arguments(self, parser):
        parser.add_argument('-c', dest='clear', action='store_true', default=False, help='clear the record file')
        parser.add_argument('-b', type=int, dest='head', action='store', default=0, help='head point')
        parser.add_argument('-t', type=int, dest='tail', action='store', default=0, help='tail point')
        parser.add_argument('-l', dest='clog', action='store_true', default=False, help='clear log')
        parser.add_argument('-s', dest='step', type=int, default=100, action='store', help='process step')
        parser.add_argument('-p', dest='run', action='store_true', default=False, help='run push')

    def handle(self, *args, **options):
        self.run = True
        if options['clear']:
            self.run = False
            if os.path.exists(user_file):
                os.remove(user_file)
                print('remove %s successfully' % user_file)
            else:
                print('file[%s] not exists, go on !' % user_file)
        if options['clog']:
            self.run = False
            if os.path.exists(log_file):
                os.remove(log_file)
                print('remove file [%s] successfully' % log_file)
            else:
                print('log_file[%s] not exists, go on!' % log_file)
        if options['run']:
            self.run = True
        self.start = options['head']
        self.end = options['tail']
        self.step = options['step']
        if self.run:
            self.main()
