# -*- coding: utf-8 -*-
# @Time    : 2019/11/8 3:19 PM
# @Author  : Esse
# @FileName: export_ad_check_img.py
import tablib
from django.core.management import BaseCommand
from hippo.models.hospital import Hospital, Hospital_Extra
from hera.management.commands.utils import get_mail


class Command(BaseCommand):
    """
    导出医院广审表的信息
    python manage.py export_ad_check_img
    """

    def handle(self, *args, **options):
        hospitals = Hospital.objects.all()
        count = hospitals.count()
        dt = tablib.Dataset()
        dt.headers = [u'医院ID', u'医院名称', u'广审表图片URL', u'广审表到期时间']
        begin = 0
        step = 1000
        while begin <= count:
            for hospital in hospitals[begin:begin + step]:
                print hospital.id
                try:
                    try:
                        he = Hospital_Extra.objects.get(hospital_id=hospital.id)
                    except:
                        he = None


                    row = (
                        hospital.id,
                        hospital.name,
                        he.ad_check_img if he and he.ad_check_img else '',
                        str(he.ad_check_end_time)[0:10] if he and he.ad_check_end_time else '',
                    )
                    dt.append(row)
                except Exception as e:
                    print e.message
                    continue

            begin += step
        get_mail(u'医院广审表信息.xlsx', u'医院广审表信息', u'zhouyang@igengmei.com', dt.xlsx).send()
