# coding=utf-8

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


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



def add_yunying_tag():
    """美购关联个性化标签 通过serviceid"""
    index = 1
    data = xlrd.open_workbook('service_dbo_20190416_tag.xls'.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[2]
            relation_tagids = list()
            try:
                if service_id:
                    service_id = int(service_id)
                else:
                    continue
                if r_info[3]:
                    relation_tagids.append(int(r_info[3]))
                if r_info[5]:
                    relation_tagids.append(int(r_info[5]))
                for tag_id in relation_tagids:
                    ServiceTag.objects.get_or_create(
                        service_id=service_id,
                        tag_id=tag_id
                    )
            except Exception as ex:
                print 'error', 'service_id:', service_id, 'tag_id:', relation_tagids
                print ex
            index += 1
    print 'result...rows...:', index


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

    def handle(self, *args, **options):
        delete_old_relation()
        add_yunying_tag()
        print 'Done!'

