#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals

from rpc.tool.error_code import CODES, gen
from rpc.decorators import bind_context
from api.tool.datetime_tool import get_datetime

from hippo.tool.user_tool import get_doctor_from_context_or_exception
from hippo.models import DoctorQuickReplay


@bind_context("doctor/quickreply/list")
def quick_reply_list(ctx):
    doctor = get_doctor_from_context_or_exception(ctx)
    # 考虑置顶操作的排序
    quick_replys = DoctorQuickReplay.objects.filter(doctor=doctor, deleted=False).order_by("-stick_time")
    return [{"id": r.id, "content": r.content} for r in quick_replys]


@bind_context("doctor/quickreply/create")
def quick_reply_create(ctx, content, stick_time):
    doctor = get_doctor_from_context_or_exception(ctx)
    if DoctorQuickReplay.objects.filter(doctor=doctor, content=content).exists():
        return gen(CODES.REPLY_CAN_NOT_BE_REPEATED)

    quick_reply = DoctorQuickReplay(doctor=doctor, content=content,
                                    stick_time=get_datetime(stick_time))
    quick_reply.clean_fields()
    quick_reply.save()
    return quick_reply.id


@bind_context("doctor/quickreply/edit")
def quick_reply_edit(ctx, quick_reply_id, content):
    doctor = get_doctor_from_context_or_exception(ctx)
    if DoctorQuickReplay.objects.filter(doctor=doctor, content=content).exists():
        gen(CODES.REPLY_CAN_NOT_BE_REPEATED)

    quick_reply = DoctorQuickReplay.objects.get(id=quick_reply_id, doctor=doctor)
    quick_reply.content = content
    quick_reply.clean_fields()
    quick_reply.save()


@bind_context("doctor/quickreply/delete")
def quick_reply_delete(ctx, quick_reply_id):
    doctor = get_doctor_from_context_or_exception(ctx)

    quick_reply = DoctorQuickReplay.objects.get(id=quick_reply_id, doctor=doctor, deleted=False)
    quick_reply.deleted = True
    quick_reply.save()


@bind_context("doctor/quickreply/stick")
def quick_reply_stick(ctx, quick_reply_id, stick_time):
    """置顶"""
    doctor = get_doctor_from_context_or_exception(ctx)

    quick_reply = DoctorQuickReplay.objects.get(id=quick_reply_id, doctor=doctor)
    quick_reply.stick_time = get_datetime(stick_time)
    quick_reply.save()
