# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import hashlib
from django.db.models import F, Q
from rpc.decorators import bind_context
from ..queries.installment import PeriodHospitalDQ
from api.models import Service, ServiceItem, PeriodHospital, Hospital

uri_pre = 'hera/installment'


@bind_context(uri_pre + '/hospital_query')
def hospital_query(ctx, options):
    dqobj = PeriodHospitalDQ(init_q=Q(is_online=True))
    return dqobj.process(**options)


@bind_context(uri_pre + '/add_hospital')
def add_hospital(ctx, hospital_id):
    hospital = Hospital.objects.get(id=hospital_id)
    hash_id = hashlib.md5(hospital.id.encode('utf-8')).hexdigest()
    hospital, _ = PeriodHospital.objects.get_or_create(hospital=hospital, period_id=hash_id)
    if not hospital.is_online:
        hospital.is_online = True
        hospital.save()


@bind_context(uri_pre + '/set_hospital')
def add_hospital(ctx, id, is_online):
    hospital = PeriodHospital.objects.get(id=id)
    hospital.is_online = is_online
    hospital.save()


@bind_context(uri_pre + '/set_service_stage')
def set_service_stage(ctx, hospital_ids, action_type='hospital_add'):
    assert action_type in ('hospital_add', 'doctor_add', 'doctor_cancel')
    if action_type == 'hospital_add':
        Service.objects.filter(
            doctor__hospital_id__in=hospital_ids,
            is_stage=False,
        ).update(is_stage=True)
    elif action_type == 'doctor_add':
        Service.objects.filter(
            doctor_id__in=hospital_ids,
            is_stage=False,
        ).update(is_stage=True)
    elif action_type == 'doctor_cancel':
        Service.objects.filter(
            doctor_id__in=hospital_ids,
            is_stage=True,
        ).update(is_stage=False)
