#!/usr/bin/env python
# coding=utf-8

from __future__ import unicode_literals
import datetime
import json

from django.db.models import Q
from gm_types.doctor import DOCTOR_INFO_STATUS, DOCTOR_TITLE_TYPE
from gm_upload.upload import get_video_upload_token
import gm_upload

from api.tool.image_utils import get_full_path
from hippo.models import DoctorEditRecord, Hospital, HospitalVideo
from rpc.decorators import bind_context, bind
from api.models.service import Service
from api.models.doctor import HospitalInfo, HospitalLicenes, Doctor
from api.tool.user_tool import get_user_from_context, get_user_extra_by_user_id, filter_user_nick_name
from hippo.tool.user_tool import get_doctor_by_user_id, get_doctor_from_context
from hippo.models.chain_hospital import MasterMerchant, SlaveMerchant
from gm_types.ascle.types import HOSPITAL_INFO_IMAGE, HOSPITAL_INFO_REVIEW
from gm_types.gaia import DOCTOR_TYPE
from django.db import transaction
from django.conf import settings
from rpc.tool.error_code import CODES, gen


def upload_video_picture_to_qiniu(video_url):
    """
    获取上传视频的首帧图片
    :param id:
    :return:
    """
    if video_url:
        video_pic = settings.VIDEO_HOST + video_url + settings.VIDEO_PIC_URL
        video_pic = gm_upload.fetch_picture_and_save_to_qiniu(video_pic)
    else:
        video_pic = ''
    return video_pic


