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

from django.db import IntegrityError

from api.models import BodyPart, Doctor, User, Person, DocBusinessRecord
from api.models.organization import OrganizationImage
from api.tool.user_tool import get_user_extra_by_user_id, user_register_log_data
from rpc.tool.dict_mixin import to_dict
from rpc.decorators import bind_context
from rpc.exceptions import RPCIntegrityError, RPCNotFoundException
from api.models.types import DOCTOR_TYPE
from ..datatables import DoctorRegisterDT
from rpc.tool.log_tool import info_logger
from rpc.tool.error_code import gen, CODES
from ..queries.doctorregister import DoctorRegisterDQ


ns_doctor = __import__('doctor', globals(), locals(), [], 0)
DoctorRegister = ns_doctor.models.DoctorRegister
RegisterOrganization = ns_doctor.models.capture.RegisterOrganization

__author__ = 'Zyy'

uri_pre = 'hera/doctorregister'


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


@bind_context(uri_pre + '/list')
def doctorregister_datatable(ctx, req_data):
    dtobj = DoctorRegisterDT(DoctorRegister)
    return dtobj.process(req_data, ['name', 'hospital', 'id', 'phone'])


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


@bind_context(uri_pre + '/get')
def doctorregister_detail(ctx, doctorregister_id, options=None):
    try:
        doctorregister = DoctorRegister.objects.get(id=doctorregister_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    doctorregister_data = to_dict(doctorregister, **options)
    area_id = None
    email = None
    log_phone = None
    user = getattr(doctorregister.person, 'user', None)
    doctorregister_data.pop('person')
    if doctorregister.person:
        area_id = doctorregister.person.area_id
        log_phone = doctorregister.person.phone
        email = doctorregister.person.email
    if not doctorregister.phone:
        doctorregister['phone'] = log_phone
    doctorregister_data['email'] = email
    doctorregister_data['log_phone'] = log_phone
    doctorregister_data['area'] = area_id or 1
    doctorregister_data['user'] = user.id if user else None
    return doctorregister_data


@bind_context(uri_pre + '/edit')
def doctordoctorregister_edit(ctx, doctorregister_id=None, doctorregister_info=None):
    if doctorregister_info is None:
        return None
    doctorregister_info['business_partener_id'] = doctorregister_info.pop('business_partener')
    doctorregister_info.pop('log_phone')
    doctorregister_info.pop('area')
    user_id = doctorregister_info.pop('user')
    person = Person.objects.get(user_id=user_id)
    if getattr(person.user, 'doctor', None):
        return gen(CODES.USER_ALREADY_EXIST)
    doctorregister_info['person_id'] = person.id
    if doctorregister_id is None:
        try:
            doctorregister = DoctorRegister.objects.create(**doctorregister_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            doctorregister = DoctorRegister.objects.get(id=doctorregister_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
        for k, v in doctorregister_info.iteritems():
            setattr(doctorregister, k, v)
        doctorregister.save()

    return doctorregister.id


@bind_context(uri_pre + '/create_doctor')
def doctor_create(ctx, doctorregister_id=None, doctorregister_info=None):
    action_user = ctx.session.user
    doctorregister_info['business_partener_id'] = doctorregister_info.pop('business_partener')
    doctorregister_info.pop('log_phone')
    doctorregister_info.pop('area')
    user_id = doctorregister_info.pop('user')
    person = Person.objects.get(user_id=user_id)
    if getattr(person.user, 'doctor', None):
        return gen(CODES.USER_ALREADY_EXIST)
    try:
        doctorregister = DoctorRegister.objects.get(id=doctorregister_id)
    except:
        info_logger.info(__import__('traceback').format_exc())
        raise RPCNotFoundException
    for k, v in doctorregister_info.iteritems():
        setattr(doctorregister, k, v)
    doctorregister.save()
    doctorregister_info['password'] = doctorregister.password
    doctorregister_info['email'] = doctorregister.email
    doctorregister_info['doctor_type'] = doctorregister.doctor_type
    doctor_id = None
    # try:
    #     换uuid之后不需要判定同名医生
    #     try:
    #         doctor = Doctor.objects.get(id=pinyin.get(doctorregister_info['name']))
    #         if doctor:
    #             return u'同名医生已经存在，请手动处理！'
    #     except Doctor.DoesNotExist:
    #         pass
    #     手机号注册过用户
    #     user = User.objects.get(username=doctorregister_info['phone'])
    #     try:
    #         if user.doctor:
    #             return u'相同手机号的医生用户已经存在,请手动检查处理！'
    #     except:
    #         生成医生账号
    #         user.is_staff = True
    #         user.last_name = doctorregister_info['name']
    #         user.password = doctorregister.password
    #         user.groups = '2'
    #         user.save()
    #         doctor_id = create_doctor(user, doctorregister_info)
    #         is_handled(doctorregister_id)
    # except User.DoesNotExist:
    #       不是注册用户,先生成用户账号再生成医生账号
    #       user = create_user(doctorregister_info)
    #       user.groups = '2'
    #       user.save()
    #       doctor_id = create_doctor(user, doctorregister_info)
    #       is_handled(doctorregister_id)
    #       ctx.logger.app(**user_register_log_data(user_id=user.id))
    #
    # person = Person.get_or_create(user)
    # person.password = doctorregister.password
    # person.save()
    try:
        user = User.objects.get(id=doctorregister.person.user_id)
        doctor_id = create_doctor(user, doctorregister_info, action_user)
        is_handled(doctorregister_id)
    except:
        raise RPCNotFoundException
    # todo synchronization doctor_organization
    # 机构上传图片
    try:
        if doctor_id is not None and doctorregister_info['doctor_type'] == DOCTOR_TYPE.OFFICER:
            image_list = RegisterOrganization.objects.filter(doctor_id=doctorregister_id)
            if len(image_list) > 0:
                doctor_organizations = []
                for item in image_list:
                    doctor_organizations.append(OrganizationImage(
                        image_url=item.image_url,
                        doctor_id=doctor_id,
                    ))
                OrganizationImage.objects.bulk_create(doctor_organizations)
    except Exception as e:
        return None
    return None


def is_handled(doctorregister_id):
    doctorregister = DoctorRegister.objects.get(id=doctorregister_id)
    doctorregister.is_handled = True
    doctorregister.save()


def create_user(data):
    user = User()
    user.username = data['phone']
    user.password = data['password']
    user.last_name = data['name']
    user.email = data['email']
    # user.is_staff = True
    user.save()
    get_user_extra_by_user_id(user.id)
    return user


def create_doctor(user, data, action_user=None):
    # 每日回复限制，默认医生: 50, 机构管理者: 10
    reply_limit_map = {DOCTOR_TYPE.DOCTOR: 50, DOCTOR_TYPE.OFFICER: 10}
    doctor_info = {
        'name': data['name'],
        'good_at': data['good_at'],
        'title': data['title'],
        'phone': data['phone'],
        'doc_email': data['email'],
        'portrait': data['portrait'],
        'doctor_type': data['doctor_type'],
        'introduction': data['introduction'],
        'business_licence': data['business_licence'],
        'practice_licence': data['practice_licence'],
        'business_partener_id': data['business_partener_id'],
        'user_id': user.id,
        'process_status': '0',
        'is_online': False,
        'accept_private_msg': False,
        'operate_log': u"医院：{}\n医生执业号{}".format(data['hospital'], data['profession_number']),

    }
    doctor = Doctor.objects.create(**doctor_info)
    doctor.reply_limit = reply_limit_map.get(doctor.doctor_type, 3)
    if doctor.phone:
        doctor.register_phone_ext()
    for part in data['good_at'].split(','):
        try:
            body = BodyPart.objects.get(name=part)
            doctor.body_parts.add(body)
        except BodyPart.DoesNotExist:
            pass
    try:
        docrecord = DocBusinessRecord()
        docrecord.doctor_id = doctor.id
        docrecord.to_business_id = data['business_partener_id']
        docrecord.user_id = action_user.id if action_user else 20296583
        docrecord.save()
    except:
        pass
    doctor.save()
    return doctor.id


@bind_context(uri_pre + '/getorganization_image')
def get_organization_image(ctx, doctor_id):
    """
    获取注册医生的机构图片
    """
    if doctor_id is None:
        return
    organizations = RegisterOrganization.objects.filter(doctor_id=doctor_id)
    organizations_data = [{
                              'image_url': item.image_url
                          } for item in organizations]
    return organizations_data


@bind_context(uri_pre + '/editorganization_image')
def edit_organization_image(ctx, doctor_id, organization_images):
    """
    修改注册机构的医院图片
    """
    RegisterOrganization.edit_organization_image(doctor_id, organization_images)
