# -*- coding: UTF-8 -*-
from django.db.models import Q

from api.models.types import SERVICE_MONITOR_STATUS, SERVICE_OPERATION_TYPE
from hera.utils import check_operate, operate_business

from rpc.decorators import bind_context
from rpc.exceptions import RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from api.models import ServiceMonitor, SERVICE_MONITOR_STATUS
from api.tool.user_tool import get_user_from_context
from ..datatables import ServiceMonitorDT
from ..queries.servicemonitor import ServiceMonitorDQ

uri_pre = 'hera/servicemonitor'


@bind_context(uri_pre + '/query')
def service_monitor_query(ctx, options):
    if check_operate(ctx.session.user_id):
        business_ids = operate_business(ctx.session.user_id)
        init_q = Q(service__doctor__business_partener__id__in=business_ids)
    else:
        init_q = None
    dqobj = ServiceMonitorDQ(init_q=init_q)
    return dqobj.process(**options)


@bind_context(uri_pre + "/list")
def doctor_datatable(ctx, req_data):
    if check_operate(ctx.session.user_id):
        business_ids = operate_business(ctx.session.user_id)
        init_q = Q(service__doctor__business_partener__id__in=business_ids)
    else:
        init_q = None
    dtobj = ServiceMonitorDT(ServiceMonitor, init_q=init_q)
    return dtobj.process(req_data, ['service__name',
                                    'service__doctor__hospital__name',
                                    'service__doctor__name',
                                    'service__doctor__business_partener__username'
                                    ])


@bind_context(uri_pre + '/get')
def monitor_detail(ctx, monitor_id, options=None):
    try:
        monitor = ServiceMonitor.objects.get(id=monitor_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    monitor_data = to_dict(monitor, **options)
    monitor_data['service_name'] = monitor.service.name
    monitor_data['is_multiattribute'] = monitor.service.is_multiattribute
    monitor_data['status_text'] = SERVICE_MONITOR_STATUS.getDesc(monitor.status)
    monitor_data['operations'] = []
    for operation in monitor.operations.all().order_by('-handle_at'):
        data = {
            'operator': operation.operator.user.last_name or operation.operator.user.username,
            'handle_at': str(operation.handle_at),
            'optype': SERVICE_OPERATION_TYPE.getDesc(operation.optype),
            'reason': operation.reason if operation.reason else '',
        }
        monitor_data['operations'].append(data)
    return monitor_data


@bind_context(uri_pre + '/edit')
def monitor_edit(ctx, monitor_id, monitor_info=None):
    try:
        monitor = ServiceMonitor.objects.get(id=monitor_id)
    except:
        raise RPCNotFoundException
    person = get_user_from_context(ctx).person
    reason = monitor_info.get('reason') or ''
    optype = int(monitor_info.get('status'))
    if optype == SERVICE_MONITOR_STATUS.NORMAL:
        monitor.cancel_black(person.id, reason)
    else:
        monitor.set_black(person.id, reason)
    return {
        'success': True,
        'status': monitor.status,
    }
