# coding=utf-8
import uuid

from django.core.management import BaseCommand
from django.db import transaction
from gm_types.gaia import DOCTOR_TYPE

from hippo.models import Doctor
from lasker.models import Participant, Vote


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('doctor_id', help=u"医生或者机构管理者ID")
        parser.add_argument('participant_id', type=int, help=u"")
        parser.add_argument('votes_num', type=int, help=u"增加的票数")

    def handle(self, *args, **options):
        doctor_id = options['doctor_id']
        participant_id = options['participant_id']
        votes_num = options['votes_num']
        doctor = Doctor.objects.filter(id=doctor_id).first()
        if not doctor:
            self.stdout.write(self.style.ERROR(u'ID 为 {} 的医生或者机构管理者不存在!'.format(doctor_id)))
            return
        with transaction.atomic():
            participant = Participant.objects.select_for_update().filter(id=participant_id).first()
            if not participant:
                self.stdout.write(self.style.ERROR(u'该医生或者机构管理者未参此奖项评比!'))
                return
            if doctor.doctor_type == DOCTOR_TYPE.DOCTOR:
                self.stdout.write(self.style.NOTICE(u'ID 为 {} 查询到是普通医生, 用户名为 {}'.format(doctor_id, doctor.name)))
            else:
                self.stdout.write(self.style.NOTICE(u'ID 为 {} 查询到是机构管理者, 用户名为 {}'.format(doctor_id, doctor.name)))

            self.stdout.write(self.style.NOTICE(u'此项目名为 {}'.format(participant.award.name)))
            self.stdout.write(self.style.NOTICE(u'此项目现在票数为 {}'.format(participant.votes_num)))
            self.stdout.write(self.style.NOTICE(u'正在进行加票操作....'))
            wx_uid = uuid.uuid4().hex
            insert_vote_list = [Vote(participant_id=participant_id, wx_uid=wx_uid, forged=True) for _ in range(votes_num)]
            participant.votes_num += votes_num
            participant.save()
            Vote.objects.bulk_create(insert_vote_list)

        self.stdout.write(self.style.NOTICE('END'))
