#coding=utf-8
import tablib
from django.core.management import BaseCommand
from openpyxl import load_workbook

from api.models import TransactionNearbyCityToES
from api.tasks.export_maidan_order_task import get_mail


class Command(BaseCommand):
    """
    临近城市数据刷新
    python manage.py update_near_city
    """
    def handle(self, *args, **options):
        dt = tablib.Dataset()
        dt.headers = (u'city_id', u'near_city_id')
        workbook = load_workbook('./near_city.xlsx', read_only=False, data_only=True)
        id = TransactionNearbyCityToES.objects.all().order_by('-id').first().id
        city_ls = []
        rows = workbook['city']._current_row
        citise = TransactionNearbyCityToES.objects.all()
        for obj in citise:
            dt.append((obj.city_id, obj.nearby_city_id))
        for item in workbook['city'][2:rows]:
            city_id = item[1].value
            near_city_id = item[3].value
            print(city_id, near_city_id)
            obj = TransactionNearbyCityToES(city_id=city_id, nearby_city_id=near_city_id)
            city_ls.append(obj)
        TransactionNearbyCityToES.objects.bulk_create(city_ls)
        TransactionNearbyCityToES.objects.filter(id__lte=id).delete()
        get_mail(u'临近城市历史数据', u'历史数据', u'songzhenqi@igengmei.com', dt).send()

