# coding=utf-8

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

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


class Command(BaseCommand):
    """
    python manage.py change_bill_cal
    修改发票的计算规则，发票金额=对账单中的抽成金额-对账单中的补扣款项（补款为正，扣款为负）
    """
    def handle(self, *args, **options):
        # 处理计算逻辑
        statements = StatementAll.objects.all()
        for sa in big_qs_iter(statements):
            st_discount = sa.service_statement.orders.aggregate(
                total_discount=Sum('discount')
            ).get('total_discount') or 0
            mt_discount = sa.maidan_statement.orders.aggregate(
                total_discount=Sum('discount_cent')
            ).get('total_discount') or 0
            mt_discount = mt_discount / 100
            sa.service_statement.total_discount = st_discount
            sa.maidan_statement.total_discount = mt_discount
            sa.service_statement.save(update_fields=['total_discount'])
            sa.maidan_statement.save(update_fields=['total_discount'])
            print '{}:{}:{}'.format(sa.id, st_discount, mt_discount)
        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()):
                fda = FeeDeductionAll.objects.filter(statementall_id=re.statementall_id)
                total_deduction = fda.aggregate(
                    total_deduction=Sum('value')
                ).get('total_deduction') or 0
                st_discount = re.statementall.service_statement.total_discount or 0
                mt_discount = re.statementall.maidan_statement.total_discount or 0
                sub_amount = st_discount + mt_discount + total_deduction
                amount += sub_amount
            bar.amount = amount
            bar.save(update_fields=['amount'])
            print '{}:{}'.format(bar.id, amount)
        print 'Bill Done!'