#! -*- encoding:utf-8 -*-

from django.core.management import BaseCommand

from gm_types.push import PUSH_INFO_TYPE, AUTOMATED_PUSH

from rpc.tool.log_tool import logging_exception
from utils.execel import ExcelReader
from api.models import Notification
from rpc.context import get_rpc_remote_invoker
from api.tasks.push_task import allocate_push_task_users


def push2users(users_push):

    for push in users_push:
        extra = {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'msgType': 4,
            'pushUrl': push["push_url"],
            'push_url': push["push_url"],
        }
        try:
            Notification.objects.create(
                title=push["push_title"],
                user_id=push["user_id"],
                content=push["push_msg"],
                url=push["push_url"],
                is_viewed=False,
            )
        except Exception as e:
            print("create, user_id: {}, error: {}".format(push["user_id"], e))
            logging_exception()

        try:
            data = allocate_push_task_users(
                user_id=int(push["user_id"]),
                alert=push["push_msg"],
                extra=extra,
                push_type=AUTOMATED_PUSH.OPERATION_TRACTATE
            )
            print("user_id: {}, msg_id: {}".format(push["user_id"], data.get("msg_id", "")))
        except Exception as e:
            print("push, user_id: {}, error: {}".format(push["user_id"], e))
            logging_exception()

class Command(BaseCommand):

    def handle(self, *args, **options):

        excel = ExcelReader("/tmp/push2special_person.xlsx")

        users_push = []
        push_url = ""
        push_msg = ""
        push_title = ""
        for row in range(excel.row_number):
            data = excel.read_row(row)
            user_id = data[0]
            push_title = data[1]
            push_msg = data[2]
            push_url = data[3]
            if not all([user_id, push_msg, push_title, push_url]) :
                continue

            users_push.append({
                "user_id": user_id,
                "push_url": push_url,
                "push_title": push_title,
                "push_msg": push_msg,
            })

        push2users(users_push)
