# coding:utf-8

"""投票数据、邀请导出"""

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from django.core.management import BaseCommand, CommandError
from django.conf import settings
from django.db.models import Q

from utils.execel import ExcelWriter
from api.models.variety_vote import UserVoteLog, VarietyVoteLog


class Command(BaseCommand):
    """
    导出投票记录
    python manage.py export_vote_data
    """

    def add_arguments(self, parser):
        parser.add_argument('-t', '--type', dest='export_type', type=str)
        parser.add_argument('-a', '--activity_id', dest='activity_id', type=int)
        parser.add_argument('-i', '--idol_id', dest='idol_id', type=int)

    def handle(self, *args, **options):

        export_type = options.get('export_type')
        if export_type not in ["vote_num", "vote_log"]:
            raise CommandError("导出类型错误，只能是：vote_num或者vote_log")

        if export_type == "vote_num":
            self.export_vote_num(*args, **options)

        elif export_type == "vote_log":
            self.export_vote_log(*args, **options)

    def export_vote_num(self, *args, **options):

        user_id = options.get('user_id')
        activity_id = options.get('activity_id')

        if not activity_id:
            raise CommandError("必须存在活动id")

        excel = ExcelWriter("vote_num.xlsx")
        excel.write_header(["activity_id", "user_id", "user_name", "time", "change_type", "phone", "vote_num",
                            "register_time"])

        query = Q(activity_id=activity_id)
        if user_id:
            query &= Q(user_id=user_id)

        logs = UserVoteLog.objects.using(settings.SLAVE_DB_NAME).filter(query).order_by("-create_time")

        print(len(logs))

        num = 2
        for log in logs:
            excel.write_row(row_num=num, values=[log.activity_id, log.user_id, log.user.last_name, log.create_time,
                                                 log.change_type, log.user.userextra.phone or '',
                                                 log.vote_num, log.user.date_joined])
            num += 1

        excel.save()

    def export_vote_log(self, *args, **options):
        activity_id = options.get('activity_id')
        idol_id = options.get('idol_id')

        if not activity_id:
            raise CommandError("必须存在活动id")

        excel = ExcelWriter("vote_log.xlsx")
        excel.write_header(["activity_id", "idol", "user_id", "user_name", "time", "phone",
                            "vote_num", "register_time"])

        query = Q(activity_id=activity_id)
        if idol_id:
            query &= Q(idol_id=idol_id)
        logs = VarietyVoteLog.objects.using(settings.SLAVE_DB_NAME).filter(query).\
            order_by("-create_time")

        print(len(logs))

        num = 2
        for log in logs:
            excel.write_row(row_num=num, values=[log.activity_id, log.idol.nick_name, log.voter_id,
                                                 log.voter.last_name, log.create_time, log.voter.userextra.phone or '',
                                                 log.vote_num, log.voter.date_joined])
            num += 1

        excel.save()


