#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   RobertDing
#   E-mail  :   robertdingx@gmail.com
#   Date    :   17/06/29 20:04:57
#   Desc    :   pos机相关
#

from django.db.models import Model, Q
from django.db.models import ForeignKey, CharField, DateTimeField
from django.db.models import FloatField, DateField

from api.models import Doctor


class POSMachine(Model):
    class Meta:
        verbose_name = u'pos机终端绑定关系'
        db_table = 'api_posmachine'
        app_label = 'api'

    doctor = ForeignKey(Doctor, related_name='pos')
    code = CharField('终端号', max_length=64, unique=True, default=None)
    update_time = DateTimeField(auto_now=True)
    create_time = DateTimeField(auto_now_add=True)


class POSRecord(Model):
    class Meta:
        verbose_name = u'pos机结算记录'
        db_table = 'api_posrecord'
        app_label = 'api'

    doctor = ForeignKey(Doctor, related_name='posrecords')
    pay_code = CharField('交易唯一id', unique=True, max_length=100)
    amount = FloatField('金额')
    record_time = DateTimeField('快钱记录生成时间', db_index=True)
    create_time = DateTimeField(auto_now_add=True)


class POSSum(Model):
    class Meta:
        verbose_name = u'pos机结算记录总数'
        db_table = 'api_posrecord_sum'
        app_label = 'api'

    doctor = ForeignKey(Doctor, related_name='possum')
    day = DateField()
    amount = FloatField('当天回款总额', default=0.0)
    create_time = DateTimeField(auto_now_add=True)


    @classmethod
    def sum_pos_back(cls, doctor_ids, last_month_dt):
        time_query = Q(day__gte=last_month_dt.get_first_day_month()) & Q(day__lte=last_month_dt.get_last_day_month())
        records = cls.objects.filter(time_query, doctor_id__in=doctor_ids)
        return sum([x.amount for x in records])
