# -*- coding: UTF-8 -*-

from pay.models import ServiceSnapshot
from api.models import Order
from rpc.decorators import bind_context
from rpc.exceptions import (RPCNotFoundException)
from rpc.tool.dict_mixin import to_dict
import json

uri_pre = 'hera/servicesnapshot'


@bind_context(uri_pre + '/get')
def service_snapeshot(ctx, id=None, refund_id=None, cashback_id=None):
    order = None
    try:
        if id:
            order = Order.objects.get(id=id)
        elif refund_id:
            order = Order.objects.get(refund__id=refund_id)
        elif cashback_id:
            order = Order.objects.get(cashback__id=cashback_id)
        else:
            raise RPCNotFoundException
        if order:
            service_snapshot = ServiceSnapshot.objects.get(order_id=order.id)
        else:
            raise RPCNotFoundException
    except:
        raise RPCNotFoundException
    order_data = to_dict(service_snapshot)
    order_snapshot = json.loads(service_snapshot.order.service_snapshot)
    order_data['service_snapshot'] = (order_snapshot.get('richtext', '') or
                                      order_snapshot.get('detail_description', '') + order_snapshot.get(
                'special_remind', ''))
    order_data['bodypart_subitem'] = service_snapshot.bodypart_subitem.name if \
        service_snapshot.bodypart_subitem else ''
    order_data['doctor_name'] = getattr(service_snapshot.doctor, 'name', '')
    order_data['hospital'] = getattr(service_snapshot.doctor.hospital, 'name', '')
    order_data['business_partener'] = getattr(service_snapshot.business_partener, 'username', '')
    order_data['real_discount'] = getattr(order, 'discount', '')
    result_items = getattr(service_snapshot, 'items', '')
    try:
        # result_items = eval(result_items)
        result_items = result_items.encode('utf-8').decode('unicode_escape')[2:-2]
    except SyntaxError:
        pass
    order_data['items'] = result_items
    return order_data
