# coding=utf-8
import json

import tablib
from openpyxl import load_workbook
from django.core.management import BaseCommand
from hera.utils import get_mail_instance, attach_title
from rpc.tool.log_tool import log_audit_hera
from hippo.models.doctor import Doctor


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


class Command(BaseCommand):

    def handle(self, *args, **options):
        wb = load_workbook(filename=u'error_doctor_list.xlsx')
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[0])
        dt_error = tablib.Dataset()
        dt_error.headers = ['doctor_id', 'exception']
        count = 0
        for rx in range(2, ws.max_row + 1):
            try:
                doctor_id = ws.cell(row=rx, column=1).value
                doctor = Doctor.objects.get(pk=doctor_id)
                doctor.business_partener = None
                doctor.save()
                print doctor_id
            except Exception as e:
                doctor_id = ws.cell(row=rx, column=1).value
                dt_error.append((doctor_id, e))
                count += 1
                continue

        dt_error.title = u'错误信息'

        to_list = ['zhouyang@igengmei.com', 'lvguowei@igengmei.com', 'sunyaxue@igengmei.com']
        send_export_mail(u'去除医生关联商务错误信息', u'错误信息共{}条'.format(count), to_list, dt_error)

        print 'DONE'

