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


change_time = str(datetime.now().date())
result_log = open('{}_change_sku_price.txt'.format(change_time), 'a')
error_log = open('{}_change_sku_price_error.txt'.format(change_time), 'a')


def write_result(item, price_id):
    price_info = item.get_price_info(price_id=price_id)
    message = 'item_id:{}, item_info:{}\n'.format(item.id, price_info)
    result_log.write(message)


def change_item_price(item, price_info, price_id):
    write_result(item, price_id)
    price_info['price_id'] = price_id
    item.update_price(**price_info)
    write_result(item, price_id)


class Command(BaseCommand):
    """
        python manage.py update_20170509_520_change_sku_price change/recover
        520 批量改sku价格
    """

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

    def handle(self, *args, **options):
        if options['action'][0] == 'change':
            start_colum = 7
        elif options['action'][0] == 'recover':
            start_colum = 3
        else:
            print '输入参数不正确'
            return

        wb = load_workbook(filename=options['action'][2])
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[int(options['action'][1])])
        p = Pool(processes=4)
        for rx in range(2, ws.get_highest_row() + 1):
            sku_id = ws.cell(row=rx, column=1).value
            apply_id = ws.cell(row=rx, column=2).value or None
            print_info = {
                'gengmei_price': ws.cell(row=rx, column=start_colum).value,
                'pre_payment_price': ws.cell(row=rx, column=start_colum + 1).value,
                'discount': ws.cell(row=rx, column=start_colum + 2).value,
                'self_support_discount': ws.cell(row=rx, column=start_colum + 3).value
            }
            try:
                item = ServiceItem.objects.get(id=sku_id)
                price_ids = self.get_price_ids(item, apply_id)
                for price_id in price_ids:
                    res = p.apply_async(change_item_price, args=(item, print_info, price_id))
                    res.get()
                print sku_id
            except Exception as e:
                message = '{}:{}'.format(sku_id, e.message)
                print message
                error_log.write(message + '\n')
                import traceback;
                traceback.print_exc(error_log)
                continue
        p.close()
        p.join()
        result_log.close()
        error_log.close()
        print u'DONE!'

    def get_price_ids(self, item, apply_id):
        price_ids = []
        if not apply_id:
            price_ids.append(item.get_default_price_info()['id'])
        activity_ids = item.specialitem_set.filter(doctorseckillapply_id=apply_id).\
            values_list('special_id', flat=True)
        price_ids += list(item.serviceitemprice_set.filter(selling_rule__activity_id__in=activity_ids).values_list('id', flat=True))
        return price_ids
