# -*- coding: UTF-8 -*-
import codecs
from django.core.management import BaseCommand
from openpyxl import load_workbook
from api.models import Service


class Command(BaseCommand):
    """
        python manage.py update_20170426_offline_service_item_lt10
        下线10元以下在线美购属性
    """

    def handle(self, *args, **options):
        wb = load_workbook(filename=u'10元以下在线美购20170425.xlsx')
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[1])
        error_log = open('20170426_offline_item_error.txt', 'a')
        result_log = open('20170426_offline_item_result.txt', 'a')
        for rx in range(2, ws.get_highest_row() + 1):
            service_id = int(ws.cell(row=rx, column=1).value)
            item_price = int(ws.cell(row=rx, column=5).value)
            try:
                service = Service.objects.get(id=service_id)
                for item in service.items.filter(is_delete=False):
                    if item.gengmei_price == item_price:
                        item.is_delete = True
                        item.save()
                        result_message = 'service_id:{}, item_id:{},item_price:{},item.is_delete:{}\n'.format(
                            service.id, item.id, item.gengmei_price, item.is_delete)
                        result_log.write(result_message)
                print service_id
            except Exception as e:
                message = '{}:{}'.format(service_id, e.message)
                print message
                error_log.write(message + u'\n')
                import traceback;
                traceback.print_exc(error_log)
                continue
        print u'DONE!'
