#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals, absolute_import

import datetime

from django.db import models
from django.db.models import Q

from gm_types.gaia import AGREEMENT_TYPE

from .doctor import Doctor


class AgreementManger(models.Manager):
    def get_valid_agreement(self, send_time=None, doctor=None):
        if send_time is None:
            send_time = datetime.datetime.now()
        query = Q(status=AGREEMENT_TYPE.IS_ONLINE)
        if doctor and doctor.created_at:
            # 保证只返回 在医生创建后产生的协议
            query &= Q(send_time__range=(doctor.created_at, send_time))
        else:
            query &= Q(send_time__lte=send_time)
        return self.filter(query)


class Agreement(models.Model):
    class Meta:
        verbose_name = u'强制签协议'
        verbose_name_plural = u'强制签协议'
        db_table = 'api_agreement'
        app_label = 'api'

    title = models.CharField(verbose_name=u'标题', max_length=128, default='')
    content = models.TextField(verbose_name=u'协议内容', default='')
    send_time = models.DateTimeField(verbose_name=u'发送时间', null=True)
    status = models.IntegerField(verbose_name=u"是否上线", default=AGREEMENT_TYPE.DEFAULT,
                                 choices=AGREEMENT_TYPE, null=False)
    create_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)

    objects = AgreementManger()

    @property
    def vaild_agreement(self):
        return self.staus == AGREEMENT_TYPE.IS_ONLINE and datetime.datetime.now() <= self.send_time

    @property
    def can_recall(self):
        return self.status == AGREEMENT_TYPE.IS_ONLINE and datetime.datetime.now() > self.send_time


class AgreementDoctor(models.Model):
    class Meta:
        verbose_name = u'签订强制协议的医生记录'
        verbose_name_plural = u'签订强制协议的医生记录'
        db_table = 'api_agreement_doctor'
        app_label = 'api'

        unique_together = (("agreement", "doctor"),)

    agreement = models.ForeignKey(Agreement)
    doctor = models.ForeignKey(Doctor)
    create_time = models.DateTimeField(verbose_name=u'同意协议时间', auto_now_add=True)
