# coding=utf-8

import xlrd
from django.core.management import BaseCommand
from api.models import Service, ServiceTag

class Command(BaseCommand):
    """
    python manage.py insert_2018_08_01_insert_spu_personal_tag
    """

    def handle(self, *args, **kwargs):
        data = xlrd.open_workbook('insert_personal_tab.xlsx'.decode('utf-8'))
        table = data.sheets()[0]

        tag_list = []
        for row in range(1, table.nrows):
            try:
                row_data = table.row_values(row)
                hospital_id = row_data[1]
                tag_ids = [row_data[2], row_data[5]]
                service_ids = Service.objects.filter(doctor__hospital_id=hospital_id).values_list('id', flat=True)
                for service_id in service_ids:
                    tag_list.extend([
                        ServiceTag(
                            service_id=service_id,
                            tag_id=tag_id
                        ) for tag_id in tag_ids if tag_id != ''
                    ])
                print row_data[0], "succeed"
            except:
                print "error", row
        step = 100
        for start in range(0, len(tag_list), step):
            ServiceTag.objects.bulk_create(tag_list[start:start+step])
        print "Done!"