@bind_context('doctor/user/update_hospital', login_required=True)
def update_hospital_detail(ctx, hospital_info):
    """
     提交 机构管理者修改个人信息
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)
    video_pic = upload_video_picture_to_qiniu(hospital_info['video_url'])
    hospital_info['video_pic'] = video_pic
    if doctor.id != hospital_info.get('id'):
        return gen(CODES.NO_PERMISSION)
    if hospital_info['open_time']:
        time = datetime.datetime.strptime(hospital_info['open_time'], '%Y-%m')
        hospital_info['open_time'] = time.strftime('%Y-%m-%d')
    with transaction.atomic():
        record = DoctorEditRecord.objects.create(
            doctor_id=doctor.id, status=DOCTOR_INFO_STATUS.APPLY_EDIT, content=json.dumps(hospital_info)
        )
        doctor.status = DOCTOR_INFO_STATUS.APPLY_EDIT
        doctor.last_edit_time = datetime.datetime.now()
        doctor.save()
    return {'edit_record_id': record.id}


@bind_context('doctor/user/hospital_info', login_required=True)
def get_hospital_detail(ctx):
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    info = DoctorEditRecord.objects.filter(doctor_id=doctor.id).last()
    reason = ''
    hospital_desc = ''
    images = None
    if info:
        content = json.loads(info.content)
        status = info.status
        reason = info.reject_reason
    else:
        content = doctor.__dict__
        status = doctor.status
        images = doctor.can_edit_info()

    hos = Hospital.objects.get(id=doctor.hospital_id)
    if hos.video_info['video_url']:
        video_url = hos.video_info['video_url']
    else:
        video_url = content.get('video_url', '')

    recommend_doctors = content.get('recommend_doctors', [])
    recommend_services = content.get('recommend_services', [])
    if doctor.status == DOCTOR_INFO_STATUS.CHECKED:
        recommend_doctors = hos.recommend_doctors
        recommend_services = hos.recommend_services
    if not content.get('hospital_desc', None):
        try:
            hospital_desc = Hospital.objects.get(id=doctor.hospital_id).name
        except:
            pass
    else:
        hospital_desc = content.get('hospital_desc')
    hospital_pics = []
    if not images:
        for url in content.get('hospital_pics', []):
            hospital_pics.append(get_full_path(url, '-w'))
    else:
        if isinstance(images['hospital_pics'], str):
            hospital_pics.append(get_full_path(images['hospital_pics'], '-w'))
        elif isinstance(images['hospital_pics'], list):
            for url in images['hospital_pics']:
                hospital_pics.append(get_full_path(url, '-w'))
    data = {
        'id': doctor.id,
        'is_merchant': doctor.is_merchant,
        'reject_reason': reason,
        'name': doctor.name,
        'hospital_desc': hospital_desc,
        'status': status,  # 医生信息可编辑的状态
        'doctor_type': doctor.doctor_type,
        'area_type': doctor.area_type,
        'portrait': content.get('portrait'),
        'phone': content.get('phone'),
        'assist_phone': content.get('assist_phone'),
        'introduction': content.get('introduction'),
        'good_at': content.get('good_at').split(','),
        'b_licences': content.get('b_licences', []) if not images else images['b_licences'],
        'p_licences': content.get('p_licences', []) if not images else images['p_licences'],
        'hospital_pics': hospital_pics,

        'open_time': content.get('open_time', None),
        'hospital_type': content.get('hospital_type', None),
        'hospital_type_desc': content.get('hospital_type_desc', ''),
        'hospital_level': content.get('hospital_level', None),
        'hospital_level_desc': content.get('hospital_level_desc', ''),
        'business_area': content.get('business_area', 0),
        'notice': content.get('notice', ''),
        'is_same_province_chain': content.get('is_same_province_chain', False),
        'is_inter_province_chain': content.get('is_inter_province_chain', False),
        'same_province_chain_hospital': content.get('same_province_chain_hospital', None),
        'same_province_chain_hospital_desc': content.get('same_province_chain_hospital_desc', ''),
        'inter_province_chain_hospital': content.get('inter_province_chain_hospital', None),
        'inter_province_chain_hospital_desc': content.get('inter_province_chain_hospital_desc', ''),
        'same_p_image': content.get('same_p_image', []),
        'area_image': content.get('area_image', []),
        'inter_p_image': content.get('inter_p_image', []),
        'level_image': content.get('level_image', []),

        'video_token': get_video_upload_token(),
        'video_url': HospitalVideo.cleaned_video_url(video_url),
        'instrument_intro': content.get('instrument_intro', ''),
        'instrument_info': content.get('instrument_info', []),
        'recommend_doctors': recommend_doctors,
        'recommend_services': recommend_services,

        'lincense_name': content.get('lincense_name', ''),
        'lincense_number': content.get('lincense_number', ''),
        'lincense_start_time': content.get('lincense_start_time', ''),
        'lincense_end_time': content.get('lincense_end_time', ''),
        'practice_start_time': content.get('practice_start_time', ''),
        'practice_end_time': content.get('practice_end_time', ''),
        'ad_check_img': content.get('ad_check_img', ''),
        'ad_check_start_time': content.get('ad_check_start_time', ''),
        'ad_check_end_time': content.get('ad_check_end_time', ''),

        'bed_count': content.get('bed_count', None) if content.get('bed_count') else None,
        'department_count': content.get('department_count', None),
        'honor_introduction': content.get('honor_introduction', u''),
        'honor_pics': content.get('honor_pics', []),
        'escort': content.get('escort', False),
        'one_to_one_consulation': content.get('one_to_one_consulation', False),
        'regular_return_visit': content.get('regular_return_visit', False),
        'wifi': content.get('wifi', False),
        'paid_parking': content.get('paid_parking', False),
        'independent_treatment_room': content.get('independent_treatment_room', False),
        'dressing_room': content.get('dressing_room', False),
        'free_parking_space': content.get('free_parking_space', False),
        'smoking_room': content.get('smoking_room', False),
        'free_drink': content.get('free_drink', False),
        'free_snack': content.get('free_snack', False),
        'swip': content.get('swip', False),

    }
    return data


@bind_context('doctor/user/hospital_list', login_required=True)
def hospital_list(ctx):
    hospital_list = [{
        'id': hos.id,
        'name': hos.name
    } for hos in Hospital.objects.all()]
    data = {
        'total': Hospital.objects.all().count(),
        'hospital_list': hospital_list
    }
    return data


@bind_context('doctor/user/hospital_doctor_list', login_required=True)
def hospital_doctor_list(ctx):
    doctor = get_doctor_from_context(ctx)
    doctors = Doctor.objects.filter(
        hospital_id=doctor.hospital_id,
        allow_hospital_agent=True,
        is_online=True
    )
    data = [{
        'id': d.id,
        'name': d.name,
        'is_online': d.is_online
            } for d in doctors]
    return data


@bind_context('doctor/user/hospital_service_list', login_required=True)
def hospital_doctor_list(ctx):
    doctor = get_doctor_from_context(ctx)
    doctor_ids = Doctor.objects.filter(
        hospital_id=doctor.hospital_id,
        allow_hospital_agent=True,
        is_online=True
    ).values_list('id', flat=True)
    services = Service.objects.filter(
        doctor_id__in=doctor_ids,
        is_online=True
    )
    data = [{
        'id': s.id,
        'name': s.name,
        'is_online': s.is_online
            } for s in services]
    return data


@bind_context('doctor/user/hospital_update', login_required=True)
def update_hospital_doctor(ctx):
    doctor = get_doctor_from_context(ctx)
    doctors = Doctor.objects.filter(
        doctor_type=DOCTOR_TYPE.DOCTOR,
        hospital_id=doctor.hospital_id,
        allow_hospital_agent=True,
        is_online=True
    )
    chief_ph_count = doctors.filter(
        title=DOCTOR_TITLE_TYPE.CHIEF,
    ).count()
    associate_chief_ph_count = doctors.filter(
        title=DOCTOR_TITLE_TYPE.VICE,
    ).count()
    ph_in_charge_count = doctors.filter(
        title=DOCTOR_TITLE_TYPE.MAIN,
    ).count()
    resident_ph_count = doctors.filter(
        title=DOCTOR_TITLE_TYPE.RESIDENT,
    ).count()
    ph_count = doctors.filter(
        title=DOCTOR_TITLE_TYPE.EMPTY,
    ).count()

    hos = Hospital.objects.get(id=doctor.hospital_id)
    hos.chief_ph_count = chief_ph_count
    hos.associate_chief_ph_count = associate_chief_ph_count
    hos.ph_in_charge_count = ph_in_charge_count
    hos.resident_ph_count = resident_ph_count
    hos.ph_count = ph_count
    hos.save()
    data = {
        'chief_ph_count': chief_ph_count,
        'associate_chief_ph_count': associate_chief_ph_count,
        'ph_in_charge_count': ph_in_charge_count,
        'resident_ph_count': resident_ph_count,
        'ph_count': ph_count
    }

    return data


def get_sub_hospital(doctor_id, city_id=None):
    """
    获取旗舰店指定城市的分店
    :param doctor_id: 旗舰店的doctor_id
    :param city_id: 城市ID
    :return: doctor_id hospital_id doctor_name hospital_name
    """
    result = []
    is_mastermerchant = MasterMerchant.objects.filter(
        mastermerchant__doctor_id=doctor_id, is_store_classification=True).exists()
    if is_mastermerchant:
        mastermerchant =  MasterMerchant.objects.get(
            mastermerchant__doctor_id=doctor_id, is_store_classification=True)
        q = Q()
        if city_id:
            q &= Q(slavemerchant__doctor__hospital__city_id=city_id)
        for d in mastermerchant.slavemerchants.filter(q):
            data = {}
            data['doctor_id'] = d.slavemerchant.doctor.id
            data['doctor_name'] = d.slavemerchant.doctor.name
            data['hospital_id'] = d.slavemerchant.doctor.hospital.id
            data['hospital_name'] = d.slavemerchant.doctor.hospital.name
            result.append(data)
    return result
