# coding=utf-8
# create by oldman at 2017/11/21
import datetime
from celery import shared_task
from gm_types.doctor import DOCTOR_MESSAGE_TYPE

from api.models import Service
from doctor.views.budan import get_all_doctors, statistic_current_month_info
from hippo.models import Doctor, DoctorMessage
from hippo.models import MESSAGE_TYPE_CONTENT
from hippo.models import Merchant
from hippo.utils import get_merchant


@shared_task
def budan_message():
    """
    补单未补的消息通知
    :return:
    """
    doctors = Doctor.objects.filter(is_merchant=True)
    time = datetime.datetime.now()
    # 防止celery异常多次发送消息，只在28号发送
    if time.day == 28:
        for doctor in doctors:
            try:
                doctor_ids, user_ids = get_all_doctors(doctor)
                result = statistic_current_month_info(doctor, doctor_ids, user_ids)
                if result['need_pay'] > 0:
                    merchant = get_merchant(doctor.id)
                    info = {
                        'type': DOCTOR_MESSAGE_TYPE.BUDAN,
                        'doctor_id': doctor.id,
                        'merchant_id': merchant.id,
                    }
                    message_info = [result['need_pay']]
                    DoctorMessage.add_message(info, *message_info)
            except Exception:
                continue
    else:
        pass


@shared_task
def service_expiry_remind():
    """
    美购到期提醒
    :return:
    """
    start_time = datetime.datetime.now() + datetime.timedelta(days=2)
    end_time = datetime.datetime.now() + datetime.timedelta(days=3)

    services = Service.objects.filter(end_time__gt=start_time, end_time__lte=end_time)
    for service in services:
        try:
            info = {
                'type': DOCTOR_MESSAGE_TYPE.SERVICE_EXPIRE,
                'info_id': service.servicereg.all()[0].id,
                'doctor_id': service.doctor.id,
            }
            merchant = get_merchant(service.doctor.id)
            if merchant:
                info['merchant_id'] = merchant.id
            message_info = service.name
            DoctorMessage.add_message(info, message_info)
        except Exception as e:
            print e
            continue
