# encoding=utf-8
from __future__ import unicode_literals
import json
from api.models import RefundOrder
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.refund import RefundOrderDQ
from ..models import UserPerm

uri_pre = 'hera/refund_new'


@bind_context(uri_pre + '/query')
def refund_new_query(ctx, options):
    req_data_cache.set(ctx.session.session_key + 'refund_new', 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 = RefundOrderDQ(init_q=init_q)
    return dqobj.process(**options)


@bind_context(uri_pre + '/refund_orders')
def refund_new_orders(ctx, querytype, nos):
    user = ctx.session.user
    req_data = json.loads(req_data_cache.get(ctx.session.session_key + 'refund_new'))
    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 = RefundOrderDQ(RefundOrder, init_q=init_q)
    if nos != 'selectall':
        refund_orders = RefundOrder.objects.filter(id__in=nos)
    else:
        if req_data.get('paging'):
            req_data.pop('paging')
        if req_data.get('columns'):
            req_data.pop('columns')
        refund_orders = dtobj.build_queryset(**req_data)
    if 'excel' in querytype:
        kwargs = {
            'refund_orders': refund_orders,
            'to_user_email': user.email,
        }
    else:
        kwargs = {
            'refund_orders': refund_orders,
        }
    return getattr(OrderAction, querytype)(**kwargs)
