# coding=utf-8
from datetime import datetime
from django.db import models

from gm_types.gaia import SERVICE_FLAG


class Lasker(models.Model):
    year = models.PositiveSmallIntegerField(unique=True, verbose_name=u"年度")
    name = models.CharField(max_length=64, verbose_name=u"奖项名称")

    create_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return "{}-{}".format(self.year, self.name)


class Award(models.Model):
    lasker = models.ForeignKey(Lasker, verbose_name=u"年度奖")
    name = models.CharField(max_length=64, verbose_name=u"奖项名称")
    laureate_type = models.SmallIntegerField(choices=SERVICE_FLAG, default=SERVICE_FLAG.DOCTOR,
                                             verbose_name=u'奖项者类型')
    image = models.CharField(max_length=128, verbose_name=u"图片")
    image_styled = models.CharField(max_length=128, verbose_name=u"被选中时的图片样式")

    create_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = (
            ('lasker', 'name'),
        )


class Participant(models.Model):
    doctor_id = models.CharField(max_length=64)
    award = models.ForeignKey(Award, related_name="participants", verbose_name="")

    create_at = models.DateTimeField(auto_now_add=True)
    votes_num = models.IntegerField(verbose_name="投票数", default=0)

    class Meta:
        unique_together = (
            ('doctor_id', 'award'),
        )


class Vote(models.Model):
    wx_uid = models.CharField(max_length=64)
    participant = models.ForeignKey(Participant, related_name="votes", verbose_name="")
    forged = models.BooleanField(default=False, verbose_name=u"虚假投票")

    create_at = models.DateTimeField(auto_now_add=True)

    @classmethod
    def has_vote_qualify(cls, wx_uid, participant_id):
        """

        :param wx_uid:
        :param participant_id:
        :return:
        """
        v = Vote.objects.filter(wx_uid=wx_uid, participant_id=participant_id).order_by('create_at').last()
        voted = v is not None and v.create_at.timetuple().tm_yday == datetime.now().timetuple().tm_yday
        return not voted


class AwardResult(models.Model):
    class Meta:
        verbose_name = u'获奖名单'
        verbose_name_plural = u'获奖名单'
        db_table = 'lasker_awardresult'
        app_label = 'lasker'

    laureate_id = models.CharField(max_length=100, verbose_name=u"获奖者id", db_index=True)
    laureate_name = models.CharField(max_length=64, verbose_name=u"获奖者名字")
    laureate_type = models.SmallIntegerField(choices=SERVICE_FLAG, default=SERVICE_FLAG.DOCTOR,
                                             verbose_name=u'获奖者类型')
    award_name = models.CharField(max_length=128, verbose_name=u"奖项名称")

    create_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)
    is_deleted = models.BooleanField(default=False, verbose_name=u"是否删除")