# coding: utf-8
from rpc.decorators import bind_context
from api.models import BDTransfer, Q
from django.contrib.auth.models import User
from django.conf import settings


@bind_context('doctor/bdtransfer/add')
def entry_public(ctx, user=None, user_phone=None, wechat=None, creator=None):
    if user_phone:
        bdtransfer_user_phone = BDTransfer.objects.filter(user_phone=user_phone)
        if bdtransfer_user_phone:
            return 0

    if wechat:
        bdtransfer_wechat = BDTransfer.objects.filter(wechat=wechat)
        if bdtransfer_wechat:
            return 0

    BDTransfer.objects.create(user=user, user_phone=user_phone, wechat=wechat, creator=creator)

    if user_phone:
        res = BDTransfer.objects.filter(user_phone=user_phone).values_list('id',flat=True)
        return list(res)
    res = BDTransfer.objects.filter(wechat=wechat).values_list('id',flat=True)
    return list(res)


@bind_context('doctor/bdtransfer/check_user_exist')
def inquire_phone_or_wechat(ctx, user_phone=None, wechat=None):

    if user_phone:
        bdtransfer_user_phone = BDTransfer.objects.filter(user_phone=user_phone)
        if bdtransfer_user_phone:
            return 0

    if wechat:
        bdtransfer_wechat = BDTransfer.objects.filter(wechat=wechat)
        if bdtransfer_wechat:
            return 0


@bind_context('doctor/bdtransfer/choice')
def backenduser_choices(ctx, q='', num=10000, initial=None):
    num = int(num)
    # page=int(page)

    if initial is not None:
        if isinstance(initial, (list, tuple)):
            qry = Q(id__in=initial)
        else:
            qry = Q(id=initial)
    else:
        qry = Q(id__contains=q) | Q(username__contains=q)

    qry &= Q(is_staff=True)
    exclude_qry = Q(groups__name=u'医生')
    query = User.objects.using(settings.HERA_READ_DB).filter(qry).exclude(exclude_qry)
    total_count = 0
    if initial:
        objs = query
    else:
        start_pos = 0
        start_pos = start_pos if start_pos >= 0 else 0
        objs = query[start_pos: start_pos + num]
    results = [
        {
            'id': obj.id,
            'text': u'{}:{}'.format(obj.id, obj.username),
        } for obj in objs
    ]
    return {"error": 0, "data": results, "message": ""}