# coding=utf-8
# create by oldman at 2017/11/3
import datetime
import json

from django.db import transaction
from gm_types.doctor import DOCTOR_BILLAPPLY_STATUS

from hera.queries.billapplyrecord import BillApplyRecordDQ
from hera.queries.doctorfinanceinfo import DoctorFinanceInfoDQ
from hippo.models.bill import DoctorFinanceInfo, BillApplyRecord, BillIdToBillApply
from rpc.decorators import bind_context
from rpc.cache import billapplyrecord_cache, req_data_cache
from rpc.tool.queryset_tool import queryset_dec
from api.tasks.export_excel_task import export_bdtransfermonth_support_excel, export_bdtransfermonthlywithdrawal_support_excel
from api.tasks.bill_tasks import export_bill_excel_task
from hera.queries.bill_bdtransfer import BDTransferMonthDQ
from hera.utils import get_business_team
from django.db.models import Q

uri_pre = 'hera/bill/'


@bind_context(uri_pre + 'query')
def query(ctx, options):
    dtobj = BillApplyRecordDQ()
    billapplyrecord_cache.set('{}:billapplyrecord'.format(ctx.session.user_id), json.dumps(options))
    return dtobj.process(**options)


@bind_context(uri_pre + 'invoice_query')
def query(ctx, options):
    dtobj = DoctorFinanceInfoDQ()
    return dtobj.process(**options)


@bind_context(uri_pre + 'invoice_get')
def invoice_get(ctx, financeinfo_id):
    """
    获取医生的财务信息
    :param ctx:
    :param financeinfo_id:
    :return:
    """
    doctorfinanceinfo = DoctorFinanceInfo.objects.get(id=financeinfo_id)
    return doctorfinanceinfo.get_info()


@bind_context(uri_pre + 'invoice_edit')
def invoice_edit(ctx, financeinfo_id, data):
    """
    修改医生的财务信息
    :param ctx:
    :param financeinfo_id:
    :param data:
    :return:
    """
    financeInfo = DoctorFinanceInfo.objects.get(id=financeinfo_id)
    for key, value in data.iteritems():
        setattr(financeInfo, key, value)
    financeInfo.save()


@bind_context(uri_pre + 'review')
def bill_review(ctx, bill_id, data):
    """
    审核发票申请
    :param ctx:
    :param bill_id:
    :param data:
    :return:
    """
    bill = BillApplyRecord.objects.get(id=bill_id)
    if data['is_pass']:
        bill.status = DOCTOR_BILLAPPLY_STATUS.SUCCESS
        bill.bill_time = datetime.datetime.now()
    else:
        bill.status = DOCTOR_BILLAPPLY_STATUS.REJECT
        bill.reason = data['reason']
        bill.more_reason = data['self_define_reason']  # 自定义原因
    bill.save()


@bind_context(uri_pre + 'add_bills')
def add_bills(ctx, bill_id, bills):
    """
    添加发票编号
    :param ctx:
    :param bill_id:
    :param bills:
    :return:
    """
    with transaction.atomic():
        [BillIdToBillApply.objects.get_or_create(billapplyrecord_id=bill_id,
                                                 bill_id=item) for item in bills]


@bind_context(uri_pre + 'add_express')
def add_express(ctx, bill_id, express_id, express_company):
    """
    添加快递信息
    :param ctx:
    :param bill_id:
    :param express_id:
    :param express_company:
    :return:
    """
    bill = BillApplyRecord.objects.get(id=bill_id)
    bill.express_company = express_company
    bill.express_id = express_id
    bill.save()


@bind_context(uri_pre + 'set_bill_list_success')
def add_express(ctx, bill_ids):
    """
    批量标记发票申请记录成功
    :param bill_ids:
    :param ctx:
    :return:
    """
    with transaction.atomic():
        for item in bill_ids:
            bill = BillApplyRecord.objects.get(id=item)
            if bill.status == DOCTOR_BILLAPPLY_STATUS.PENDING:
                bill.status = DOCTOR_BILLAPPLY_STATUS.SUCCESS
                bill.bill_time = datetime.datetime.now()
                bill.save()


@bind_context(uri_pre + 'export_excel')
def export_excel(ctx, bill_ids, excel_type, is_all, category):
    """
    导出发票信息
    :param ctx:
    :return:
    """
    user = ctx.session.user
    if is_all:
        dqobj = BillApplyRecordDQ()
        options = json.loads(billapplyrecord_cache.get('{}:billapplyrecord'.format(ctx.session.user_id)))
        options.pop('paging')
        options.pop('columns')
        bill_ids = list(dqobj.build_queryset(**options).values_list('id', flat=True))
    export_bill_excel_task.delay(bill_ids, excel_type, category, user.email)

@bind_context(uri_pre + 'bdtransfermonth_query')
def bdtransfermonth_query(ctx, options):
    init_q = None
    _in, businessman_list, team_groups = get_business_team(ctx)
    if _in:
        init_q = Q(doctor__business_partener__in=businessman_list) | Q(doctor__business_group__in=team_groups)
    req_data_cache.set(ctx.session.session_key + 'bdtransfermonth', json.dumps(options))
    dqobj = BDTransferMonthDQ(init_q=init_q)
    return dqobj.process(**options)


@bind_context(uri_pre + 'bdtransfermonth_excel_export')
def bdtransfermonth_excel_export(ctx):
    """
    导出转诊补单管理
    :param ctx:
    :return:
    """
    init_q = Q()
    _in, businessman_list, team_groups = get_business_team(ctx)
    if _in:
        init_q = Q(doctor__business_partener__in=businessman_list) | Q(doctor__business_group__in=team_groups)
    dqobj = BDTransferMonthDQ(init_q=init_q)
    options = json.loads(req_data_cache.get(ctx.session.session_key + 'bdtransfermonth'))
    options.pop('paging')
    options.pop('columns')
    datas = dqobj.build_queryset(**options)
    export_bdtransfermonth_support_excel.delay(queryset_dec(datas, need_instant_data=True), ctx.session.user)

@bind_context(uri_pre + 'bdtransfermonth_query_v2')
def bdtransfermonth_query(ctx, options):
    req_data_cache.set(ctx.session.session_key + 'bdtransfermonthly', json.dumps(options))
    dqobj = BDTransferMonthDQ()
    return dqobj.process(**options)

@bind_context(uri_pre + 'bdtransfermonthlywithdrawal_excel_export')
def bdtransfermonthlywithdrawal_excel_export(ctx):
    """
    导出转诊跨月撤销
    :param ctx:
    :return:
    """
    dqobj = BDTransferMonthDQ()
    options = json.loads(req_data_cache.get(ctx.session.session_key + 'bdtransfermonthly'))
    options.pop('paging')
    options.pop('columns')
    datas = dqobj.build_queryset(**options)
    export_bdtransfermonthlywithdrawal_support_excel.delay(queryset_dec(datas, need_instant_data=True), ctx.session.user)
