# coding=utf-8

import xlrd
from django.core.management import BaseCommand
from api.models import TransactionNearbyCity
from api.models import TransactionNearbyCityToES
from search.utils.area import NearbyCityGraph

class Command(BaseCommand):
    """
    交易部分 邻近城市表（包括美购医院医生）
    """

    def handle(self, *args, **kwargs):
        data = xlrd.open_workbook('transaction_nearby_city.xlsx'.decode('utf-8'))

        table = data.sheets()[1]
        # 清空表
        TransactionNearbyCity.objects.all().delete()
        city_list = []
        for row in range(1, table.nrows):
            try:
                row_data = table.row_values(row)
                city = row_data[3].strip()
                nearby_cities = row_data[5].strip().split(' ')
                city_list.extend([
                    TransactionNearbyCity(
                        city_id=city,
                        nearby_city_id=nearby_city
                    ) for nearby_city in nearby_cities
                ])
            except:
                print row + 1
        TransactionNearbyCity.objects.bulk_create(city_list)
        print 'Insert Done'
        TransactionNearbyCityToES.objects.all().delete()
        g = NearbyCityGraph.build()
        es_city_list = []
        for k, v in g.cityMapping.items():
            es_city_list.extend([
                TransactionNearbyCityToES(
                    city_id=k,
                    nearby_city_id=vv,
                ) for vv in v
            ])
        TransactionNearbyCityToES.objects.bulk_create(es_city_list)
        print 'DONE!'

