# coding=utf-8
import threading
import Queue
import datetime
from multiprocessing import cpu_count

from django.core.management import BaseCommand

from api.models import Message
from gm_types.gaia import MESSAGE_TYPE

g_queue = Queue.Queue(maxsize=int(1e+3))
g_counter = 0
_lock = threading.Lock()


def worker():
    global g_counter
    while True:
        item = g_queue.get()
        if item is None:
            break
        try:
            condition1 = [u'医生您好', u'购买', u'预付款', u'更美总价', u'到医还需付', u'到时见']
            condition2 = [u'医生您好', u'分拨打了您的电话', u'敬请留意']
            if item.type == MESSAGE_TYPE.TEXT and item.is_system is False \
                    and (all(map(lambda x: x in item.content, condition1))
                         or all(map(lambda x: x in item.content, condition2))):
                item.is_system = True
                item.save(update_fields=['is_system'])
                with _lock:
                    g_counter += 1
        except Exception as e:
            with _lock:
                print('Dealing with id:{} got wrong. Error info: {}'.format(item.id, e))
        g_queue.task_done()


class Command(BaseCommand):
    def handle(self, *args, **options):
        thread_nums = 4
        threads = []
        for i in range(thread_nums):
            t = threading.Thread(target=worker)
            t.start()
            threads.append(t)

        qs = Message.objects.filter(send_time__gte=datetime.datetime(2017, 1, 1, 0, 0, 0))
        chunk_size = 500
        cursor = 0
        while True:
            chunk = qs[cursor:cursor + chunk_size]
            if not chunk:
                break
            for item in chunk:
                g_queue.put(item)
                cursor += 1

        g_queue.join()

        for i in range(thread_nums):
            g_queue.put(None)

        for t in threads:
            t.join()

        print("Message statistics done.Total: {}, update:{}".format(cursor, g_counter))
