# -*- coding: utf-8 -*-

from api.models import (
    Doctor,
    Hospital,
    DOCTOR_ORDER_TYPE,
    DOCTOR_TYPE,
)
from search.utils.doctor import filter_doctor


def get_doctors_detail(id_list, is_favored=False, need_intro=False):
    """get doctor info with doctor detail v2."""
    doctors = Doctor.objects.prefetch_related(
        'business_partener', 'hospital__city__province', 'hospital__hospital_extra', 'hospital__doctor_hospital', 'tags'
    ).filter(id__in=id_list, is_online=True)
    res = {
        'doctor_info': {}
    }

    hospital_id_list = []
    map_doctor_hospital = {}

    for doctor in doctors:
        res['doctor_info'][doctor.id] = doctor.doctor_detail_v2(
            is_favored, need_intro
        )
        hospital_id = res['doctor_info'][doctor.id]['hospital_id']
        hospital_id_list.append(hospital_id)

        # 医院跟医生不是1对1
        if hospital_id in map_doctor_hospital:
            map_doctor_hospital[hospital_id].append(doctor.id)
        else:
            map_doctor_hospital[hospital_id] = [doctor.id]

    hospitals = Hospital.objects.filter(id__in=hospital_id_list)

    for hospital in hospitals:
        doctor_ids = map_doctor_hospital[hospital.id]
        for doctor_id in doctor_ids:
            res['doctor_info'][doctor_id]['hospital_rate'] = hospital.rate

    return res


def get_doctors_hospitals_by_tags(tag_ids, offset=0, size=10,
                                  sort_type=DOCTOR_ORDER_TYPE.DEFAULT2):
    result = {}
    filters = {'tag_ids': tag_ids}
    for doctor_type, dict_key in [(DOCTOR_TYPE.DOCTOR, 'doctors'),
                                  (DOCTOR_TYPE.OFFICER, 'hospitals')]:
        filters['doctor_type'] = doctor_type
        doctors = filter_doctor(
            offset=0, size=size,
            filters=filters, sort_type=sort_type
        )
        doctor_ids = doctors['doctor_ids']
        doctors = Doctor.objects.prefetch_related(
            'business_partener', 'hospital__city__province', 'hospital__hospital_extra', 'hospital__doctor_hospital',
            'tags'
        ).filter(id__in=doctor_ids)
        doctors = {d.id: d for d in doctors}
        result[dict_key] = [
            doctors[did].doctor_detail_v2()
            for did in doctor_ids if did in doctors
        ]
    return result
