# coding=utf-8
from operator import attrgetter
import tablib
from openpyxl import load_workbook
from django.core.management.base import BaseCommand

from hippo.models.doctor import Doctor
from hera.utils import get_mail_instance, attach_title


class Command(BaseCommand):
    def handle(self, *args, **options):
        dt = tablib.Dataset()
        dt.headers = [u"城市", u"是否KA", u"商家名称", u"商家ID", u"商家管理者ID"]
        wb = load_workbook('/tmp/merchants.xlsx')
        ws = wb.active
        for row in list(ws)[1:]:
            values = map(attrgetter('value'), row)
            hospital_id = values[3]
            merchant = Doctor.objects.filter(
                is_merchant=True,
                hospital_id=hospital_id
            ).first()
            if merchant:
                values.append(merchant.user_id)
            else:
                values.append('')
            dt.append(values)

        mail = get_mail_instance(u"商家信息", u"商家信息", ['xufukun@igengmei.com'])
        mail.attach(attach_title(u"商家信息.xlsx"), dt.xlsx)
        mail.send()
