# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

import datetime

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

from .topic import Problem
from talos.services.user import UserService
from talos.services.doctor import DoctorService


class VotePK(models.Model):
    class Meta:
        verbose_name = u'投票活动'
        db_table = 'api_votepk'
        app_label = 'talos'

    topic = models.ForeignKey(Problem, verbose_name=u'pk关联帖子', related_name='vote_record')
    person_id = models.CharField(verbose_name=u'用户外键id', max_length=64)
    vote_date = models.DateField(verbose_name=u'投票时间', auto_now_add=True)
    vote_doctor_id = models.CharField(max_length=100, verbose_name=u'支持的医生')
    vote_user_id = models.IntegerField()

    @classmethod
    def vote_info(cls, topic=None, doctors_id=None, users_id=None, user=None):
        voted_info = {}
        voted_data = VotePK.objects.filter(topic=topic)
        if users_id:
            objs = UserService.get_users_by_user_ids(users_id)

        elif doctors_id:
            objs = DoctorService.get_doctor_from_doctor_ids(doctors_id)
            objs = {o.id: o for o in objs}

        else:
            return {}

        for k in objs:
            obj = objs[k]
            if users_id:
                obj_id = obj.id
                obj_portrait = ''
                obj_name = obj.nickname
                filter_obj = Q(vote_user_id=obj.id)
            else:
                obj_id = obj.id
                obj_portrait = obj.portrait
                obj_name = obj.name
                filter_obj = Q(vote_doctor_id=obj.id)

            voted_info[obj_id] = {
                'id': obj_id,
                'portrait': obj_portrait,
                'name': obj_name
            }

            vote_num = voted_data.filter(filter_obj).count()
            voted = (
                False
                if not user
                else voted_data.filter(
                    filter_obj,
                    person_id=user.person_id,
                    vote_date=datetime.date.today()
                ).exists()
            )
            support_rate = (
                '%.2f' % (
                    voted_data.filter(
                        filter_obj
                    ).count() * 1.0 / voted_data.count() * 100
                )
                if voted_data.count()
                else 0
            )
            voted_info[obj_id].update(
                {
                    'vote_num': vote_num,
                    'support_rate': support_rate,
                    'voted': voted,
                }
            )
        return voted_info
