# coding=utf8
from __future__ import absolute_import, unicode_literals

from django.db.models import Q

from rpc.decorators import bind, bind_context
from rpc.context import get_rpc_remote_invoker
from rpc.tool.log_tool import logging_exception

from message.utils.push_service import push_message_user_multi
from api.models import Person, Doctor, Order
from api.tool.user_tool import get_user_from_context

from maidan.models.order import MaidanOrder
from sms.utils.smsfactory import send_sms
from gm_types.gaia import PLATFORM_CHOICES
from gm_types.push import PUSH_INFO_TYPE


@bind('push/push/user_notification/uids')
def user_noti_uids(user_ids, platform=None, alert='', extra=None, push_time=None,
                   urgency=None):
    """用户版极光推送临时实现
    目前不实现push_time和urgency
    """
    if platform is None:
        platform = [PLATFORM_CHOICES.IPHONE, PLATFORM_CHOICES.ANDROID]

    if push_time is not None:
        raise NotImplementedError
    if urgency is not None:
        raise NotImplementedError

    push_message_user_multi(
                            user_ids=user_ids,
                            platform=platform,
                            alert=alert,
                            extra=extra)


# 检查此接口是否还在使用中
@bind('push/push/user_notification/person_ids')
def user_noti_person_ids(person_ids, platform=None, alert='', extra=None, push_time=None,
                         urgency=None, silent=True):
    """用户版极光推送临时实现
    目前不实现push_time和urgency
    """
    if push_time is not None:
        raise NotImplementedError
    if urgency is not None:
        raise NotImplementedError

    user_ids = list(Person.objects.filter(pk__in=person_ids).values_list('user_id', flat=True))

    push_message_user_multi(
                            user_ids=user_ids,
                            platform=platform,
                            alert=alert,
                            extra=extra,
                            silent=silent
    )


@bind('push/push/user_message/person_ids')
def user_msg_person_ids(person_ids, platform=None, msg_content='', extra=None, push_time=None,
                        urgency=None):
    if platform is None:
        platform = [PLATFORM_CHOICES.IPHONE, PLATFORM_CHOICES.ANDROID]

    if push_time is not None:
        raise NotImplementedError
    if urgency is not None:
        raise NotImplementedError

    user_ids = list(Person.objects.filter(pk__in=person_ids).values_list('user_id', flat=True))

    push_message_user_multi(
                            user_ids=user_ids,
                            platform=platform,
                            msg_content=msg_content,
                            extra=extra)


@bind('push/installment/renmai/notify')
def renmai_audit_push(grant, period, period_price, phone, order_id='', settlement_id=''):
    assert order_id or settlement_id

    if str(order_id).startswith('md_'):
        order = MaidanOrder.objects.get(pk=order_id[3:])
        push_url = 'gengmei://my_maidan'
    else:
        q = Q(id=order_id) if order_id else Q(settlementitem__settlement_id=settlement_id)
        order = Order.objects.get(q)
        push_url = 'gengmei://order_list'

    if grant:
        push_msg = u'您的美购订单{}申请分期审核成功！'\
            '共分{}期，每期还款{}元。点击查看详情。'\
            .format(order_id, period, period_price)
        sms_templete_id = 30
        sms_params = [
            {'number': period},
            {'order_id': order_id},
            {'money': period_price},
        ]
    else:
        push_msg = u'【更美APP】您的美购订单{}，因资金方申请分期失败，'\
            '该订单仍可到店支付尾款后正常使用。'.format(order_id)
        sms_templete_id = 31
        sms_params = [{'order_id': order_id}]

    send_sms(phone, sms_templete_id, sms_params)
    push_message_user_multi(
        user_ids=[order.user.id],
        platform=[PLATFORM_CHOICES.IPHONE, PLATFORM_CHOICES.ANDROID],
        alert=push_msg,
        extra={'type': PUSH_INFO_TYPE.GM_PROTOCOL, 'pushUrl': push_url},
    )


def doctor_noti_doctor_ids(
        doctor_ids, platform=None, alert='', extra=None, push_time=None, urgency=None):
    """医生版极光推送临时实现
    目前不实现push_time和urgency
    """
    rpc_invoker = get_rpc_remote_invoker()
    try:
        rpc_invoker['push2/push/doctor/notification/doctor_ids'](
            doctor_ids=doctor_ids,
            platform=platform,
            extra=extra,
            alert=alert,
        ).unwrap()
    except Exception as e:
        logging_exception()