# coding:utf-8

"""初始化面诊师。

面诊师存放在 diagnosis 服务中
"""

import json

from django.core.management import BaseCommand
from django.conf import settings

from gm_types.gaia import DOCTOR_TYPE

from api.models import Doctor, Service, ServiceTag, Tag, TagRelation, Merchant
from rpc.all import get_rpc_remote_invoker

rpc = get_rpc_remote_invoker()


class Command(BaseCommand):
    tags = settings.FACE_CONSULT_TAGS
    len_batch_create = 20

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

        tag_relas = TagRelation.objects.filter(
            parent_id__in=self.tags
        ).values("parent_id", "child_id")

        relations = {tag_id: [tag_id] for tag_id in self.tags}
        for tag_rela in tag_relas:
            relations[tag_rela["parent_id"]].append(tag_rela["child_id"])

        counsellors = []

        doctor_ids = []  # TODO: 加入指定doctor_id 生成

        query = Doctor.objects.using(settings.SLAVE_DB_NAME).filter(
            is_online=True, doctor_type=DOCTOR_TYPE.DOCTOR, user_id__isnull=False)

        if doctor_ids:
            query = query.filter(id__in=doctor_ids)

        for doctor in query:
            # 获取标签数量，并且排序获取前三
            doctor_tags_service_cnt = {}
            for tag_id, relation_ids in relations.items():
                service_cnt = ServiceTag.objects.filter(
                    service__doctor_id=doctor.id, tag_id__in=relation_ids, service__is_online=True
                ).count()
                if not service_cnt:
                    continue
                doctor_tags_service_cnt[tag_id] = service_cnt
            good_ats = sorted(doctor_tags_service_cnt.items(), key=lambda d: - d[1])

            good_at = json.dumps([i for i, _ in good_ats[:3]])

            counsellor = {
                "doctor_id": doctor.id,
                "user_id": doctor.user_id,
                "merchant": doctor.merchant and doctor.merchant.id or None,
                "good_at": good_at,
            }
            counsellors.append(counsellor)

            # 每批生成20个数据
            if len(counsellors) == self.len_batch_create:
                self.create_counsellor(counsellors)
                counsellors = []

        if counsellors:
            self.create_counsellor(counsellors)

        print("创建面诊师脚本执行完毕")

    def create_counsellor(self, counsellors):

        try:
            rpc["diagnosis/batch_create_counsellor"](counsellors_info=counsellors).unwrap()
        except:
            print("创建面诊师出错：{}".format(json.dumps(counsellors)))
