#! /usr/bin/env python
# -*- coding: utf-8 -*-
# create by oldman
# Date: 2019/4/23
import datetime
from django.core.management import BaseCommand
from gm_types.push import HERA_TASK_TYPE

from api.models import PushTask, get_rpc_remote_invoker
from hera.utils import get_mail_instance


class Command(BaseCommand):
    """
    监控push_task有没有执行
    python manage.py monitor_push_task
    """
    def handle(self, *args, **options):
        now_time = datetime.datetime.now()
        start_time = datetime.datetime(now_time.year,now_time.month,now_time.day)
        # now_time = datetime.datetime(2019,4,21)
        pushtasks = PushTask.objects.filter(eta__gte=start_time, eta__lte=now_time, approver__isnull=False)
        data = [pushtask.id for pushtask in pushtasks]
        print(data)
        raw = get_rpc_remote_invoker()['push2/push/user/get_push_info'](
            hera_push_task_ids=[x.id for x in pushtasks],
            task_type=HERA_TASK_TYPE.MESSAGE
        ).unwrap()
        print(raw)
        message_map = {x['hera_push_task_id']: x['msg_id'] for x in raw}
        res_not = [str(i) for i in data if i not in message_map ]
        res_yes = [str(i) for i in data if i  in message_map ]
        res_not_str, res_yes_str = u'', u''
        if res_yes:
            res_yes_str = u'\n'.join(res_yes) + u'有极光消息ID\n'
        if res_not:
            res_not_str = u'\n'.join(res_not) + u'没有有极光消息ID\n'
        print(res_not)
        print(res_yes)
        sub = u'运营后台推送状态检查'
        to_list = ['lipeng@igengmei.com', 'product@igengmei.com', 'libingxue@igengmei.com', 'liujingyi@igengmei.com', 'gaohuitian@igengmei.com']
        mail = get_mail_instance(sub, res_yes_str + res_not_str + u'请确认是否正常推送!', to_list)
        mail.send()

