# coding=utf8
from __future__ import unicode_literals, absolute_import, print_function

from datetime import datetime

from django.db import models

from api.models import Person, User


class RecommendDoctor(models.Model):
    class Meta:
        verbose_name = u'推荐医生'
        verbose_name_plural = u'推荐医生'
        db_table = 'api_recommend_doctor'
        app_label = 'api'

    person = models.ForeignKey(Person)
    diary_id = models.IntegerField(null=True, blank=True)  # TODO related_name='recommend_doctor',

    # TODO 下面的字段基本没什么卵用 2016.3.18
    raw_doctor = models.TextField(verbose_name=u'专家名称', blank=True, default='', max_length=200)
    raw_hospital = models.TextField(verbose_name=u'机构名称', blank=True, default='', max_length=200)
    item_name = models.CharField(u'项目名称', max_length=30)
    recommend_time = models.DateTimeField(verbose_name=u'推荐时间', auto_now_add=True)
    connected = models.BooleanField(verbose_name=u"已联系", default=False, db_index=True)


class StockAlert(models.Model):

    class Meta:
        verbose_name = u'缺货提醒'
        db_table = 'api_stock_alert'
        app_label = 'api'

    diary_id = models.IntegerField()  #TODO related_name='diary'
    business_partener = models.ForeignKey(User, related_name='business_partener+')
    appointment = models.IntegerField(default=1)
    doctor = models.CharField(u'专家名称', max_length=50)
    hospital = models.CharField(u'机构名称', max_length=100)
    item_name = models.CharField(u'项目名称', max_length=30)
    phone = models.CharField(u'手机', max_length=30, null=True)
    note = models.TextField(verbose_name=u'备注', null=True, max_length=200)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now_add=True)

    @classmethod
    def insert(cls, recommend_doctor):
        diary_id = recommend_doctor.diary_id
        defaults = {
            'doctor': recommend_doctor.raw_doctor,
            'hospital': recommend_doctor.raw_hospital,
            'item_name': recommend_doctor.item_name,
        }
        obj, created = cls.objects.get_or_create(diary_id=diary_id,
                                                 defaults=defaults)
        if not created:
            obj.appointment += 1
            obj.update_time = datetime.now()
            obj.save()
        return obj
