# coding=utf-8
from django.conf import settings

from celery import shared_task
from api.models.doctor import Doctor
from api.models.hospital import Hospital
from api.models.order import Order
from api.models.types import PRIVATE_MESSAGE_PUSH_STATUS
from api.models.types import MESSAGE_TYPE
from message.utils.message import send_one_message
from api.tool.user_tool import get_user_by_id
from api.models.message import PrivateMessagePush
from api.models import User
from gm_types.msg import CONVERSATION_TYPE


@shared_task
def send_private_message_ontime(message_id):
    """
    私信推送
    """
    # 只有通过审核的私信才可以发送
    try:
        message = PrivateMessagePush.objects.get(id=message_id)
    except PrivateMessagePush.DoesNotExist:
        return

    if message.status != PRIVATE_MESSAGE_PUSH_STATUS.OK:
        return

    if not message.content:
        return

    orders = []
    send_user = get_user_by_id(settings.BOSS)
    user_list = []

    if message.service_id:
        orders = Order.objects.filter(service_id=message.service_id)
    elif message.doctor_id:
        try:
            doctor = Doctor.objects.get(id=message.doctor_id)
        except Doctor.DoesNotExist:
            return

        service_ids = [item.id for item in doctor.services.all()]
        if service_ids:
            orders = Order.objects.filter(service_id__in=service_ids)
    elif message.hospital_id:
        try:
            hospital = Hospital.objects.get(id=message.hospital_id)
        except Hospital.DoesNotExists:
            return

        doctors = Doctor.objects.filter(hospital=hospital)
        service_ids = set()
        for doctor in doctors:
            for item in doctor.services.all():
                service_ids.add(item.id)

        if service_ids:
            orders = Order.objects.filter(service_id__in=list(service_ids))
    elif message.user_list:
        for user_id in message.user_list.split('\n'):
            send_user_id = filter(str.isdigit, str(user_id))
            if send_user_id:
                user_list.append(send_user_id)

    if orders:
        order_status = message.order_status.split(',') if message.order_status != '' else None
        if order_status:
            orders = orders.filter(status__in=order_status)
        user_list = list(orders.values_list('user_id', flat=True))

    if message.url:
        content = {'text': message.content, 'url': '{}{}'.format('gengmei://common_webview?url=', message.url)}
        msg_type = MESSAGE_TYPE.TEXT_WITH_URL
    else:
        content = {'text': message.content}
        msg_type = MESSAGE_TYPE.TEXT

    for user_id in set(user_list):
        try:
            target_user = User.objects.get(id=user_id)
            send_one_message(send_user, target_user=target_user, conversation=None,
                             conversation_type=CONVERSATION_TYPE.MESSAGE,
                             msg_type=msg_type, push_stat_labels={'event_type':'push', 'event':'received_private_msg'},
                             content=content)
        except:
            continue
