#!/usr/bin/env python
# coding=utf-8

from api.tool.datetime_tool import get_timestamp
from api.tool.log_tool import logging_exception

from rpc.decorators import bind_context
from rpc.decorators import list_interface
from rpc.tool.error_code import gen, CODES

from hippo.tool.user_tool import get_doctor_from_context
from hippo.models import Agreement, AgreementDoctor


@bind_context('doctor/agreement/list', login_required=True)
def agreement_list(ctx):
    """
        强制协议列表，只返回老医生没有同意的
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)
    agreements = Agreement.objects.get_valid_agreement(doctor=doctor)
    ag_doctors = Agreement.objects.filter(agreementdoctor__doctor=doctor)
    result = [{
        'id': ag.id,
        'title': ag.title,
        'content': ag.content,
        'send_time': get_timestamp(ag.send_time),
    } for ag in (set(agreements) - set(ag_doctors))]
    result = sorted(result, key=lambda x: x['send_time'])  # 按发送时间排序
    return result


@bind_context('doctor/agreement/detail', login_required=True)
def agreement_detail(ctx, id):
    """
        医生协议详情
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    try:
        ag = Agreement.objects.get(id=id)
    except:
        logging_exception()
        raise
    result = {
        'id': ag.id,
        'title': ag.title,
        'content': ag.content,
        'status': ag.status,
        'agree_time': None,
    }
    try:
        ag_doctor = AgreementDoctor.objects.get(doctor=doctor, agreement=ag)
        result['agree_time'] = get_timestamp(ag_doctor.create_time)
    except AgreementDoctor.DoesNotExist:
        pass
    return result


@bind_context('doctor/agreement/accept', login_required=True)
def accept_agreement(ctx, id):
    """
        医生签订协议
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    try:
        agreement = Agreement.objects.get(id=id)
        AgreementDoctor.objects.get_or_create(doctor=doctor, agreement=agreement)
    except:
        logging_exception()
        raise
    return gen(CODES.SUCCESS)


@bind_context('doctor/agreement/accepted_list', login_required=True)
@list_interface(offset_name='start_num', limit_name='count', element_model=Agreement)
def accepted_list(ctx, start_num=0, count=10):
    """
        医生同意过的协议列表
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    ag_doctors = Agreement.objects.filter(agreementdoctor__doctor=doctor).order_by('-agreementdoctor__create_time')
    result = {
        'total_count': ag_doctors.count(),
        'data': [],
    }

    for ag in ag_doctors[start_num: start_num + count]:
        item = {
            'id': ag.id,
            'title': ag.title,
            'content': ag.content,
            'send_time': get_timestamp(ag.send_time),
            'agree_time': None,
        }
        try:
            ag_doctor = AgreementDoctor.objects.get(doctor=doctor, agreement=ag)
            result['agree_time'] = get_timestamp(ag_doctor.create_time)
        except AgreementDoctor.DoesNotExist:
            pass
        result['data'].append(item)
    return result
