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

from gm_types.gaia import SERVICE_FLAG
from gm_types.gaia import DOCTOR_TYPE

from rpc.cache import doctor_badge_cache


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"是否删除")
    online_time = models.DateTimeField(verbose_name="上线时间")
    offline_time = models.DateTimeField(verbose_name="下线时间")
    is_special_skin = models.IntegerField(verbose_name="是否有特殊皮肤")

    @classmethod
    def get_award_result_with_laureate_id(cls, laureate_id, doctor_type=None):
        # 获取医院或者医生 名医大赏荣誉和是否有特殊皮肤
        award_name = doctor_badge_cache.get(laureate_id)
        is_special_skin_cache_key = "{laureate_id}_is_special_skin".format(laureate_id=laureate_id)
        is_special_skin = doctor_badge_cache.get(is_special_skin_cache_key)
        if award_name is None or not json.loads(award_name) or is_special_skin is None:
            now_time = datetime.now()
            laureate_type = SERVICE_FLAG.DOCTOR \
                if doctor_type is not None and doctor_type == DOCTOR_TYPE.DOCTOR \
                else SERVICE_FLAG.HOSPITAL
            result = AwardResult.objects.filter(
                laureate_id=laureate_id,
                is_deleted=False,
                laureate_type=laureate_type,
                online_time__lt=now_time,
                offline_time__gt=now_time,
            ).first()
            if result and result.award_name:
                award_name = json.dumps(result.award_name.split(','))
                is_special_skin = result.is_special_skin
            else:
                award_name = json.dumps([])
                is_special_skin = 0
            ex = 24 * 60 * 60
            doctor_badge_cache.set(laureate_id, award_name, ex=ex)
            doctor_badge_cache.set(is_special_skin_cache_key, is_special_skin, ex=ex)
        return json.loads(award_name), int(is_special_skin)
