# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function


"""
事件监听
"""
from django.db.models import Q

from rpc.decorators import bind_context
from gm_types.push import PUSH_STAT_CATEGORY

from api.tasks.push_task import query_push_task
from api.tasks import push_task
from api.models import ServiceReserve
from api.models import Order


@bind_context("api/event/service/start_sale")
def service_start_sale(ctx,platform=None, service_id=None, extra=None, alert='', title=''):
    """福利上架开卖监听事件

    事件: 当有福利上架后，向已预定用户发送通知
    :param service_id: 上架福利id
    :return:
    """
    if platform is None or service_id is None:
        return

    labels = {
        'push_stat_category':PUSH_STAT_CATEGORY.SERVICE_START_SALE,
    }

    push_content = '你预定的美购{}已经上架啦，快去购买吧'.format(alert)


    query = Q(servicereserve__service_id=service_id, servicereserve__stat='1')  # TODO Do not use hard code
    query_push_task(platform=platform, query=query, extra=extra, alert=push_content, labels=labels)

    for service_reserve in ServiceReserve.objects.filter(service_id=service_id):
        order_item = Order.objects.filter(Q(service_id=service_reserve.service_id) & Q(user_id=service_reserve.user_id)).first()
        if order_item is not None:
            service_reserve.stat = '9' # TODO Do not use hard code
            service_reserve.save()

    push_task.query_send_notification.delay(query, title=title, content=push_content, url=extra['pushUrl'])
    push_task.query_send_sms.delay(query, service_id, alert)