from django.core.management import BaseCommand
import xlrd
import datetime
from api.models import BDTransfer


def make_data():
    f = open('hera/excel/old.xlsx')
    readbook = xlrd.open_workbook(filename=None, file_contents=f.read())
    a_sheet = readbook.sheet_by_index(0)

    ret = {}
    rows = a_sheet.nrows
    for i in range(1,rows):
        bdtransfer_id = a_sheet.cell(i,0).value
        phone = str(a_sheet.cell(i,1).value)

        try:
            phone = str(int(float(phone)))
        except:
            pass
        date = a_sheet.cell(i,2).value
        if date:
            if isinstance(date, float):
                date = xlrd.xldate.xldate_as_datetime(date, 0)
            elif isinstance(date, str):
                date = datetime.datetime.strptime(date,'%Y-%m-%d')
        else:
            date = None

        ret[bdtransfer_id] = {
            'old_phone':phone,
            'old_datetime':date,
        }
    f.close()
    return ret


class Command(BaseCommand):
    def handle(self, *args, **options):
        ret = make_data()
        for bdtransfer_id in ret:
            try:
                bdtransfer = BDTransfer.objects.get(id=int(float(bdtransfer_id)))
            except:
                print 'don not have this bdtransfer id {}'.format(str(int(float(bdtransfer_id))))
                continue

            for attr, value in ret[bdtransfer_id].items():
                setattr(bdtransfer, attr, value)

            bdtransfer.save()

        print 'Done'