#!/usr/bin/env python
# -*- coding: utf-8 -*-

import math
import time
import queue
from multiprocessing import Pool, Manager

from concurrent.futures import ThreadPoolExecutor
from django.core.management.base import BaseCommand
from django.db.models import Q, Max
from gm_types.gaia import CONST_STRINGS as const_strings

from settings import settings
from talos.models.topic.topic import Problem
from talos.models.topic.topicvote import TopicVote
from qa.cache import ViewRecord

topic_queue = queue.Queue()
max_topic_info = Problem.objects.using(settings.SLAVE_DB_NAME).order_by("id").last()


def handle_topic(topic_queue):
    last_topic_id = topic_queue.get()

    if max_topic_info.id <= last_topic_id:
        topic_queue.put(last_topic_id)
        return

    print("last_topic_id=======", last_topic_id, max_topic_info.id)
    per_num = 500

    topics = Problem.objects.using(settings.SLAVE_DB_NAME).filter(id__gt=last_topic_id).order_by('id')[:per_num]

    max_id = topics.aggregate(max_id=Max('id'))
    topic_queue.put(max_id.get('max_id'))

    for topic in topics:

        topic_count = TopicVote.objects.using(settings.SLAVE_DB_NAME).filter(topic_id=topic.id).count()
        topic.new_vote_num = topic_count * 7
        if topic_count > 0:
            view = ViewRecord(Problem.get_redis_vote_key())
            view[topic.id] = topic.new_vote_num
            topic.save()

    return


def update_topic_vote():
    all_count = Problem.objects.using(settings.SLAVE_DB_NAME).all().order_by('id').count()
    topic_queue.put(0)  # 触发程序开始

    per_num = 500
    cnt = math.ceil(float(all_count) / per_num)
    #handle_topic(topic_queue)
    with ThreadPoolExecutor(max_workers=4) as ex:
        for i in range(cnt):
            ex.submit(handle_topic, topic_queue)


class Command(BaseCommand):

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

        print("BEGIN")
        start_time = time.time()
        print("start at: ", start_time)

        update_topic_vote()

        end_time = time.time()
        print("end at: ", end_time)
        print('total use {} s.'.format(end_time - start_time))
        print("END")
