# encoding=utf-8
from __future__ import unicode_literals
import json
from api.models import CashBackOrder
from django.db.models import Q
from rpc.cache import req_data_cache
from rpc.decorators import bind_context
from ..actions.order import OrderAction
from ..utils import check_business, check_operate, operate_business
from ..queries.cashback import CashbackDQ
from ..models import UserPerm

uri_pre = 'hera/cashback'


@bind_context(uri_pre + '/query')
def diary_query(ctx, options):
    req_data_cache.set(ctx.session.session_key + 'cashback', json.dumps(options))
    if check_operate(ctx.session.user_id):
        business_ids = operate_business(ctx.session.user_id)
        init_q = Q(order__service__doctor__business_partener__id__in=business_ids)
    else:
        init_q = None
    dqobj = CashbackDQ(init_q=init_q)
    return dqobj.process(**options)


@bind_context(uri_pre + '/action')
def cashback_orders(ctx, querytype, nos):
    user = ctx.session.user
    options = json.loads(req_data_cache.get(ctx.session.session_key + 'cashback'))
    if check_business(ctx.session.groups):
        # 判断是商务并且非商务leader
        members = UserPerm.members(user)
        init_q = Q(order__service__doctor__business_partener__in=members)
    else:
        init_q = None
    dtobj = CashbackDQ(init_q=init_q)
    if nos != 'selectall':
        cashback_orders = CashBackOrder.objects.filter(id__in=nos)
    else:
        if options.get('paging'):
            options.pop('paging')
        if options.get('columns'):
            options.pop('columns')
        cashback_orders = dtobj.build_queryset(**options)
    if 'excel' in querytype:
        kwargs = {
            'cashback_orders': cashback_orders,
            'to_user_email': user.email,
        }
    else:
        kwargs = {
            'cashback_orders': cashback_orders,
        }
    return getattr(OrderAction, querytype)(**kwargs)


@bind_context(uri_pre + '/error_query')
def cashback_error_query(ctx, options):
    dqobj = CashbackDQ()
    return dqobj.process(**options)
