#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   zhangxiaolin
#   E-mail  :   petelin1120@gmail.com
#   Date    :   17/9/28 11:40
#   Desc    :   迁移之前的补单结算单到新的模型, 从一个医生最开始有补单结算单开始, 以后每个月都需要创建, 以使得其balance连续.
import datetime

from django.core.management import BaseCommand
from django.db.models import Min
from gm_types.gaia import BUDAN_SETTLEMENT_STATUS, BUDAN_STATUS
from dateutil import relativedelta

from api.models import BuDanSettlement
from rpc.tool.log_tool import logging_exception


class Command(BaseCommand):
    def __init__(self):
        super(Command, self).__init__()
        # 之前已10月之前的数据, 保证10月分上线.
        self.stop_month_at = datetime.date(year=2017, month=9, day=1)

    def do_one_doctor(self, doctor_id, min_month_at):
        month_at = min_month_at
        balance = 0
        while month_at <= self.stop_month_at:
            try:
                settlement = BuDanSettlement.objects.get(doctor_id=doctor_id, month_at=month_at)
            except BuDanSettlement.DoesNotExist:
                settlement = BuDanSettlement.objects.create(doctor_id=doctor_id, month_at=month_at,
                                                            status=BUDAN_SETTLEMENT_STATUS.PAY_SUCCESS)
                if balance < 0:
                    settlement.payment += -balance
            else:
                origin_payment = settlement.payment
                if balance < 0:
                    settlement.payment += -balance
                if settlement.status == BUDAN_SETTLEMENT_STATUS.PAY_SUCCESS:
                    settlement.alread_payment += origin_payment
                elif settlement.status == BUDAN_SETTLEMENT_STATUS.NOT_PAY:
                    balance += -origin_payment
            settlement.status = BUDAN_SETTLEMENT_STATUS.PAY_SUCCESS
            settlement.balance = balance
            settlement.save(update_fields=('payment', 'balance', 'alread_payment', 'status'))

            settlement.items.update(status=BUDAN_STATUS.CREATE_SETTLEMENT)

            month_at = month_at + relativedelta.relativedelta(months=+1)

    def handle(self, *args, **options):
        doctor_min_month = BuDanSettlement.objects.values('doctor').annotate(min_month_at=Min('month_at'))

        success = fail = 0
        for item in doctor_min_month:
            doctor_id, min_month_at = item['doctor'], item['min_month_at']
            try:
                self.do_one_doctor(doctor_id, min_month_at)
                success += 1
            except:
                logging_exception()
                fail += 1
        print "SUCCESS, FAIL:", success, fail
