#! /usr/bin/env python
# -*- coding: utf-8 -*-
# create by oldman
# Date: 2018/9/27
import datetime

import tablib
from django.contrib.auth.models import User
from django.core.management import BaseCommand
from gm_types.doctor import DOCTOR_INFO_STATUS
from gm_types.gaia import PLATFORM_CHANNEL, DOCTOR_TYPE, LOGIN_AUTH_TYPE
from openpyxl import load_workbook

from api.models import BodyPart, random_str
from api.models import UserExtra
from api.tasks.export_maidan_order_task import get_mail
from api.tool.person import create_user_by_phone, create_person_by_phone
from api.tool.user_tool import get_user_extra_by_user_id
from hippo.models import Doctor
from hippo.models import DoctorRegister, Person, transaction, DOCTOR_REGISTER_STATUS
from hippo.models import DoctorRegisterRecord
from hippo.models import Hospital
from hippo.tool.user_tool import get_user_by_id
from rpc.context import get_rpc_remote_invoker
from rpc.tool.error_code import gen


def _read_excel():
    wb = load_workbook(filename=u'doctor.xlsx')
    sheetnames = wb.get_sheet_names()
    ws = wb.get_sheet_by_name(sheetnames[0])
    # 读取excel
    doctors = []
    for rx in range(2, ws.get_highest_row() + 1):
        try:
            item = {
                "phone": ws.cell(row=rx, column=1).value,
                "name": ws.cell(row=rx, column=2).value,
                "related_phone": ws.cell(row=rx, column=3).value
            }
            doctors.append(item)
        except Exception as e:
            print e
            continue
    return doctors


def _create_doctor(doctorregister):
    """
    根据注册信息生成医生
    create by oldman at 2017-02-20
    :return: 医生实体
    """
    doctors = Doctor.objects.filter(user=doctorregister.person.user)
    if doctors.count() > 0:
        raise ValueError
    if doctorregister.doctor_type == DOCTOR_TYPE.OFFICER:
        doctor_hospital = Doctor.objects.filter(hospital_id=doctorregister.related_hospital.id,
                                                doctor_type=DOCTOR_TYPE.OFFICER)
        if doctor_hospital.count() > 0:
            raise ValueError
    # 每日回复限制，默认医生: 50, 机构管理者: 10
    reply_limit_map = {DOCTOR_TYPE.DOCTOR: 50, DOCTOR_TYPE.OFFICER: 10}
    doctor = Doctor.objects.create(
        user=doctorregister.person.user,
        name=doctorregister.name,
        portrait=doctorregister.portrait,
        doctor_type=doctorregister.doctor_type,
        phone=doctorregister.phone,
        assist_phone=doctorregister.assist_phone,
        title=doctorregister.title,
        department=doctorregister.department,
        introduction=doctorregister.introduction,
        area_type=doctorregister.area_type,
        good_at=doctorregister.good_at,
        # business_partener_id=doctorregister.business_partener.id,
        # business_group=doctorregister.business_group,
        # hospital_id=doctorregister.related_hospital.id,
        accept_private_msg=True,
        is_online=False,
        # 注册通过合同待审状态
        status=DOCTOR_INFO_STATUS.CHECK_PENDING
    )
    doctor.reply_limit = reply_limit_map.get(doctor.doctor_type, 3)
    doctor.save()
    # doctor.update_licences_images(DOCTOR_LICENCE_TYPE.BUSINESS, self.b_licences)
    # doctor.update_licences_images(DOCTOR_LICENCE_TYPE.PRACTICE, self.p_licences)
    doctor.update_licence_images(doctorregister.b_licences, doctorregister.p_licences, doctorregister.t_licences)
    for part in doctor.good_at.split(','):
        try:
            body = BodyPart.objects.get(name=part)
            doctor.body_parts.add(body)
        except BodyPart.DoesNotExist:
            pass

    from maidan.models import MaidanSetting
    MaidanSetting.objects.create(
        doctor_id=doctor.id,
        is_open=True,
    )
    # 如果是机构管理者，同步医院图片
    if doctor.doctor_type == DOCTOR_TYPE.OFFICER:
        doctor.update_hospital_pics(doctorregister.hospital_pics())
    # 医生商务关联器
    # docrecord = DocBusinessRecord()
    # docrecord.doctor_id = doctor.id
    # docrecord.to_business_id = doctor.business_partener.id
    # docrecord.user = user
    # docrecord.save()
    # 注册400电话
    doctor.register_phone_ext()
    # 同步医生信息到用户
    try:
        user_id = doctor.user.id
        user = get_user_by_id(user_id)
        extra = get_user_extra_by_user_id(user.id)
    except:
        user = None
        extra = None
    if extra and doctor.portrait:
        extra.portrait = doctor.portrait
        extra.last_login = datetime.datetime.now()
        extra.save()
    if doctor.name:
        name = doctor.name
        is_doctor = doctor.doctor_type == DOCTOR_TYPE.DOCTOR
        is_suozhang = doctor.user.id == 22
        if is_doctor and not is_suozhang:
            name = u'{} 医生'.format(name)
        user.last_name = name
        user.save()

    return doctor


