# coding=utf-8
# create by xueqianqian at 2019/7/8
import tablib
from celery import shared_task
from email.header import make_header

from api.tasks.export_maidan_order_task import get_mail
from hera.utils import attach_title
from hera.utils import get_mail_instance
from rpc.tool.log_tool import log_audit_hera, info_logger

from gm_types.consultation import ORDER_SETTLE_STATUS, ORDER_SETTLE_TYPE

DATETIME_FMT = '%Y-%m-%d %H:%M:%S'


def send_export_mail(subject, body, to_list, dt, send=True):
    if not isinstance(to_list, (list, tuple)):
        to_list = [to_list]
    mail = get_mail_instance(subject, body, to_list)
    mail.attach(attach_title(u'{}.xlsx'.format(subject)), dt.xlsx)
    if send:
        mail.send()

    # audit log
    audit_data = {
        'audit_type': 'export_excel',
        'email_title': subject,
        'email_to': to_list,
        # 'excel_data': dt.xlsx,
        # 'excel_name': u'{}.xlsx'.format(subject),
    }
    log_audit_hera(audit_data)
    return mail


@shared_task
def export_referral_data_excel_task(to_user_email, send_list, order_list, hospital_list, channel_list):
    """
    导出所有转诊数据统计搜索出的数据
    :param to_user_email:
    :return:
    """

    info_logger.info(u'导出开始')
    dt_send = tablib.Dataset()   #派单情况
    dt_order = tablib.Dataset()  #成单情况
    dt_hospital = tablib.Dataset()  #医院情况
    dt_channel = tablib.Dataset()   #渠道情况
    dt_send.headers = (u'人员', u'派单数量', u'派单人数', u'派单医院')
    dt_order.headers = (u'人员', u'成单金额', u'成单抽佣金额', u'成单数', u'成单人数')
    dt_hospital.headers = (u'医院', u'派单数', u'成单数', u'成单金额', u'成单抽佣款金额', u'平均派单业绩', u'平均成单业绩')
    dt_channel.headers = (u'渠道', u'新增线索数', u'派单数', u'成单数',  u'成单金额', u'成单抽佣金额')

    for send in send_list:
        dt_send.append((
            send['single_creator_name'],
            send['send_num'],
            send['send_person'],
            send['send_hospital'],
        ))
    for order in order_list:
        dt_order.append((
            order['single_creator_name'],
            order['budan_projects_payment'],
            order['budan_payment'],
            order['send_num'],
            order['order_num'],
        ))

    for hospital in hospital_list:
        dt_hospital.append((
            hospital['single_doctor_name'],
            hospital['send_num'],
            hospital['order_num'],
            hospital['budan_projects_payment'],
            hospital['budan_payment'],
            hospital['send_achievement'],
            hospital['order_achievement'],
        ))

    for channel in channel_list:
        dt_channel.append((
            channel['channel'],
            channel['clue_num'],
            channel['send_num'],
            channel['order_num'],
            channel['budan_projects_payment'],
            channel['budan_payment'],
        ))

    dt_send.title = u'派单情况'
    dt_order.title = u'成单情况'
    dt_hospital.title = u'医院情况'
    dt_channel.title = u'渠道情况'
    body = ''
    book = tablib.Databook((dt_send, dt_order, dt_hospital, dt_channel))
    info_logger.info(u'导出结束')
    file_name = make_header([('导出转诊数据统计', 'utf-8')]).encode('utf-8')
    get_mail(file_name, body, to_user_email, book).send()

@shared_task
def export_clue_data_excel_task(to_user_email, send_list):
    """
    导出所有线索数据统计搜索出的数据
    :param to_user_email:
    :return:
    """

    info_logger.info(u'导出开始')
    dt = tablib.Dataset()
    dt.headers = (u'人员', u'创建线索数', u'已通过微信验证数', u'未通过微信验证数')

    for send in send_list:
        dt.append((
            send['bdtransfer_creator_name'],
            send['clue_num'],
            send['adopted'],
            send['notadopted'],
        ))

    body = ''
    info_logger.info(u'导出结束')
    file_name = make_header([('导出线索数据统计', 'utf-8')]).encode('utf-8')
    get_mail(file_name, body, to_user_email, dt).send()


