# -*- coding: utf-8 -*-

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.utils.timezone import utc
from django.db.models import Q

from billing.models import Info, Record, Proof, Reckoning, RDetail

from datetime import timedelta, datetime
from utils.common import now
# from pprint import pprint


class Command(BaseCommand):

    help = u'reckoning generate'

    gathers = {}

    def handle(self, *args, **options):
        '''
            每月1日凌晨10分启动脚本
        '''
        if now().month == 1:
            self.period_year = now().year - 1
            self.period_month = 12
        else:
            self.period_year = now().year
            self.period_month = now().month - 1

        self.monthStart = datetime(self.period_year, self.period_month, 1).replace(tzinfo=utc)
        self.monthEnd = datetime(now().year, now().month, 1, 23, 59, 59).replace(tzinfo=utc) - timedelta(1)
        self.period = self.monthStart.strftime('%Y%m')

        # self.monthStart = datetime(2015, 9, 1)
        # self.monthEnd = datetime(2015, 9, 30, 23, 59, 59)
        # self.period = "201509"

        users = User.objects.all()
        for user in users:
            self._collect(user)

        self._autosave()

    def _collect(self, user):

        infos = Info.objects.filter((Q(closeTime=None) | Q(closeTime__gte=self.monthStart)), Q(user=user))
        for info in infos:
            records = Record.objects.filter(Q(info=info), Q(endTime__gte=self.monthStart))
            self._cal(records)

    def _cal(self, records):
        for record in records:
            proofs = Proof.objects.filter(Q(record=record), Q(createTime__gt=self.monthStart), Q(createTime__lte=self.monthEnd))
            for proof in proofs:
                self._summary(record.info.user, record.info.rid, record.info.rtype, proof.money)

    def _summary(self, user, rid, rtype, money):
        if rid in self.gathers:
            self.gathers[rid]['money'] += money
        else:
            self.gathers[rid] = {
                'user': user,
                'rid': rid,
                'rtype': rtype,
                'money': money
            }

    def _autosave(self):
        for g in self.gathers:
            reckoning = Reckoning.objects.filter(Q(user=self.gathers[g]['user']), Q(period=self.period))

            if reckoning:
                reckoning = reckoning.get()

                rdetail = RDetail.objects.filter(Q(reckoning=reckoning), Q(rid=self.gathers[g]['rid']))
                if rdetail:
                    rdetail = rdetail.get()

                    reckoning.money += (self.gathers[g]['money'] - rdetail.cost)

                    rdetail.cost = self.gathers[g]['money']
                    rdetail.save()
                else:

                    reckoning.money += self.gathers[g]['money']

                    rdetail = RDetail()
                    rdetail.reckoning = reckoning
                    rdetail.period = self.period
                    rdetail.rid = self.gathers[g]['rid']
                    rdetail.rtype = self.gathers[g]['rtype']
                    rdetail.cost = self.gathers[g]['money']
                    rdetail.save()

                reckoning.save()

            else:
                reckoning = Reckoning()
                reckoning.user = self.gathers[g]['user']
                reckoning.period = self.period
                reckoning.startTime = self.monthStart
                reckoning.endTime = self.monthEnd
                reckoning.money = self.gathers[g]['money']
                reckoning.createTime = now()
                reckoning.save()

                rdetail = RDetail()
                rdetail.reckoning = reckoning
                rdetail.period = self.period
                rdetail.rid = self.gathers[g]['rid']
                rdetail.rtype = self.gathers[g]['rtype']
                rdetail.cost = self.gathers[g]['money']
                rdetail.save()
