# coding=utf-8
# create by oldman at 2018/9/19

from hippo.models import MasterMerchant, SlaveMerchant
from hippo.models import Merchant
from hippo.utils import get_doctors
from rpc.tool.log_tool import logging_exception


def get_merchant_message_doctors(doctor_id):
    """
    获取医生可管理私信的医生
    医生可为商户可不为商户
    :param doctor_id:
    :return:
    """
    try:
        merchants = Merchant.objects.filter(doctor_id=doctor_id)
        if merchants.exists():
            merchant = merchants.first()
            res = get_doctors(merchant.doctor.id)
            mastermerchants = MasterMerchant.objects.filter(
                mastermerchant_id=merchant.id, is_message_related=True)
            if mastermerchants.exists():
                mastermerchant = mastermerchants.first()
                for item in mastermerchant.slavemerchants.all():
                    res.extend(get_doctors(item.slavemerchant.doctor.id))
        else:
            res = get_doctors(doctor_id)
        return res
    except Exception:
        logging_exception()
        return []


def get_master_merchant(merchant_id):
    """
    根据商户ID获取朱商户的ID
    :param merchant:
    :return:
    """
    try:
        slavemerchants = SlaveMerchant.objects.filter(slavemerchant_id=merchant_id)
        if slavemerchants.exists():
            return slavemerchants.first().mastermerchant.mastermerchant
    except:
        return None