def _audit_doctor(register, record_user):
    try:
        # 同步医生注册的数据
        with transaction.atomic():
            registerrecord = DoctorRegisterRecord.objects.create(doctor_register_id=register.id,
                                                                 content=u'修改医生信息',
                                                                 status=DOCTOR_REGISTER_STATUS.DATA_CHECKED,
                                                                 handler=record_user.person)
            register.status = DOCTOR_REGISTER_STATUS.DATA_CHECKED
            registerrecord.status = DOCTOR_REGISTER_STATUS.DATA_CHECKED
            registerrecord.save()
            register.save()
            # 注册医生
            rpc_invoker = get_rpc_remote_invoker()
            if register.status != DOCTOR_REGISTER_STATUS.DATA_CHECKED:
                raise ValueError('医生注册申请状态错误！')
            doctor = _create_doctor(register)

            try:
                params = [
                    {'name': register.name}
                ]
                rpc_invoker['sms/template/send'](phone=register.person.phone,
                                                 template_id=42,
                                                 params=params).unwrap()
            except Exception as e:

                pass

            try:
                rpc_invoker['artemis/account/create'](doctor_id=doctor.id).unwrap()
            except  Exception as e:
                pass

            # 注册通过之后，创建了医生，状态是 合同待审状态，等待合同审核
            # 但需要注意的是，合同审核已经和注册没有关系了，这是注册最后一条record
            # 之后医生合同审核通过 同步了 register的状态，没有添加record，目的只是为了PC端展示
            register.status = DOCTOR_REGISTER_STATUS.CHECK_PENDING
            registerrecord.status = DOCTOR_REGISTER_STATUS.CHECK_PENDING
            registerrecord.save()
            register.save()
            hospitals = Hospital.objects.filter(name=doctor.name)
            if hospitals.exists():
                doctor.hospital = hospitals.first()
                doctor.save()

            return doctor
    except Exception:
        raise


def _create_user(phone):
    try:
        Person.objects.get(phone=phone)
        return None
    except Person.DoesNotExist:
        pass

    try:
        user = User.objects.get(username=phone)
    except User.DoesNotExist:
        from api.tasks.user_related_tasks import follow_suozhang
        user = UserExtra.create_user(phone, "", random_str(32), login_auth_type=LOGIN_AUTH_TYPE.phone)
    person = create_person_by_phone(phone, user, PLATFORM_CHANNEL.UNKNOWN, None, 1)
    return user, person


class Command(BaseCommand):
    """
    批量创建医生
    python manage.py update_2018_09_27_create_new_doctor
    """

    def handle(self, *args, **options):
        record_user = User.objects.get(username=u'tanzhimin')
        doctor_infos = _read_excel()
        doctor_type = DOCTOR_TYPE.OFFICER
        is_merchant = 1
        to_user_email = 'lipeng@igengmei.com'
        dt = tablib.Dataset()
        dt.headers = [
            U'医生名字', u'医生ID', u'医院ID'
        ]
        print doctor_infos
        for item in doctor_infos:
            try:
                with transaction.atomic():
                    phone = item['phone']
                    name = item['name']
                    related_phone = item['related_phone']
                    persons = Person.objects.filter(phone=phone)
                    if persons.exists():
                        person = persons.first()
                    else:
                        user, person = _create_user(phone)
                    # 创建医生注册
                    doctor_register = DoctorRegister.objects.create(
                        person=person,
                        name=name,
                    )
                    doctor = _audit_doctor(doctor_register,record_user)
                    doctor.phone=related_phone
                    doctor.doctor_type = doctor_type
                    doctor.is_merchant = is_merchant
                    doctor.save()
                    x = (doctor.name,
                         doctor.id,
                         doctor.hospital_id if doctor.hospital else u'')
                    dt.append(x)
                    print doctor.id
            except Exception as e:
                print e.message
                continue
        print u'Done'
        body = u'新增医生数据'
        get_mail(u'新增数据', body, to_user_email, dt).send()

