# coding=utf-8

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


def delete_old_relation():
    """
    删除历史个性化标签
    :return:
    """
    ServiceTag.objects.filter(tag__tag_type=TAG_TYPE.YUNYING).delete()


def insert_tag_relation():
    """美购关联个性化标签"""
    data = xlrd.open_workbook('doctor_person_tag.xlsx'.decode('utf-8'))

    for table in data.sheets()[:8]:
        for row in range(1, table.nrows):
            r_info = table.row_values(row)
            hospital_id = r_info[2]
            tag_ids = [r_info[3], r_info[5]]
            service_ids = Service.objects.filter(doctor__hospital_id=hospital_id) \
                .values_list('id', flat=True)
            for s_id in service_ids:
                for t_id in tag_ids:
                    try:
                        ServiceTag.objects.get_or_create(
                            service_id=s_id,
                            tag_id=t_id
                        )
                    except:
                        print 'error', 's_id:', s_id, 't_id:', t_id


def add_yunying_tag():
    """美购关联个性化标签 通过serviceid"""
    data = xlrd.open_workbook('service_dbo_tag.xlsx'.decode('utf-8'))
    for table in data.sheets()[:8]:
        for row in range(1, table.nrows):
            r_info = table.row_values(row)
            service_id = r_info[5]
            tag_ids = [r_info[6], r_info[8]]
            ServiceTag.objects.filter(service_id=service_id, tag__tag_type=TAG_TYPE.YUNYING).delete()
            for tag_id in tag_ids:
                if tag_id:
                    try:
                        ServiceTag.objects.get_or_create(
                            service_id=service_id,
                            tag_id=tag_id
                        )
                    except:
                        print 'error', 'service_id:', service_id, 'tag_id:', tag_id


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

    def handle(self, *args, **options):
        # print('-------delete tag_relation start------')
        # delete_old_relation()
        # print('-------delete tag_relation end------')
        #
        # print('-------insert tag_relation start------')
        # insert_tag_relation()
        # print('-------insert tag_relation end------')
        add_yunying_tag()
        print 'Done!'

