# coding: utf-8
import time
import itertools
import operator
from datetime import datetime
from rpc.decorators import bind
from api.models import Q
from api.models import BDTransferMonth
from api.models import BDTransferApplyRecord
from api.models import BDTransferToBudan

uri_pre = 'hera/finance/'


@bind(uri_pre + 'budan_manager')
def get_budan_manager(doctor_ids=None, doctor_name=None,
                      start_time=None, end_time=None,
                      is_finished=None, pre_id=None, next_id=None,
                      limit=21):
    """
    财务转诊补单相关
    :param doctor_id: 商户ID
    :param doctor_name: 商户名称
    :param start_time: 开始时间
    :param end_time: 结束时间
    :param is_finished: 佣金补交状态
    :param pre_id: 分页 上一页
    :param last_id: 分页 下一页
    :return:
    """
    result = list()
    q_list = Q()
    if pre_id is not None:
        q_list.add(Q(id__lt=pre_id), Q.AND)
    if next_id is not None:
        q_list.add(Q(id__gt=next_id), Q.AND)
    if is_finished is not None:
        q_list.add(Q(is_finished=is_finished), Q.AND)
    if doctor_ids and len(doctor_ids) > 0:
        q_list.add(Q(doctor__id__in=doctor_ids), Q.AND)
    if doctor_name and len(doctor_name) > 0:
        q_list.add(Q(doctor_name=doctor_name), Q.AND)
    if start_time and len(start_time) > 0:
        format_start_time = datetime.strptime('{} {}'.format(start_time, '00:00:00'), "%Y-%m-%d %H:%M:%S")
        q_list.add(Q(month_at__gte=format_start_time), Q.AND)
    if end_time and len(end_time) > 0:
        format_end_time = datetime.strptime('{} {}'.format(end_time, '23:59:59'), "%Y-%m-%d %H:%M:%S")
        q_list.add(Q(month_at__lte=format_end_time), Q.AND)

    data = list()
    if len(q_list) > 0:
        query_filter = BDTransferMonth.objects.\
            values('id', 'doctor__id', 'doctor__name', 'month_at',
                   'total_amount', 'should_pay', 'already_pay', 'is_finished',
                   'created_time'
                   )\
            .filter(q_list).order_by('-month_at')[:limit]
        data = list(query_filter)
    for item in data:
        result.append({
            'id': item.get('id'),
            'doctor_id': item.get('doctor__id'),
            'doctor_name': item.get('doctor__name'),
            'month_at': item.get('month_at').strftime('%Y-%m-%d'),
            'total_amount': item.get('total_amount', 0),
            'should_pay': item.get('should_pay', 0),
            'already_pay': item.get('already_pay', 0),
            'is_finished': item.get('is_finished'),
            'created_time': time.mktime(item.get('created_time').timetuple())  # 时间转换时间戳
        })
    return result


