# coding=utf-8

from django.core.management import BaseCommand
from django.db.models import Sum

from pay.models import StatementAll
from hippo.models.bill import BillApplyRecord
from rpc.tool.queryset_tool import big_qs_iter


class Command(BaseCommand):
    """
    python manage.py change_bill_payment
    修改发票的计算规则，美购预付款总额由实际预付款累加改为美购展示预付款累加
    """
    def handle(self, *args, **options):
        # 处理计算逻辑
        statements = StatementAll.objects.filter(statement_date__gt=201710)
        for sa in big_qs_iter(statements):
            total_real_prepay = sa.service_statement.orders.aggregate(
                total_real_prepay=Sum('servicesnapshot__pre_payment_price')
            ).get('total_real_prepay')
            if not total_real_prepay:
                total_real_prepay = 0
            sa.service_statement.total_real_prepay = total_real_prepay
            sa.service_statement.save(update_fields=['total_real_prepay'])
            print '{}:{}'.format(sa.id, total_real_prepay)
        print 'Statement Done!'

        # 处理现有开票记录
        bars = BillApplyRecord.objects.all()
        for bar in big_qs_iter(bars):
            amount = 0
            for re in big_qs_iter(bar.recordtoperiods.all()):
                total_real_prepay = re.statementall.service_statement.orders.aggregate(
                    total_real_prepay=Sum('servicesnapshot__pre_payment_price')
                ).get('total_real_prepay')
                if not total_real_prepay:
                    total_real_prepay = 0
                sub_amount = total_real_prepay + \
                             re.statementall.maidan_statement.original_amount_cent / 100 - re.statementall.total_settle_amount
                amount += sub_amount
            bar.amount = amount
            bar.save(update_fields=['amount'])
            print '{}:{}'.format(bar.id, amount)
        print 'Bill Done!'