# coding=utf-8
from __future__ import unicode_literals, absolute_import

import datetime
from django.db import models
from gm_types.gaia import MAIDAN_STATEMENT_STATUS
from api.models import Doctor, Person
from pay.manager.statement_manager import MaiDanHistoryStatementManager
from rpc.tool.generate_random_code import generate_num
from maidan.models.order import MaidanOrder


class MaidanStatement(models.Model):
    class Meta:
        verbose_name = u'买单对帐单'
        verbose_name_plural = u'买单对帐单'
        db_table = 'maidan_statement'
        app_label = 'maidan'
        unique_together = ('doctor', 'statement_date')

    id = models.CharField(max_length=15, verbose_name='对账单号', primary_key=True)
    doctor = models.ForeignKey(Doctor, verbose_name='对账对象医生')
    status = models.IntegerField(choices=MAIDAN_STATEMENT_STATUS, default=MAIDAN_STATEMENT_STATUS.CREATED)
    orders = models.ManyToManyField(MaidanOrder, verbose_name='关联买单订单', through='MaidanOrderStatementRelationship',
                                    related_name='statement')
    original_amount_cent = models.IntegerField(verbose_name='实际支付总额(分)', default=0)
    settle_amount_cent = models.IntegerField(verbose_name='结算金额(分)', default=0)

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name=u'最后一次修改时间')
    statement_date = models.IntegerField(verbose_name='对账年月', null=False)
    settle_snapshot = models.TextField(default='', verbose_name='财务打款时快照')
    operator = models.ForeignKey(Person, null=True, blank=True, verbose_name='对账者')
    # 发票计算专用，maidanorder.discount_cent/100的累加（元为单位）
    total_discount = models.FloatField(verbose_name='抽成总额', default=0)

    history_objects = MaiDanHistoryStatementManager()
    objects = models.Manager()

    @classmethod
    def create(cls, **data):
        data['id'] = generate_num(15)
        return cls.objects.create(**data)

    def settle(self, operator):
        self.orders.update(is_settled=True, settled_time=datetime.datetime.now())
        self.operator = operator
        self.status = MAIDAN_STATEMENT_STATUS.SETTLED
        self.save()

    @property
    def doctor_fee_cent(self):
        # 医生结算金额总和
        return self.orders.aggregate(doctor_fee_sum=models.Sum('doctor_discount_cent')).get('doctor_fee_sum') or 0

    @property
    def price_sum_cent(self):
        # 用户填写金额总和
        return self.orders.aggregate(price_sum=models.Sum('maidan_price_cent')).get('price_sum') or 0

    @property
    def order_count(self):
        # 已验证订单数
        return self.orders.count()

    @property
    def settle_amount(self):
        #结算金额，单位元
        return self.settle_amount_cent / 100


class MaidanOrderStatementRelationship(models.Model):
    class Meta:
        verbose_name = u'买单对帐单订单关系'
        verbose_name_plural = u'买单对帐单订单关系'
        db_table = 'maidan_orderstatementrelationship'
        app_label = 'maidan'

    statement = models.ForeignKey(MaidanStatement, verbose_name='关联买单对账单')
    order = models.OneToOneField(MaidanOrder, verbose_name='关联订单')
