# coding=utf-8
from django.db.models import Sum

from api.models.bd_transfer import BDTransferMonth, BDTransferApplyRecord, BDTransferToBudan, BuDan
from gm_types.doctor import BDTRANSFER_APPLY_STATUS, BDTRANSFER_PIC_TYPE
from rpc.decorators import bind_context
from hippo.tool.user_tool import get_doctor_from_context
from rpc.tool.error_code import CODES, gen


@bind_context('doctor/bdtransfer/list', login_required=True)
def BDTransferList(ctx, year):
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        gen(CODES.DOCTOR_NOT_FOUND)
    bdtms = BDTransferMonth.objects.filter(doctor_id=doctor.id, month_at__year=year)
    return [{
        "id": bdtm.id,
        "month": str(bdtm.month_at)[:7],
        "total_amount": bdtm.total_amount,
        "should_pay": bdtm.should_pay,
        "already_pay": bdtm.already_pay,
        "has_paid": bdtm.is_finished,
        "transfer_sum": bdtm.month_budans.count()
    } for bdtm in bdtms]


@bind_context('doctor/bdtransfer/apply/list', login_required=True)
def BDTransferApplyList(ctx, bdm_id):
    def get_status(budan_id):
        re = BDTransferToBudan.objects.filter(budan_id=budan.budan_id).order_by('-id').first()
        if re:
            return re.bdtransferapplyrecord.status
        else:
            return 1

    doctor = get_doctor_from_context(ctx)
    if not doctor:
        gen(CODES.DOCTOR_NOT_FOUND)
    bdtm = BDTransferMonth.objects.get(id=bdm_id)
    if bdtm.doctor.id != doctor.id:
        gen(CODES.NO_PERMISSION)
    data = {
        "month": str(bdtm.month_at)[0:7],
        "total_amount": bdtm.total_amount,
        "transfer_sum": bdtm.month_budans.count(),
        "should_pay": bdtm.should_pay,
        "already_pay": bdtm.already_pay
    }
    budans = [{
        "id": budan.budan.id,
        "total_amount": budan.budan.extra_consume,
        "should_pay": budan.budan.payment,
        "status": get_status(budan.budan_id)
    } for budan in bdtm.month_budans.all()]
    data['budans'] = budans
    return data


@bind_context('doctor/bdtransfer/apply', login_required=True)
def BDTransferApplyList(ctx, bdm_id, budan_ids, proof_of_payments, authorization_vouchers):
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        gen(CODES.DOCTOR_NOT_FOUND)
    bd_data = BuDan.objects.filter(id__in=budan_ids).aggregate(
        total_amount=Sum('extra_consume'), should_pay=Sum('payment')
    )
    ba = BDTransferApplyRecord.objects.create(
        total_amount=bd_data['total_amount'] or 0,
        should_pay=bd_data['should_pay'] or 0,
        doctor=doctor,
        bdtransfermonth_id=bdm_id
    )
    ba.update_pics(BDTRANSFER_PIC_TYPE.PROOF_OF_PAYMENT, proof_of_payments)
    ba.update_pics(BDTRANSFER_PIC_TYPE.AUTHORIZATION_VOUCHER, authorization_vouchers)
    for id in budan_ids:
        BDTransferToBudan.objects.create(
            bdtransferapplyrecord_id=ba.id,
            budan_id=id
        )
    return {'success': True}


@bind_context('doctor/bdtransfer/record', login_required=True)
def BDTransferRecordList(ctx, bdm_id):
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        gen(CODES.DOCTOR_NOT_FOUND)
    bdtm = BDTransferMonth.objects.get(id=bdm_id)
    if bdtm.doctor.id != doctor.id:
        gen(CODES.NO_PERMISSION)
    records = BDTransferApplyRecord.objects.filter(doctor_id=doctor.id, bdtransfermonth_id=bdm_id)
    data = {
        "month": str(bdtm.month_at)[0:7],
        "total_amount": bdtm.total_amount,
        "should_pay": bdtm.should_pay,
        "already_pay": bdtm.already_pay,
        "transfer_sum": bdtm.month_budans.count()
    }
    bdtransfer_list = [{
        "id": record.id,
        "budan_ids": list(record.record_budans.values_list('budan_id', flat=True)),
        "should_pay": record.should_pay,
        "status": record.status,
        "reason": record.reason,
        "created_time": str(record.created_time)[0: 19],
        "total_amount": record.total_amount
    } for record in records]
    data['bdtransfer_list'] = bdtransfer_list
    return data


@bind_context('doctor/bdtransfer/record/detail', login_required=True)
def BDTransferRecordDetail(ctx, record_id):
    re = BDTransferApplyRecord.objects.get(id=record_id)
    budans = [{
        "id": budan.budan_id,
        "total_amount": budan.budan.extra_consume,
        "should_pay": budan.budan.payment
    } for budan in re.record_budans.all()]
    data = {
        "proof_of_payments": re.get_pics(image_type=BDTRANSFER_PIC_TYPE.PROOF_OF_PAYMENT),
        "authorization_vouchers": re.get_pics(image_type=BDTRANSFER_PIC_TYPE.AUTHORIZATION_VOUCHER),
        "should_pay": re.should_pay,
        "budans": budans
    }
    return data

