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

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


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

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

    def handle(self, *args, **options):
        filename = options['filename'][0]
        error_log = ''
        result_log = ''
        file = open(filename, 'r')
        chang_file = json.loads(file.read())
        for k, v in chang_file.iteritems():
            try:
                serviceitem = ServiceItem.objects.get(id=k)
                for lock_id in v:
                    print k, lock_id
                    lock = ServiceLock.objects.create(locklist_id=lock_id, service_id=serviceitem.service_id)
                    result_log += u'{},{},{}\n'.format(lock_id, lock.locklist_id, lock.service_id)
            except Exception as e:
                message = '{}:{}'.format(k, e.message)
                print message
                error_log += message + '\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_log).send()
