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

import datetime
import json
import traceback

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, sms_logger
from utils.execel import ExcelReader
from api.models import PushClickUser
from rpc.context import get_rpc_remote_invoker
from api.tasks.push_task import allocate_push_task_users
from community.views.doctor_care import doctor_care
from sms.utils.sms_mengwang import mw_batch_send_message, OweFeeException


@shared_task
def operative_care_sms():
    day = datetime.datetime.now().date()
    sms_logger.info('[SMS-operative_care] begin to process... at day(%s)' % str(day))
    excel_data_list = get_excel_data()
    sms_logger.info('[SMS-operative_care] get condition from excel: %s' % json.dumps(excel_data_list, ensure_ascii=False))
    send_mess_by_condition(excel_data_list)
    sms_logger.info('[SMS-operative_care] finish sending message at day(%s)' % str(day))



def get_excel_data():
    excel = ExcelReader("./postoperative_sms.xlsx")

    p_list = []
    cur_count = 0
    for row in range(excel.row_number):
        _row_data = excel.read_row(row)
        name = _row_data[0]

        tag_str = _row_data[1] or ''
        day = _row_data[2]
        sms_content = _row_data[6]
        try:
            tag_list = [int(x.strip()) for x in filter(None,tag_str.split(','))]
            if tag_list and str(day).isdigit() and sms_content:
                if not name and cur_count:
                    name = p_list[cur_count-1][0]
                p_list.append([name, tag_list, day, sms_content])
                cur_count += 1
        except:
            pass
    return p_list


def send_mess_by_condition(p_list):
    '''
    根据要发送的条件, 获取用户, 并发送短信
    '''
    for p in p_list:
        name, tag_list, day, content = p
        sms_logger.info('[SMS-postoperative_care]process category(%s) at day(%s), with content(%s)' % (name, day, content))
        order_user_ids = doctor_care(day=day, tag_ids=tag_list)
        # order_user_ids = [20893163, 20893334, 1631727]
        # order_user_ids = [1631727]
        exclude_user_ids = PushClickUser.get_user_ids()
        des_order_user_ids = list(set(order_user_ids) - set(exclude_user_ids))
        try:
            send_mess_to_user_ids(des_order_user_ids, content)
        except OweFeeException as e:
            sms_logger.warn('[SMS-postoperative_care] finished category(%s) at day(%s) owe fee, stopped!!! ' % (name, day))
            break
        except Exception as e:
            sms_logger.warn('[SMS-postoperative_cate] finished category(%s) at day(%s) failed for reason: %s' % (name, day, traceback.format_exc()))
        else:
            sms_logger.info('[SMS-postoperative_cate] finished category(%s) at day(%s) successfully' % (name, day))


def send_mess_to_user_ids(user_ids, mess_content):
    '''
    根据user_ids发送短信
    '''

    from api.util.user_util import get_phone_by_user_ids

    user_phone_map = get_phone_by_user_ids(user_ids)
    phone_list = user_phone_map.values()
    phone_list = list(set(phone_list))

    mw_batch_send_message(phone_list, mess_content)
