# -*- coding: UTF-8 -*-
from datetime import datetime
from django.core.management import BaseCommand
from openpyxl import load_workbook
from api.models import ServiceItem
from .utils import get_mail

change_time = str(datetime.now().date())


class Command(BaseCommand):
    """
        python manage.py update_20170518_unlock_sku
        解锁sku美购
    """

    def add_arguments(self, parser):
        parser.add_argument('filename', nargs='+', type=str)

    def handle(self, *args, **options):
        filename = options['filename'][0]
        wb = load_workbook(filename=filename)
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[0])
        error_msg = ''
        result_log = ''
        for rx in range(2, ws.get_highest_row() + 1):
            sku_id = ws.cell(row=rx, column=2).value
            try:
                serviceitem = ServiceItem.objects.get(id=sku_id)
                result_log += u'{}:{}'.format(sku_id, serviceitem.service.servicelock_set.values('id', 'locklist_id'))
                serviceitem.service.servicelock_set.all().delete()
                print sku_id
            except Exception as e:
                message = '{}:{}'.format(sku_id, e.message)
                print message
                error_msg += '\n'
        body = u'{}_unlock_sku'.format(change_time)
        get_mail(u'{}_rusult.txt'.format(body), u'{}_result'.format(body), [u'chenfeifei@gmei.com'], result_log).send()
        get_mail(u'{}_error.txt'.format(body), u'{}_error'.format(body), [u'chenfeifei@gmei.com'], error_msg).send()
        print u'DONE!'
