# 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))
        specialitem_list = SpecialItem.objects.filter(special_id__in=list_special_ids)
        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():
                    row_refund_anytime = []
                    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')
                                    serviceitem.pre_payment_price = serviceitem_old.get('pre_payment_price')
                                    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)
                                    # refund_anytime = specialitem.service.refund_anytime
                                    # specialitem.service.refund_anytime = False
                                    # specialitem.service.save()
                                    # row_refund_anytime.append(specialitem.service.id)
                                    # row_refund_anytime.append(refund_anytime)
                                    # row_refund_anytime.append(specialitem.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_add.xlsx'.format(month, day), 'wb').write(dt_result.xlsx)
        # open(u'/data/11_11/{}_{}_refund_anytime_result_modify_add.xlsx'.format(month, day), 'wb').write(
        #     dt_service_refund_anytime.xlsx)
        print(u'修改成功!')
        print (u'开始修改美购是否支持随时退款!')
        file_name = '/data/11_11/11_{}_refund_anytime_result_modify.xlsx'.format(int(day) - 1)
        wb_anytime = load_workbook(filename=file_name)
        sheetnames_anytime = wb_anytime.get_sheet_names()
        if sheetnames_anytime == 0:
            return
        ws_anytime = wb_anytime.get_sheet_by_name(sheetnames_anytime[0])
        dt_service_refund_anytime_end = tablib.Dataset()
        dt_service_refund_anytime_end.headers = [u'美购ID', u'是否支持随时返现', u'是否支持随时返现(修改后)']

        for rx in range(2, ws_anytime.get_highest_row() + 1):
            try:
                refund_anytime_end = []
                service = Service.objects.get(id=int(ws_anytime.cell(row=rx, column=1).value))
                old_refund = service.refund_anytime
                print ws_anytime.cell(row=rx, column=2).value
                service.refund_anytime = (ws_anytime.cell(row=rx, column=2).value == 'True')
                service.save()
                refund_anytime_end.append(service.id)
                refund_anytime_end.append(old_refund)
                refund_anytime_end.append(service.refund_anytime)
                dt_service_refund_anytime_end.append(refund_anytime_end)
            except Exception as e:
                print e.message
                continue
        open(u'/data/11_11/{}_{}_refund_anytime_result_end.xlsx'.format(month, day), 'wb').write(
            dt_service_refund_anytime_end.xlsx)
