# coding: utf-8
from rpc.decorators import bind_context
from hippo.models.doctor import *
from .referral_data_task import *
from django.conf import settings
from hippo.tool.chain_hospital_tools import get_merchant_message_doctors
from api.models import Conversation, Message, Merchant


@bind_context('api/mims/phone_leads/export_excel')
def export_excel_phone_leads(ctx, result):
    doctor_id_list = []
    # user_id : [uid_hash,,,,]
    user_2_uid_hash = {}
    for i in result:
        user_id = i.get('user_id')
        officer_id = i.get('doctor_id')
        doctor_id_list.append(officer_id)
        merchant_doctor_list = get_merchant_message_doctors(officer_id)
        for doctor_info in merchant_doctor_list:
            doctor_user_id = doctor_info.get('user_id','')
            if user_id and doctor_user_id:
                uid_hash = Conversation.gen_uid_hash([user_id, doctor_user_id])
                user_2_uid_hash.setdefault(user_id,[]).append(uid_hash)

    print user_2_uid_hash
    need_pop_user_id_list = []
    for user_id in user_2_uid_hash:
        uid_hash_list = user_2_uid_hash[user_id]
        if uid_hash_list:
            conversation_ids = Conversation.objects.filter(uid_hash__in=uid_hash_list).values_list('id', flat=True)
            if conversation_ids:
                message_count = Message.objects.filter(conversation_id__in=conversation_ids, is_system=False).count()
                print message_count
                if message_count >= 3:
                    need_pop_user_id_list.append(user_id)

    res = Doctor.objects.filter(id__in=doctor_id_list).values_list('id', 'name', 'hospital__city__name',
                                                                   'hospital__city__province__region__name',
                                                                   'business_partener__username','hospital_id')
    info_logger.info('export_excel_phone_leads------过滤出用户------{}'.format(str(need_pop_user_id_list)))
    # 过滤出有效私信的
    if need_pop_user_id_list:
        for item in result[:]:
            user_id = item.get('user_id')
            if user_id in need_pop_user_id_list:
                result.remove(item)

    for i in result:
        for j in res:
            if i.get('doctor_id') == j[0]:
                i['hospital_name'] = j[1]
                i['city'] = j[2]
                i['region'] = j[3]
                i['name'] = j[4]
                i['hospital_id'] = j[5]

    for item in result:
        merchant_id = item.get('merchant_id','')
        merchant_level = ''
        if merchant_id:
            merchant = Merchant.objects.filter(id=merchant_id).first()
            if merchant:
                merchant_level = merchant.merchant_level
        item['merchant_level'] = merchant_level

    for email in settings.EMAIL_LIST:
        return_export_excel_phone_leads.delay(email, result)