# coding: utf-8
import tablib
from django.core.management import BaseCommand
from api.models.message import Message
from api.models import Doctor
from gm_types.gaia import DOCTOR_TYPE
from hippo.models.quick_reply import QuickReplyGroup, QucikReplyContent
from hippo.models.merchant import Merchant, MerchantRelevance
from rpc.tool.log_tool import info_logger
from hera.utils import get_mail_instance, attach_title


class Command(BaseCommand):
    """
    导出商家当前设置的【快捷回复】 数据
    """
    def handle(self, *args, **options):

        dt = tablib.Dataset()
        dt.headers = [
            u"商户ID", u"商户名称", u"医生ID", u"医生名称",
            u"医生类型", u"快捷回复分组名称", u"快捷回复内容序号", u"快捷回复内容文案"
        ]
        quick_replys = QuickReplyGroup.objects.prefetch_related("qucik_reply_contents").all()
        doctor_ids = list({item.doctor_id for item in quick_replys})
        info_logger.info("total quick_replys: %s" % len(quick_replys))

        doctors = Doctor.objects.filter(id__in=doctor_ids)
        doctor_info = {
            d.id: {
                "id": d.id,
                "doctor_name": d.name,
                "doctor_type": DOCTOR_TYPE.getDesc(d.doctor_type),
                "merchant_id": "-",
                "merchant_name": "-"
            }
            for d in doctors
        }

        info_logger.info("total doctor info: %s" % len(doctor_info))

        merchants = Merchant.objects.filter(doctor_id__in=doctor_ids).all()
        for m in merchants:
            doctor_info[m.doctor_id]["merchant_id"] = m.id
            doctor_info[m.doctor_id]["merchant_name"] = m.name

        info_logger.info("total merchants: %s" % len(merchants))

        row = 1
        for quick_reply in quick_replys:
            for content in quick_reply.qucik_reply_contents.all():
                doctor = doctor_info.get(quick_reply.doctor_id)

                dt.append(
                    [
                        doctor["merchant_id"], doctor["merchant_name"], doctor["id"],
                        doctor["doctor_name"], doctor["doctor_type"], quick_reply.name,
                        content.rank, content.name
                    ]
                )
        info_logger.info("导出商家快捷回复设置导出结束")
        body = u'商家快捷回复设置导出'
        email_list = ["zhongshangwu@igengmei.com"]
        send_export_mail(u'商家快捷回复设置导出', body, email_list, dt)


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()

    return mail