# coding=utf-8
from __future__ import unicode_literals

from django.contrib.auth.models import User

from gm_types.gaia import DOCTOR_TYPE
from doctor.models import DoctorRegister
from hippo.tool.chain_hospital_tools import get_merchant_message_doctors
from hippo.utils import get_doctors
from rpc.decorators import bind, bind_context
from rpc.tool.error_code import CODES, gen
from hippo.models.chain_hospital import MasterMerchant
from api.models import Doctor, Person
from api.tool.verification_code import calc_verification_code
from api.tool.user_tool import get_doctor_from_context
from services.unread.base import gen_poll_channel
from services.unread.stat import DoctorUnread
from doctor.views.special import can_show_activity


@bind('doctor/is_certified')
def user_is_certified_doctor(phone):
    """check if user is a certified doctor."""
    person = None

    # check if user exists
    try:
        try:
            person = Person.objects.get(phone=phone)
        except Person.DoesNotExist:
            # 因为web后台需要支持【用户名登录】, 下次整理一下登录方式
            person = Person.objects.get(user__username=phone)
    except Person.DoesNotExist:
        pass

    if person and person.user:
        try:
            # check if doctor has certified
            Doctor.objects.get(user__id=person.user.id)
            return gen(CODES.SUCCESS)
        except Doctor.DoesNotExist:
            pass

    # here we should check if this doctor has applied certification
    applies = DoctorRegister.objects.filter(person__phone=phone)
    if applies:
        return gen(CODES.DOCTOR_HAS_APPLIED)

    return gen(CODES.DOCTOR_HAS_NOT_APPLIED)


@bind_context('doctor/login')
def doctor_login(ctx, username, password):
    is_seccode_valid = u"%04d" % calc_verification_code(username) == password

    # 用于App Store审核
    if username == u'12345678912' and password == u'1234':
        is_seccode_valid = True

    if not is_seccode_valid:
        return gen(CODES.USERNAME_PASSWORD_NOT_MATCH)

    user = None
    try:
        person = Person.objects.get(phone=username)
        user = person.user
        if not user.is_active:
            raise User.DoesNotExist
    except Person.DoesNotExist:
        return gen(CODES.LOGIN_FAIL)

    user.backend = "django.contrib.auth.backends.ModelBackend"
    ctx.session.do_login(user)

    try:
        doctor = Doctor.objects.get(user__id=user.id)
    except Doctor.DoesNotExist:
        return gen(CODES.DOCTOR_NOT_FOUND)

    result = doctor.doctor_detail()
    result['session'] = ctx.session.session_key
    return result


@bind_context('doctor/account/enable_agent', login_required=True)
def agent_enable(ctx):
    """开启/关闭 医院托管代理功能
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    doctor.allow_hospital_agent = not doctor.allow_hospital_agent
    doctor.save()
    return {'allow_hospital_agent': doctor.allow_hospital_agent}


@bind_context('doctor/account/get_badge', login_required=True)
def get_badge(ctx, conversation_id=None):
    """
        获取未读数目消息
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    du = DoctorUnread(doctor.id)
    data = {
        'order_unview_num': du.get_order_unread(),
        'refund_processing_num': du.get_refund_unread(),
        'reserve_num': du.get_reserve_unread(),
        'conversation_num': du.get_conversation_all_unread(),
    }
    if conversation_id:
        unread = du.get_conversation_unread(conversation_id)
        data['conversation_info'] = {
            'id': conversation_id,
            'unread_num': unread,
        }
        if data['conversation_num'] >= unread:
            data['conversation_num'] = data['conversation_num'] - unread
    return data


@bind_context('doctor/account/get_badge_v2', login_required=True)
def get_badge(ctx, conversation_id=None):
    """
    商戶获取未读消息数目
    :param ctx:
    :return:
    """
    doctor = get_doctor_from_context(ctx)
    doctor_merchants = get_merchant_message_doctors(doctor.id)
    manage_doctor_ids = [du['doctor_id'] for du in doctor_merchants]
    doctor_unread_instance = DoctorUnread(doctor.id)
    data = {
        'order_unview_num': doctor_unread_instance.get_order_unread(),
        'refund_processing_num': doctor_unread_instance.get_refund_unread(),
        'reserve_num': doctor_unread_instance.get_reserve_unread(),
        'conversation_num': sum(DoctorUnread.get_all_conversation_unread_num_by_ids(manage_doctor_ids).values()),
        'show_activity': can_show_activity(doctor.id)
    }
    if conversation_id:
        unread = doctor_unread_instance.get_conversation_unread(conversation_id)
        data['conversation_info'] = {
            'id': conversation_id,
            'unread_num': unread,
        }
        if data['conversation_num'] >= unread:
            data['conversation_num'] = data['conversation_num'] - unread
    return data


@bind_context('doctor/account/poll_connect', login_required=True)
def get_poll_connect_string(ctx):
    """
        获取连接poll的connect_string
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    poll_channel = gen_poll_channel(doctor.id)
    result = ctx.rpc_remote['poll/named_channel/create_temporary_connect_string'](named_channel=poll_channel).unwrap()
    return result


@bind_context('doctor/account/manage', login_required=True)
def doctor_manager_setting(ctx, data):
    """
        更改医生的一些设置
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)
    for k, v in data.iteritems():
        setattr(doctor, k, v)
    doctor.save()
    return 'success'

