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

import pinyin
from django.db import IntegrityError


from rpc.tool.dict_mixin import to_dict
from rpc.decorators import bind_context
from rpc.exceptions import (RPCPermissionDeniedException, RPCIntegrityError,
    RPCNotFoundException)


from api.models import DoctorRegisterInfo
from ..datatables import DoctorRegisterInfoDT

from rpc.tool.log_tool import info_logger
from ..queries.doctorregisterinfo import DoctorRegisterInfoDQ

__author__ = 'Zyy'

uri_pre = 'hera/doctorregisterinfo'


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


@bind_context(uri_pre+'/list')
def doctorregisterinfo_datatable(ctx, req_data):
    dtobj = DoctorRegisterInfoDT(DoctorRegisterInfo)
    return dtobj.process(req_data, ['name', 'hospital', 'phone'])


@bind_context(uri_pre+'/listupdate')
def doctorregisterinfo_listupdate(ctx, items):
    info = []
    for obj in items:
        doctorregisterinfo = DoctorRegisterInfo.objects.get(pk=obj['key'])
        doctorregisterinfo.is_handled = obj['is_handled']
        doctorregisterinfo.comments = obj['comments']
        doctorregisterinfo.save()
        info.append(obj['key'])
    return info


@bind_context(uri_pre+'/get')
def doctorregisterinfo_detail(ctx, doctorregisterinfo_id, options=None):
    try:
        doctorregister = DoctorRegisterInfo.objects.get(id=doctorregisterinfo_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    diary_data = to_dict(doctorregister, **options)
    return diary_data

@bind_context(uri_pre+'/edit')
def doctorregisterinfo_edit(ctx, doctorregisterinfo_id=None, doctorregisterinfo_info=None):
    if doctorregisterinfo_info is None:
        return None

    if doctorregisterinfo_id is None:
        try:
            doctorregisterinfo = DoctorRegisterInfo.objects.create(**doctorregisterinfo_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            doctorregisterinfo = DoctorRegisterInfo.objects.get(id=doctorregisterinfo_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
        for k, v in doctorregisterinfo_info.iteritems():
            setattr(doctorregisterinfo, k, v)
        doctorregisterinfo.save()

    return doctorregisterinfo.id
