#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/3/29

from celery import shared_task
from datetime import datetime
from django.db.models import Sum, Q
from gm_types.gaia import BUDAN_TYPE, BUDAN_STATUS


from api.models.budan import BuDan
from hippo.models.merchant import Merchant
from api.models.bd_transfer import BDTransferMonth, BDTransferMonthToBudan


def bdtransfer_month_to_budan(day):
    q = Q(create_time__month=day.month, create_time__year=day.year) & \
        Q(budan_type=BUDAN_TYPE.TRANSFER_BUDAN) & \
        Q(status=BUDAN_STATUS.CREATED)

    for merchant in Merchant.objects.filter(is_online=True):
        merchant_q = Q(doctor_id=merchant.doctor_id) & q
        bd_queryset = BuDan.objects.filter(merchant_q)
        s_sum = lambda name: bd_queryset.aggregate(sum=Sum(name))['sum'] or 0

        bd, created = BDTransferMonth.objects.update_or_create(
            month_at=day,
            doctor_id=merchant.doctor_id,
            defaults={'total_amount': s_sum('extra_consume'), 'should_pay': s_sum('payment'), 'is_finished': True}
        )
        if bd.should_pay != bd.already_pay:
            bd.is_finished = False
            bd.save()

        for budan in bd_queryset:
            BDTransferMonthToBudan.objects.get_or_create(
                bdtransfermonth=bd, budan=budan
            )


@shared_task()
def init_bdtransfer_budan():
    bdtransfer_month_to_budan(datetime.now())