# coding=utf-8

from collections import namedtuple

import xlrd

from django.core.management import BaseCommand

from api.models import PeriodHospital


location = '/tmp/线上分期机构表.xlsx'


Hdict = namedtuple('Hdict', 'id name date')


class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        data = xlrd.open_workbook(location)
        table = data.sheets()[0]
        rows = {unicode(x[0].value).strip(): x for x in list(table.get_rows())[1:] if x[0].value}
        hospitals = PeriodHospital.objects.filter(hospital_id__in=rows.keys())
        fail_id = set(rows.keys()) - {x.hospital_id for x in hospitals}

        for hospital in hospitals:
            hdict = Hdict(*rows[hospital.hospital_id])
            hdate = str(hdict.date.value)[:8]
            if hdate.isdigit() and hdate.startswith('201') and len(hdate) == 8:
                hospital.create_time = '{}-{}-{}'.format(hdate[:4], hdate[4:6], hdate[6:])
            hospital.default_online = True
            hospital.save()
        print('Done!')
