# coding=utf-8
import datetime
import tablib
from django.core.management import BaseCommand
from django.db import transaction
from openpyxl import load_workbook, Workbook
from openpyxl.writer.excel import ExcelWriter

from api.models import Service
from api.models import ServiceItem, SpecialItem


def get_services():
    wb = load_workbook(filename='/data/11_11/service.xlsx')
    sheetnames = wb.get_sheet_names()
    if sheetnames == 0:
        return
    ws = wb.get_sheet_by_name(sheetnames[0])
    dict_service = {}
    for rx in range(3, ws.get_highest_row()+1):
        try:
            serviceitem_id = int(ws.cell(row=rx, column=3).value)
            serviceitem = ServiceItem.objects.get(id=serviceitem_id)
            if serviceitem.service.id not in dict_service:
                dict_service[serviceitem.service.id] = []
            dict_service[serviceitem.service.id].append(
                {
                    'serviceitem_id': serviceitem_id,
                    'gengmei_price': int(ws.cell(row=rx, column=5).value),
                    'pre_payment_price': int(ws.cell(row=rx, column=6).value),
                    'discount': int(ws.cell(row=rx, column=7).value),
                    'cash_back_fee': int(ws.cell(row=rx, column=8).value),
                    'refund_anytime': bool(ws.cell(row=rx, column=9).value),
                    'gengmei_price_new': int(ws.cell(row=rx, column=10).value),
                    'pre_payment_price_new': int(ws.cell(row=rx, column=11).value),
                    'refund_anytime': serviceitem.service.refund_anytime
                }
            )
        except Exception as e:
            print e.message
            continue
    print u'数据读取完毕'
    print dict_service.keys()
    return dict_service


class Command(BaseCommand):
    """
    python manage.py change_price_1111_1  special_id
    """

    def add_arguments(self, parser):
        parser.add_argument('special_id', nargs='+', type=int)

    def handle(self, *args, **options):
        list_special_ids = []
        for opt in options['special_id']:
            list_special_ids.append(int(opt))
        print list_special_ids
        specialitem_list = SpecialItem.objects.filter(special_id__in=list_special_ids)
        services_ids = SpecialItem.objects.filter(special_id__in=list_special_ids).values_list('service_id', flat=True)
        dt_service_refund_anytime = tablib.Dataset()
        dt_service_refund_anytime.headers = [u'美购ID', u'是否支持随时返现', u'是否支持随时返现(修改后)']

        dt_result = tablib.Dataset()
        dt_result.headers = [u'美购ID', u'美购名称', u'多属性ID', u'多属性名称', u'更美价', u'预付款', u'抽成', u'返现', u'美购是否支持随时退款',
                             u'修改后的更美价', u'修改后的预付款']

        dict_service = get_services()
        print dict_service
        print u'开始处理!'
        for specialitem in specialitem_list:
            try:
                with transaction.atomic():
                    if specialitem.service.id in dict_service:
                        service_data = dict_service.get(specialitem.service.id)
                        print service_data

                        for serviceitem in specialitem.service.items.filter(is_delete=False):
                            for serviceitem_old in service_data:
                                print serviceitem_old
                                if serviceitem.id == serviceitem_old.get('serviceitem_id'):
                                    row_service_item = []
                                    gengmei_price_old = serviceitem.gengmei_price
                                    pre_payment_price_old = serviceitem.pre_payment_price
                                    serviceitem.gengmei_price = serviceitem_old.get('gengmei_price_new')
                                    serviceitem.pre_payment_price = serviceitem_old.get('pre_payment_price_new')
                                    serviceitem.save()
                                    row_service_item.append(specialitem.service.id)
                                    row_service_item.append(specialitem.service.name)
                                    row_service_item.append(serviceitem.id)
                                    row_service_item.append(''.join(serviceitem.items_name))
                                    row_service_item.append(gengmei_price_old)
                                    row_service_item.append(pre_payment_price_old)
                                    row_service_item.append(serviceitem.discount)
                                    row_service_item.append(serviceitem.cash_back_fee)
                                    row_service_item.append(specialitem.service.refund_anytime)
                                    row_service_item.append(serviceitem.gengmei_price)
                                    row_service_item.append(serviceitem.pre_payment_price)
                                    dt_result.append(row_service_item)

            except Exception as e:
                print e.message
                continue
        for service_id in services_ids:
            try:
                print service_id
                row_refund_anytime = []
                service = Service.objects.get(pk=service_id)
                refund_anytime_old = service.refund_anytime
                service.refund_anytime = False
                service.save()
                row_refund_anytime.append(service.id)
                row_refund_anytime.append(refund_anytime_old)
                row_refund_anytime.append(service.refund_anytime)
                dt_service_refund_anytime.append(row_refund_anytime)
            except Exception as e:
                print e.message
                continue

        current = datetime.datetime.now()
        month = current.month
        day = current.day
        open(u'/data/11_11/{}_{}_price_result_modify.xlsx'.format(month, day), 'wb').write(dt_result.xlsx)
        open(u'/data/11_11/{}_{}_refund_anytime_result_modify.xlsx'.format(month, day), 'wb').write(
            dt_service_refund_anytime.xlsx)
        print(u'修改成功!')
