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

from celery import shared_task
from gm_types.push import PUSH_INFO_TYPE, AUTOMATED_PUSH
from gm_protocol import GmProtocol

from rpc.tool.log_tool import logging_exception, user_push_logger
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
from api.tasks.postoperative_sms import operative_care_sms
from community.views.doctor_care import doctor_care


def push2users(user_ids, push_url, push_title, push_msg):

    step = 10
    user_ids_list = [user_ids[i:i + step] for i in range(0, len(user_ids), step)]
    for user_list in user_ids_list:
        extra = {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'msgType': 4,
            'pushUrl': push_url,
            'push_url': push_url,
        }
        try:
            Notification.objects.bulk_create([
                Notification(
                    title=push_title,
                    user_id=user_id,
                    content=push_msg,
                    url=push_url,
                    is_viewed=False,
                )
                for user_id in user_list
            ])
        except Exception as e:
            logging_exception()

        try:
            data = allocate_push_task_users(
                user_id=user_list,
                alert=push_msg,
                extra=extra,
                push_type=AUTOMATED_PUSH.OPERATION_TRACTATE
            )
            user_push_logger.info("user_list: {}, msg: {}".format(user_list, data))
        except Exception as e:
            user_push_logger.info("user_list: {}, err: {}".format(user_list, e))
            logging_exception()


@shared_task
def push2special_user():

    excel = ExcelReader("./push2special.xlsx")

    for row in range(excel.row_number):
        data = excel.read_row(row)

        tag_ids = [int(i.strip()) for i in str(data[0]).split(',') if i.strip()]
        day = data[1]

        # 获取用户列表
        user_ids = doctor_care(day=day, tag_ids=tag_ids)
        push_title = data[2]
        push_msg = data[3]
        push_id = data[4]

        if not all([user_ids, push_msg, push_title, push_id]) :
            continue

        push_url = GmProtocol().get_tractate_detail(tractate_id=push_id)
        push2users(user_ids=user_ids, push_url=push_url,
                   push_title=push_title, push_msg=push_msg)
    countdown = 5 * 60 * 60
    operative_care_sms.apply_async(args=(), countdown=countdown)