@shared_task
def export_connection_data_excel_task(to_user_email, consul, dict2, hospital_id_list):
    """
    导出连线记录功能
    :param to_user_email:
    :return:
    """
    from hippo.models.hospital import Hospital
    from hippo.models.doctor import Doctor

    id_list = []
    for i in consul:
        id = i['counsellor_doctor_id']
        id_list.append(id)
    id_list_finall = set(id_list)
    id_list_finally = list(id_list_finall)
    name = Doctor.objects.filter(id__in=id_list_finally).values_list("id", "name", "hospital__name")

    dict1 = {}
    for i in id_list_finally:
        for j in list(name):
            if i == j[0]:
                dic = {i: j}
                dict1[i] = dic

    hospital_name = Hospital.objects.filter(id__in=hospital_id_list).values_list('id', 'name')

    dict3 = {}
    for i, j in dict2.items():
        for z in list(hospital_name):
            if j.get(i)[2] == z[0]:
                j.get(i).append(z[1])
                dict3[i] = j.get(i)

    consul_finally = []
    for i in consul:
        type = i.get('counsellor_type')
        a = i.get('counsellor_doctor_id')
        b = dict1.setdefault(a)
        c = i.get('counsellor_consultant_id')
        d = dict3.setdefault(str(c))
        if type == '医生':
            if b:
                docter = {'doctor_name': b[a][1]}
                hospital = {'hospital_name': b[a][2]}
                c = dict(i.items() + docter.items() + hospital.items())
                consul_finally.append(c)
            else:
                docter = {'doctor_name': 'None'}
                hospital = {'hospital_name': 'None'}
                c = dict(i.items() + docter.items() + hospital.items())
                consul_finally.append(c)
        if type == '面诊师':
            if d:
                docter_id = {'counsellor_doctor_id': d[0]}
                docter = {'doctor_name': d[1]}
                hospital = {'hospital_name': d[3]}
                c = dict(i.items() + docter_id.items() + docter.items() + hospital.items())
                consul_finally.append(c)
            else:
                docter = {'doctor_name': 'None'}
                hospital = {'hospital_name': 'None'}
                c = dict(i.items() + docter.items() + hospital.items())
                consul_finally.append(c)

    info_logger.info(u'导出开始')
    dt = tablib.Dataset()
    dt.headers = (u'连线记录ID',u'连线类型', u'发起时间', u'连线开始时间', u'连线结束时间',
                  u'面诊时长(s)', u'等待时长(s)', u'用户ID', u'用户类型', u'年龄', u'性别',
                  u'是否做过医美', u'咨询项目', u'医生ID',u'医生名称',u'机构名称',
                  u'医生类型', u'擅长项目', u'连线状态', u'结束原因')

    for send in consul_finally:
        dt.append((
            send['id'],
            send['type'],
            send['creat_time'],
            send['connected_time'],
            send['finish_time'],
            send['face_length'],
            send['wait_ingres'],
            send['user_id'],
            send['user_classify'],
            send['user_age'],
            send['user_gender'],
            send['user_has_aesthetic_medicine'],
            send['user_target_project'],
            send['counsellor_doctor_id'],
            send['doctor_name'],  # 医生名称
            send['hospital_name'],  # 机构名称
            send['counsellor_type'],
            send['counsellor_good_at'],
            send['status'],
            send['finish_reason'],
        ))

    body = ''
    info_logger.info(u'导出结束')
    file_name = make_header([('导出连线记录', 'utf-8')]).encode('utf-8')
    get_mail(file_name, body, to_user_email, dt).send()


@shared_task
def export_order_settlement_excel_task(to_user_email, data):
    """
    导出连线记录功能
    :param to_user_email:
    :return:
    """
    from hippo.models.doctor import Doctor

    doctor_ids = [item["counsellor_doctor_id"] for item in data if item["counsellor_type"] == 1]  # 医生类型面诊顾问
    doctor_names = Doctor.objects.filter(id__in=list(set(doctor_ids))).values_list("id", "name")

    doctor_name_map = {doctor_id: name for doctor_id, name in doctor_names}

    info_logger.info(u'导出开始')
    dt = tablib.Dataset()
    dt.headers = (u'对账单id', u'结算对象类型', u'结算对象id', u'结算对象名称', u'结算周期', u'结算金额',
                  u'结算状态', u'结算类型', u'结算账号', u'财务结算时间')

    for record in data:
        if record["counsellor_type"] == 1:
            name = doctor_name_map.get(record['counsellor_doctor_id'], "")
        else:
            name = record["consultant_name"]

        dt.append((
            record['id'],
            record.get('counsellor_type_text'),
            record.get('counsellor_doctor_id') or record.get('counsellor_consultant_id'),
            name or "",
            "{}{}".format(record["year"], record["month"]),
            str(round(record['amount'] / 100, 2)),
            ORDER_SETTLE_STATUS.getDesc(record['status']) or "",
            ORDER_SETTLE_TYPE.getDesc(record["type"]) or "",
            record['account'] or "",
            record['settle_time'],
        ))

    body = ''
    info_logger.info(u'导出结束')
    file_name = make_header([('导出订单结算账单', 'utf-8')]).encode('utf-8')
    get_mail(file_name, body, to_user_email, dt).send()


@shared_task
def return_export_data_excel_task(to_user_email, send_list):
    """
    回访导出
    :param to_user_email:
    :return:
    """
    info_logger.info(u'导出开始')
    dt = tablib.Dataset()
    dt.headers = (u'回访任务ID', u'转诊对象ID', u'任务状态',u'线索状态',
                  u'姓名', u'执行人', u'计划回访时间', u'实际回访时间',
                  u'回访形式', u'有效状态', u'创建人',u'创建时间')

    for send in send_list:
        dt.append((
            send['id'],
            send['bdtransfer__id'],
            send['status'],
            send['bdtransfer__object_state'],
            send['bdtransfer__user'],
            send['assignor'],
            send['plan_at'],
            send['visit_at'],
            send['method'],
            send['state'],
            send['creator'],
            send['create_at'],
        ))

    body = ''
    info_logger.info(u'导出结束')
    file_name = make_header([('导出回访记录', 'utf-8')]).encode('utf-8')
    get_mail(file_name, body, to_user_email, dt).send()