#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   zhangxiaolin
#   E-mail  :   petelin1120@gmail.com
#   Date    :   17/10/30 19:27
#   Desc    :   ..df
import datetime
from django.core.management import BaseCommand
from django.db import transaction
from django.db.models import Sum
from gm_types.gaia import ORDER_STATUS

from api.models import BuDanSettlement, Order
from doctor.views.budan import get_all_doctors


class Command(BaseCommand):
    """if order related multiple diaries, delete the link, just keep one.
    """
    @transaction.atomic
    def handle(self, *args, **options):
        wait_save = []
        before_month_first_day = datetime.date.today().replace(month=9, day=1)
        current_month_first_day = datetime.date.today().replace(month=10, day=1)
        for settlement in BuDanSettlement.objects.filter(month_at=before_month_first_day):
            doctor_ids, user_ids = get_all_doctors(settlement.doctor)
            order_paid = Order.objects.filter(
                user_id__in=user_ids,
                status__in=(ORDER_STATUS.USED, ORDER_STATUS.SETTLED),
                validate_time__gte=before_month_first_day,
                validate_time__lt=current_month_first_day
            ).aggregate(total=Sum('discount'))['total'] or 0
            if order_paid > 0:
                order_ids = Order.objects.filter(
                    user_id__in=user_ids,
                    status__in=(ORDER_STATUS.USED, ORDER_STATUS.SETTLED),
                    validate_time__gte=before_month_first_day,
                    validate_time__lt=current_month_first_day
                ).values_list('id', flat=True)
                print("settlement: {} ,发现拍单: {} ,增加了 {} 元".format(settlement.id, order_ids, order_paid))
                settlement.alread_payment += order_paid
                settlement.balance += order_paid
                wait_save.append(settlement)

        raw_input("any key")
        for s in wait_save:
            s.save(update_fields=['alread_payment', 'balance'])
