# coding=utf-8
"""更新日记本doctor_id, hospital_id。"""

import math
import time
from multiprocessing import Pool, Manager

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

from gm_types.gaia import TAG_TYPE

from talos.models.diary import Diary
from utils.rpc import rpc_client


def update_diary(queue, limit):

    start_id = queue.get()
    print("start_id: {0}".format(start_id))

    query = Q(pk__gt=start_id, is_online=True, service_id__isnull=False) & (
                Q(doctor_id__isnull=True) | Q(hospital_id__isnull=True))
    diaries = Diary.objects.filter(query)[: limit]
    if not diaries:
        return

    max_id = diaries.aggregate(max_id=Max('id'))
    queue.put(max_id["max_id"])
    print("queue put: ", max_id["max_id"])

    service_ids = list(set(diaries.values_list("service_id", flat=True)))
    doctor_info = rpc_client['api/doctor/list_by_service_ids'](service_ids=service_ids).unwrap()

    for diary in diaries:

        info = {}
        if diary.service_id:
            info = doctor_info.get(str(diary.service_id))

        if not info:
            continue

        diary.doctor_id = info.get('id', None)
        diary.hospital_id = info.get('hospital_id', None)
        diary.save()


class Command(BaseCommand):

    def handle(self, *args, **options):
        """更新日记本doctor_id, hospital_id。"""

        print('------ starting -----')
        start_time = time.time()
        print("start at: ", start_time)

        queue = Manager().Queue(maxsize=8)
        queue.put(0)  # 触发程序开始

        # 没有美购的日记
        args_list = []
        per_num = 500
        count = Diary.objects.using(settings.SLAVE_DB_NAME).filter(is_online=True,
                                                                   service_id__isnull=False,
                                                                   doctor_id__isnull=True).count()
        cnt = int(math.ceil(count/per_num))
        for _ in range(cnt):
            args_list.append((queue, per_num))

        db.connections.close_all()
        pool = Pool(processes=4)
        for args in args_list:
            pool.apply(update_diary, args)
        pool.close()
        pool.join()

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