# coding=utf-8

import xlrd
from django.core.management import BaseCommand
from django.db.transaction import atomic
from api.models import Service, ServiceItem, ServiceRegister, ServiceRegisterItem
from api.models import ServiceItemKey, AttrOptions
from ..tools import baselog


def sku_name():
    data = xlrd.open_workbook('normative_sku_name.xls'.decode('utf-8'))
    table = data.sheets()[0]
    for r in range(1, table.nrows):
        info = table.row_values(r)
        sku_id = info[2]
        sku_name = info[3]
        print(sku_id, sku_name)
        try:
            with atomic():
                sku_reg = ServiceRegisterItem.objects.get(
                    serviceitem_id=sku_id)
                sku = ServiceItem.objects.get(id=sku_id)
                obj = ServiceItemKey.objects.filter(serviceitem_id=sku_id).first()
                if obj:
                    AttrOptions.objects.filter(id=obj.serviceattroption_id).update(name=sku_name)
        except Exception as e:
            print(sku_id)
            print(e)


def spu_short_description():
    data = xlrd.open_workbook('normative_spu_name.xls'.decode('utf-8'))
    table = data.sheets()[0]
    for r in range(1, table.nrows):
        info = table.row_values(r)
        spu_id = info[0]
        spu_short_description = info[2]
        print(spu_id, spu_short_description)
        try:
            with atomic():
                spu_reg = ServiceRegister.objects.get(service_id=spu_id)
                spu_reg.short_description = spu_short_description
                spu_reg.save()
                spu = Service.objects.get(id=spu_id)
                spu.short_description = spu_short_description
                spu.save()
        except Exception as e:
            print(spu_id)
            print(e)


class Command(BaseCommand):
    """
    python manage.py insert_20190527_normative_service_name
    """
    def handle(self, *args, **options):
        sku_name()
        spu_short_description()
        print("Done!")