# coding=utf-8
from django.core.management import BaseCommand
from django.db.models import Sum
from maidan.models import MaidanStatement
from maidan.models import MaidanOrder
from gm_types.gaia import MAIDAN_STATEMENT_STATUS


class Command(BaseCommand):
    """
    python manage.py update_20170303_fix_maidan_discont_create
    """
    def handle(self, *args, **kwargs):
        maidanstatement_log = open('买单结算单结算额修改_20170303.txt', 'a')
        maidanorder_log = open('买单订单抽成修改_20170303.txt', 'a')
        maidans = MaidanOrder.objects.all()
        for maidan in maidans:
            try:
                if maidan.is_settled:
                    maidan.settle_price_cent = maidan.doctor_discount_cent - maidan.discount_cent
                    maidan.save()
                else:
                    old_discount_cent = maidan.discount_cent
                    discount_rate = maidan.doctor.maidansetting.discount_rate
                    maidan.settle_price_cent = int(maidan.doctor_discount_cent * (100 - discount_rate)/10000.0) * 100
                    maidan.discount_cent = maidan.payment_cent - maidan.settle_price_cent
                    maidan.save()
                    message = u'maidan_id:{}, old_discount_cent:{}, new_discount_cent:{}\n'.format(
                        maidan.id, old_discount_cent, maidan.discount_cent)
                    maidanorder_log.writelines(message)
                print u'maidan:{}'.format(maidan.id)
            except Exception as e:
                print maidan.id, e.message

        print u'===================ORDER==DONE======================='

        statements = MaidanStatement.objects.filter(status=MAIDAN_STATEMENT_STATUS.CREATED)
        for statement in statements:
            try:
                old_settle_amount_cent = statement.settle_amount_cent
                settle_amount_cent = statement.orders.aggregate(t=Sum('settle_price_cent')).get('t')
                statement.settle_amount_cent = settle_amount_cent
                statement.save()
                message = u'maidanstatement_id:{}, old_settle_amount:{}, new_settle_amount:{}\n'.format(
                    statement.id, old_settle_amount_cent, statement.settle_amount_cent)
                maidanstatement_log.writelines(message)
                print u'statement:{}'.format(statement.id)
            except Exception as e:
                print statement.id, e.message
        print u'Done!!'
