import json

from django.contrib.auth.decorators import login_required
from django.http import JsonResponse

from clients.models import Card
from ecp_integration.integration import get_doctors_ecp_free_dates_by_research, get_doctor_ecp_free_slots_by_date, register_patient_ecp_slot, cancel_ecp_patient_record
from users.models import DoctorProfile
from slog.models import Log


@login_required
def get_available_slots_of_dates(request):
    request_data = json.loads(request.body)
    data = get_doctors_ecp_free_dates_by_research(
        request_data['research_pk'],
        request_data['date_start'],
        request_data['date_end'],
        request.user.doctorprofile.get_hospital_id(),
    )
    return JsonResponse({"data": data})


@login_required
def get_available_slots(request):
    request_data = json.loads(request.body)
    slots = get_doctor_ecp_free_slots_by_date(
        request_data['doctor_pk'],
        request_data['date'],
    )
    return JsonResponse({"result": slots})


@login_required
def fill_slot(request):
    request_data = json.loads(request.body)
    card_pk = request_data['card_pk']
    slot_id = request_data['slot_id']
    type_slot = request_data['type_slot']
    doctor_pk = request_data['doctor_pk']
    date = request_data['date']
    card = Card.objects.get(pk=card_pk)
    ecp_id = card.get_ecp_id()

    if not ecp_id:
        return JsonResponse({"register": False, "message": "Пациент не найден в ЕЦП"})

    doctor_data = DoctorProfile.objects.filter(rmis_location=doctor_pk).first()
    age_target_patient = card.individual.age(days_monthes_years=True, target_date=date)
    age_month = age_target_patient[2] * 12 + age_target_patient[1]
    if doctor_data.max_age_patient_registration != -1 and (age_month > doctor_data.max_age_patient_registration):
        return JsonResponse({"register": False, "message": "Запись ограничена по возрасту"})
    r = register_patient_ecp_slot(ecp_id, slot_id, type_slot)
    return JsonResponse(r)


@login_required
def cancel_slot(request):
    request_data = json.loads(request.body)
    slot_id = request_data['slotId']
    patent_pk = request_data['patentPk']
    rmis_location = request_data['rmisLocation']
    type_slot = request_data['typeSlot']
    result = cancel_ecp_patient_record(slot_id, type_slot)
    if result:
        card_patient = Card.objects.filter(pk=patent_pk).first()
        Log.log(key=patent_pk, type=140001, user=request.user.doctorprofile,
                body={"slot_id": slot_id, "type_slot": type_slot, "rmis_location": rmis_location, "patient": card_patient.get_fio_w_card()})
    return JsonResponse({"result": result})

@@ -2388,16 +2388,29 @@
 Log.log(
+%0A            
 key=pate
@@ -2415,16 +2415,28 @@
 tent_pk,
+%0A           
  type=14
@@ -2440,16 +2440,28 @@
 =140001,
+%0A           
  user=re
@@ -2486,20 +2486,16 @@
 rofile,%0A
-    
         
@@ -2621,16 +2621,26 @@
 _card()%7D
+,%0A        
 )%0A    re

Update api/ecp/views.py