# coding=utf-8
import datetime

from gm_types.gaia import PUNISHMENT_TYPE_FULL

from api.models import Punishment, PvPunishmentRecord
from api.models.tickets import end_of_today

from hippo.models.merchant import Merchant

from rpc.decorators import bind


@bind('api/punish/diary')
def get_punishment_diary(diary_doctor_info=None):
    """
    日记本相关的医生是否在罚单中
    :param diary_doctor_info:[{'diary_id': xx, 'doctor_id':xx}]
    :return:
    """
    def is_punish_doctor(diary_doctor_info):
        if diary_doctor_info.get('doctor_id'):
            now = datetime.datetime.now()
            return Punishment.objects.filter(start_time__lt=now, end_time__gt=now, enable=True, doctor_id=diary_doctor_info['doctor_id'])
        return False

    re_list = list(filter(is_punish_doctor, diary_doctor_info))
    return [item['diary_id'] for item in re_list]


@bind('api/punishment/create_by_pvlimit')
def create_by_pvlimit(merchant_id, punish_object, date):
    today = datetime.date.today()
    if str(today) != date:
        return
    now = datetime.datetime.now()
    merchant = Merchant.objects.filter(id=merchant_id).first()
    if not (merchant and merchant.doctor_id):
        return
    punishment = Punishment.objects.filter(
        target=punish_object,
        doctor_id=merchant.doctor_id,
        end_time__gt=now,
        punish_type=PUNISHMENT_TYPE_FULL.PV,
        enable=True
    ).order_by('-id').first()
    if not punishment:
        return
    defaults = {'pv_limit': punishment.pv_limit}
    pv, created = PvPunishmentRecord.objects.get_or_create(
        defaults=defaults,
        end_time=end_of_today(),
        punishment=punishment
    )
