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


from rpc.decorators import bind_context
from hera.queries.freecustom import FreecustomDQ
from api.models.freecustom import FreeCustom, FreecustomImage
from rpc.exceptions import RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from api.tool.image_utils import get_full_path
from rpc.tool.time_tool import get_current_time
from api.models.types import PLAN_TYPE, TREATMENT_TYPE, RECOVER_TIME_TYPE, ORDER_STATUS

uri_pre = 'hera/freecustom'


@bind_context(uri_pre + '/query')
def diary_query(ctx, options):
    dqobj = FreecustomDQ()
    return dqobj.process(**options)


@bind_context(uri_pre+'/get')
def freecustom_detail(ctx, freecustom_id, options=None):
    try:
        freecustom = FreeCustom.objects.get(id=freecustom_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    freecustom_data = to_dict(freecustom, **options)
    freecustom_data.pop('user')
    freecustom_data['user_name'] = freecustom.user.user.last_name
    freecustom_data['plan_type'] = PLAN_TYPE.getDesc(freecustom.plan_type)
    freecustom_data['recover_time'] = RECOVER_TIME_TYPE.getDesc(freecustom.recover_time)
    freecustom_data['images'] = []
    freecustom_data['follow_status'] = int(freecustom.follow_status) if freecustom.follow_status else 0
    freecustom_data['is_phone_connect'] = u'是' if freecustom.is_phone_connect else u'否'
    freecustom_data['order_list'] = []
    for order in freecustom.has_order.all():
        freecustom_data['order_list'].append({
            'id': order.id,
            'service_id': order.service.id,
            'service_name': order.service.name,
            'status': ORDER_STATUS.getDesc(order.status)
        })
    for images in FreecustomImage.objects.filter(freecustom=freecustom):
        freecustom_data['images'].append(get_full_path(images.image_url))
    freecustom_data['operation_type'] = u''
    for t in freecustom.operation_type.split(','):
        if t:
            freecustom_data['operation_type'] += TREATMENT_TYPE.getDesc(t) + u','
    return freecustom_data


@bind_context(uri_pre+'/edit')
def monitor_edit(ctx, freecustom_id, freecustom_info=None):
    user = ctx.session.user
    now = get_current_time("%Y-%m-%d %H:%M:%S")
    kefu_comments = u''
    try:
        freecustom = FreeCustom.objects.get(id=freecustom_id)
    except:
        raise RPCNotFoundException
    if freecustom_info['follow_status'] < freecustom.follow_status:
        return {
            'status': False,
            'msg': u'跟进状态不可后退'
        }
    if freecustom_info['kefu_comments'] != '':
        kefu_comments = u'{}  备注人:{} 备注时间:{}\n'.format(
            freecustom_info['kefu_comments'].replace('\n', ' '),
            user, now,
        )
    freecustom_info['kefu_comments'] = freecustom.kefu_comments + kefu_comments
    freecustom_info['feedback_time'] = now
    for k, v in freecustom_info.iteritems():
        setattr(freecustom, k, v)
    freecustom.save()
    return {
        'status': True,
        'freecustom_id': freecustom_id
    }
