#!/usr/bin/env python
# coding=utf-8
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import User

from api.models import Doctor
from hera.models import UserPerm, BackendGroup
from api.tool.user_tool import get_user_from_context

from rpc.tool.error_code import CODES, gen
from rpc.decorators import bind_context
from rpc.cache import business_select_cache


@bind_context('doctor/business/login')
def doctor_login(ctx, name, password):
    """
        商务登录
    """
    user = authenticate(username=name, password=password)
    if user and user.is_staff:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        ctx.session.do_login(user)
        if ctx.session.groups and 'business' in ctx.session.groups:
            return ctx.session.session_key
        else:
            return gen(CODES.BUSINESS_NOT_FOUND)
    else:
        return gen(CODES.LOGIN_FAIL)


@bind_context('doctor/business/info')
def doctor_business_info(ctx):
    user = get_user_from_context(ctx)
    return {'person_id': user.person.id.hex}


@bind_context('doctor/business/doctors')
def doctor_query(ctx, query=None):
    """商务管理的医生列表，按搜索词返回"""
    user = get_user_from_context(ctx)
    is_business = lambda x: x.belong_groups.filter(name='business').exists()
    members = filter(is_business, UserPerm.members(user))
    doctors = Doctor.objects.filter(business_partener__in=members)
    limit = 30
    if query:
        doctors = doctors.filter(name__contains=query)
    else:
        limit = 100
    result = {
        'total': doctors.count(),
        'doctors': [],
    }
    # 暂时最多返回30个
    doctors = doctors.select_related('hospital')
    result['doctors'] = [
        {
            'id': doctor.id,
            'name': doctor.name,
            'hospital_name': doctor.hospital.name if doctor.hospital else ""
        } for doctor in doctors[:limit]
    ]
    return result


@bind_context('doctor/business/select_doctor')
def select_doctor(ctx, doctor_id):
    """
        选择管理的医生
    """
    user = get_user_from_context(ctx)
    print '***select_doctor******user.id is %s' % user.id
    print ctx.session.session_key
    try:
        select_user = User.objects.get(doctor__id=doctor_id)
    except User.DoesNotExist:
        return gen(CODES.DOCTOR_NOT_FOUND)

    if select_user.doctor.business_partener not in UserPerm.members(user):
        return gen(CODES.BUSINESS_NO_PERMISSION)
    # 登录 获取session
    from rpc.context import Session
    select_session = Session()
    select_user.backend = "django.contrib.auth.backends.ModelBackend"
    select_session.do_login(select_user)
    login_session = select_session.session_key

    # 缓存商务选择医生的登录session, 在"doctor/user/get_info"接口判断是否对该医生session有访问权限
    business_select_cache.set(login_session, user.person.id.hex, settings.ASCLE_USER_COOKIE_TIME)
    return login_session
