#! /usr/bin/env python
# -*- coding: utf-8 -*-
# create by oldman
# Date: 2018/9/25
import tablib
from django.core.management import BaseCommand
from openpyxl import load_workbook

from api.tasks.export_maidan_order_task import get_mail
from hippo.models import Hospital


def _create_hospital(**kwargs):
    hospital = Hospital.objects.create(**kwargs)
    return hospital


def _read_excel():
    wb = load_workbook(filename=u'hospital.xlsx')
    sheetnames = wb.get_sheet_names()
    ws = wb.get_sheet_by_name(sheetnames[0])
    # 读取excel
    hospitals = []
    for rx in range(2, ws.get_highest_row() + 1):
        try:
            item = {
                "name": ws.cell(row=rx, column=1).value,
                "city_id": ws.cell(row=rx, column=2).value,
                "hospital_type": ws.cell(row=rx, column=3).value,
                "location": ws.cell(row=rx, column=4).value,
                "doctor_reply_limit": 0,
                "accept_private_msg": True,
                "description": ws.cell(row=rx, column=7).value
            }
            hospitals.append(item)
        except Exception as e:
            print e
            continue

    print 'Done'
    return hospitals


class Command(BaseCommand):
    """
    批量创建新的医院
    python manage.py update_2018_09_25_create_new_hospital
    """

    def handle(self, *args, **options):
        hospital_ids = []
        hospitals = _read_excel()
        to_user_email = 'lipeng@igengmei.com'
        dt = tablib.Dataset()
        dt.headers = [
            U'医院名字', u'医院ID'
        ]
        for info in hospitals:
            try:
                hospital = _create_hospital(**info)
                x = (hospital.name,
                     hospital.id)
                dt.append(x)
                hospital_ids.append((hospital.id, hospital.name))
                print hospital.id
            except Exception as e:
                print e
                continue
        print hospital_ids
        body = u'新增医院数据'
        get_mail(u'新增医院数据', body, to_user_email, dt).send()