# coding=utf-8
# create by oldman at 2017/10/31
from django.db.models import Q
from django.db.models import Sum
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.trade import STATEMENT_STATUS, STATEMENT_OPERATION_TYPE

from hera.models import BackendGroup
from hippo.models import Merchant, MerchantAccount
from pay.models import OrderStatementRelationship
from pay.models.operation import StatementOperation
from pay.models.statementall import StatementAll, StatementAllOperation
from rpc.decorators import bind


class StatementAllDB(DataBuilder):
    def __init__(self, **kwargs):
        super(StatementAllDB, self).__init__(**kwargs)
        self._accounts = {}

    def get_account(self, obj):
        account = getattr(self._accounts, obj.id, None)
        if not account:
            account = obj.get_account()
            self._accounts[obj.id] = account
        return account

    def getval_city(self, obj):
        account = self.get_account(obj)
        return account and account.city.name

    def getval_province(self, obj):
        account = self.get_account(obj)
        return account and account.province.name

    def getval_bank(self, obj):
        account = self.get_account(obj)
        return account and account.bank

    def getval_subbranch(self, obj):
        account = self.get_account(obj)
        return account and account.subbranch

    def getval_account_name(self, obj):
        account = self.get_account(obj)
        return account and account.account_name

    def getval_account_number(self, obj):
        account = self.get_account(obj)
        return account and account.account_number

    def getval_account_is_change(self, obj):
        return obj.account_has_changed

    def getval_status_desc(self, obj):
        return STATEMENT_STATUS.getDesc(obj.status)

    def getval_id_operate(self, obj):
        return self.id

    def getval_id_detail(self, obj):
        return self.id

    def getval_id_log(self, obj):
        return self.id

    def getval_account_is_change(self, obj):
        return obj.account_has_changed


    def getval_doctor__d_merchant__is_freeze(self, obj):
        result = u'未冻结'
        if obj.doctor.d_merchant.is_freeze:
            result = u'已冻结'
        return result


    def getval_order_commission(self, obj):
        orders = OrderStatementRelationship.objects.filter(
            statement=obj.service_statement).order_by('-order__created_time')
        total = 0
        for order in orders:
            total += order.order.discount
        return total


    def getval_maidan_order_commission(self, obj):
        total = 0
        for item in obj.maidan_statement.orders.all():
            total += item.discount_cent / 100
        return total


    def getval_meiquan_amount(self, obj):
        orders = OrderStatementRelationship.objects.filter(
            statement=obj.service_statement).order_by('-order__created_time')
        total = 0
        for order in orders:
            servicesnapshot = order.order.servicesnapshot
            if servicesnapshot.coupon_info_id:
                total += servicesnapshot.coupon_gengmei_value
        return total


    def getval_service_point(self, obj):
        orders = OrderStatementRelationship.objects.filter(
            statement=obj.service_statement).order_by('-order__created_time')
        total = 0
        for order in orders:
            total += order.order.points_deduction
        return total


    def getval_info_update_time(self, obj):
        """
        判断打款状态
        :param obj:
        :return:
        """
        if obj.status == 6:
            updated_at = obj.updated_at
            doctor = obj.doctor
            try:
                merchant = Merchant.objects.get(doctor=doctor)
                merchant_account = MerchantAccount.objects.get(merchant_id=merchant.id)
            except:
                return ''
            update_time = merchant_account.update_time
            """
            比较资料更新时间和对账单修改时间
            """
            if update_time and update_time > updated_at:
                return update_time.strftime('%Y-%m-%d %H:%M:%S')
        return ''


@DB
class StatementAllDQ(DataSQLQuery):
    model = StatementAll
    data_model = StatementAllDB
    distinct = True

    def filter_doctor__name(self, srch_key, srch_val, regex=False):
        return Q(doctor__name__contains=srch_val)

    def filter_account_name(self, srch_key, srch_val, regex=False):
        return Q(Q(doctor__account__account_name__contains=srch_val) | Q(account__account_name__contains=srch_val))

    def filter_opuser(self, srch_key, srch_val, regex=False):
        is_staf = BackendGroup.objects.filter(members=srch_val, name='business').exists()
        if not is_staf:
            return Q()
        else:
            return Q(doctor__business_partener_id=srch_val)

    def filter_statement_date(self, srch_key, srch_val, regex=False):
        start = srch_val[0][:4] + srch_val[0][5:7]
        end = srch_val[1][:4] + srch_val[1][5:7]
        return Q(statement_date__gte=start) & Q(statement_date__lte=end)


class StatementAllOperationDB(DataBuilder):
    def getval_operator__user__last_name(self, obj):
        if obj.optype == STATEMENT_OPERATION_TYPE.CREATE:
            return u'系统'
        if obj.optype in [STATEMENT_OPERATION_TYPE.CHECK, STATEMENT_OPERATION_TYPE.REFUSE]:
            return obj.operator.user.doctor.name + u'医生'
        return obj.operator.user.last_name or obj.operator.user.username

    def getval_optype(self, obj):
        return STATEMENT_OPERATION_TYPE.getDesc(obj.optype)


class StatementAllOperationDQ(DataSQLQuery):
    model = StatementAllOperation
    data_model = StatementAllOperationDB



@bind('gaia/db/finance_statementall/query')
def finance_statementall_export(**kwargs):
    dqobj = StatementAllDQ()
    options = kwargs.get('options')
    return dqobj.process(**options)