@bind(uri_pre + 'commission_manager')
def get_commission_manager(doctor_ids=None,
                           applyrecord_ids=None,
                           applay_time_start=None,
                           applay_time_end=None,
                           success_time_start=None,
                           success_time_end=None,
                           merchant_name=None,
                           merchant_id=None,
                           status=None,
                           pre_id=None,
                           next_id=None,
                           limit=21):
    """
    财务转诊佣金相关
    :param doctor_ids: 商户ID
    :param applyrecord_ids: 佣金补交单ID
    :param applay_time_start: 申请开始时间
    :param applay_time_end: 申请结束时间
    :param success_time_start: 成功开始时间
    :param success_time_end: 成功结束时间
    :param status: 状态
    :param pre_id: 上一页
    :param next_id: 下一页
    :param limit: 分页条数
    :return:
    """
    result = list()
    q_list = Q()

    if applyrecord_ids:
        q_list.add(Q(id__in=applyrecord_ids), Q.AND)
    if doctor_ids and len(doctor_ids) > 0:
        q_list.add(Q(doctor__id__in=doctor_ids), Q.AND)

    if applay_time_start and len(applay_time_start) > 0:
        format_applay_time_start = datetime.strptime('{} {}'.format(applay_time_start, '00:00:00'),
                                                     "%Y-%m-%d %H:%M:%S")
        q_list.add(Q(created_time__gte=format_applay_time_start), Q.AND)
    if applay_time_end and len(applay_time_end) > 0:
        format_applay_time_end = datetime.strptime('{} {}'.format(applay_time_end, '23:59:59'), "%Y-%m-%d %H:%M:%S")
        q_list.add(Q(created_time__lte=format_applay_time_end), Q.AND)

    if success_time_start and len(success_time_start) > 0:
        format_success_time_start = datetime.strptime('{} {}'.format(success_time_start, '00:00:00'),
                                                      "%Y-%m-%d %H:%M:%S")
        q_list.add(Q(pass_time__gte=format_success_time_start), Q.AND)
    if success_time_end and len(success_time_end) > 0:
        format_success_time_end = datetime.strptime('{} {}'.format(success_time_end, '23:59:59'), "%Y-%m-%d %H:%M:%S")
        q_list.add(Q(pass_time__lte=format_success_time_end), Q.AND)

    if status:
        q_list.add(Q(status__in=status), Q.AND)

    if merchant_id:
        q_list.add(Q(doctor__d_merchant__id=merchant_id), Q.AND)

    if merchant_name:
        q_list.add(Q(doctor__d_merchant__name=merchant_name), Q.AND)
    if pre_id:
        q_list.add(Q(id__gt=pre_id), Q.AND)
    if next_id:
        q_list.add(Q(id__lte=next_id), Q.AND)

    if q_list:
        query_filter = BDTransferApplyRecord.objects.filter(q_list).values(
            'id', 'pass_time', 'created_time', 'total_amount', 'should_pay',
            'status', 'bdtransfermonth_id', 'doctor__id', 'doctor__name',
            'doctor__d_merchant__id', 'doctor__d_merchant__name'
        ).order_by('-id')[:limit]
        data = list(query_filter)
    else:
        query_filter = BDTransferApplyRecord.objects.filter().values(
            'id', 'pass_time', 'created_time', 'total_amount', 'should_pay',
            'status', 'bdtransfermonth_id', 'doctor__id', 'doctor__name',
            'doctor__d_merchant__id', 'doctor__d_merchant__name'
        ).order_by('-id')[:limit]
        data = list(query_filter)
    if data:
        for item in data:
            result.append({
                'applyrecord_id': item.get('id'),
                'pass_time': item.get('pass_time').strftime("%Y-%m-%d %H:%M:%S") if item.get('pass_time') else '',
                'created_time': item.get('created_time').strftime("%Y-%m-%d %H:%M:%S") if item.get('created_time') else '',
                'total_amount': item.get('total_amount', 0),
                'should_pay': item.get('should_pay', 0),
                'status': item.get('status'),
                'bdtransfermonth_id': item.get('bdtransfermonth_id'),
                'merchant_name': item.get('doctor__d_merchant__name'),
                'merchant_id': item.get('doctor__d_merchant__id')
            })
    return result


@bind(uri_pre + 'get_applayrecord_ids_by_budan_id')
def get_applayrecord_ids_by_budan_id(budan_id=None):
    """
    通过补单ID获取佣金补交记录
    :param bdtransfer_id:
    :return:
    """
    result = list()
    if budan_id:
        data = BDTransferToBudan.objects.values('bdtransferapplyrecord__id', 'budan__id').filter(budan__id=budan_id)
        result = list(set(item.get('bdtransferapplyrecord__id') for item in data))
    return result


@bind(uri_pre + 'get_budan_ids_by_record_ids')
def get_budan_ids_by_record_ids(record_ids=None):
    """
    通过佣金补交记录获取转诊ID
    :param record_ids:
    :return:
    """
    result = dict()
    if record_ids in (None, '', []):
        return result
    if record_ids:
        data = BDTransferToBudan.objects.values('bdtransferapplyrecord__id', 'budan__id').\
            filter(bdtransferapplyrecord__id__in=record_ids)\
            .order_by('-bdtransferapplyrecord__id')
        for k, g in itertools.groupby(data, key=operator.itemgetter('bdtransferapplyrecord__id')):
            result.update({
                k: list(item.get('budan__id') for item in g)
            })
    return result


@bind(uri_pre + 'get_applay_month_at')
def get_applay_month_at(bdtransfermonth_ids=None):

    """ 
    :param bdtransfermonth_ids: 
    :return: 
    """
    result = {}
    if bdtransfermonth_ids:
        data = BDTransferMonth.objects.values('id', 'month_at').filter(id__in=bdtransfermonth_ids)
        for item in data:
            result.update({
                item.get('id'): item.get('month_at').strftime("%Y-%m")
            })
    return result


