# -*- coding: UTF-8 -*-

from django.core.management import BaseCommand
import tablib
import datetime
from api.models import *
from rpc.tool.queryset_tool import big_qs_iter
from doctor.tool.service_tool import count_pre_payment
from gm_types.gaia import SERVICE_SELL_TYPE


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--update', action='store_true', default=False)

    def handle(self, *args, **options):
        do_update = options['update']
        now_t = datetime.datetime.now()
        dt = tablib.Dataset()
        dt.headers = [
            'service_id', 'sku_id', 'price_id', 'gengmei_price',
            'old_prepay', 'old_discount', 'old_self_support_discount',
            'new_prepay', 'new_discount', 'new_self_support_discount',
        ]

        qs = ServiceItemPrice.objects.filter(
                gengmei_price__lte=500, is_enable=True, service_item__is_delete=False,
                service_item__service__service_type=SERVICE_SELL_TYPE.NORMAL,
            )  # .exclude(service_item__service__end_time__lt=now_t)
        cnt = qs.count()
        i = 0
        for p in big_qs_iter(qs):
            i += 1
            print u'(%s/%s) service: %s, sku: %s, price: %s' % (
                i, cnt, p.service_item.service.id, p.service_item.id, p.id
            )
            price = p.gengmei_price
            old_prepay = p.pre_payment_price
            old_discount = p.discount
            old_self_support_discount = p.self_support_discount

            pinfo = count_pre_payment(price)
            new_prepay = pinfo['pre_payment_price_int']
            new_prepay_percent = pinfo['pre_payment_price']
            new_discount = pinfo['discount']
            new_self_support_discount = old_self_support_discount

            dt.append([
                p.service_item.service.id, p.service_item.id, p.id, price,
                old_prepay, old_discount, old_self_support_discount,
                new_prepay, new_discount, new_self_support_discount,
            ])

            if do_update:
                print '  gengmei_price: %s | before: %s, %s | after: %s, %s' % (
                    price, old_prepay, old_discount, new_prepay, new_discount,
                )
                p.service_item.update_price(
                    p.id,
                    pre_payment_price=new_prepay,
                    discount=new_discount,
                )
                if p.is_default_price:
                    ServiceRegisterItem.objects.filter(
                        serviceitem=p.service_item
                    ).update(
                        pre_payment_price=new_prepay_percent,
                        pre_payment_price_int=new_prepay,
                        discount=new_discount,
                    )

        open('/tmp/change_price_rule.xlsx', 'wb').write(dt.xlsx)
