import base64
import os

from django.core.paginator import Paginator
from cda.integration import render_cda
from l2vi.integration import gen_cda_xml, send_cda_xml
import collections

from integration_framework.views import get_cda_data
from utils.response import status_response
from hospitals.models import Hospitals
import operator
import re
import time
from datetime import datetime, time as dtime, timedelta
from operator import itemgetter

import pytz
import simplejson as json
from dateutil.relativedelta import relativedelta
from django.contrib.auth.decorators import
 login_required
from django.core.files.base import ContentFile
from django.db import transaction
from django.db.models import Q, Prefetch
from django.http import HttpRequest
from django.http import JsonResponse
from django.utils import dateformat
from django.utils import timezone
from api import sql_func
from api.dicom import search_dicom_study
from api.patients.
views import save_dreg
from api.sql_func import get_fraction_result, get_field_result
from api.stationar.stationar_func import forbidden_edit_dir, desc_to_data
from api.views import get_reset_time_vars
from appconf.manager import SettingManager
from clients.models import Card, DocumentType, Individual, DispensaryReg, BenefitReg
from directions.models import (
    DirectionDocument,
    DocumentSign,
    Napravleniya,
    Issledovaniya,
    NumberGenerator,
    Result,
    ParaclinicResult,
    Recipe,
    MethodsOfTaking,
    ExternalOrganization,
    MicrobiologyResultCulture,
    MicrobiologyResultCultureAntibiotic,
    DirectionToUserWatch,
    IstochnikiFinansirovaniya,
    DirectionsHistory,
    MonitoringResult,
    TubesRegistration,
    DirectionParamsResult,
    IssledovaniyaFiles,
)
from directory.models import Fractions, ParaclinicInputGroups, ParaclinicTemplateName, ParaclinicInputField, HospitalService, Researches
from laboratory import settings
from laboratory import utils
from laboratory.decorators import group_required
from laboratory.settings import DICOM_SERVER, TIME_ZONE
from laboratory.utils import current_year, strdatetime, strdate, strtime, tsdatetime, start_end_year, strfdatetime, current_time
from pharmacotherapy.models import ProcedureList, ProcedureListTimes, Drugs, FormRelease, MethodsReception
from results.sql_func import get_not_confirm_direction, get_laboratory_results_by_directions
from results.views import result_normal, result_print
from rmis_integration.client import Client, get_direction_full_data_cache
from slog.models import Log
from statistics_tickets.models import VisitPurpose, ResultOfTreatment, Outcomes, Place
from users.models import DoctorProfile
from utils.common import non_selected_visible_type, none_if_minus_1, values_from_structure_data
from utils.dates import normalize_date, date_iter_range, try_strptime
from utils.dates import try_parse_range
from utils.xh import check_float_is_valid, short_fio_dots
from .sql_func import get_history_dir, get_confirm_direction, filter_direction_department, get_lab_podr, filter_direction_doctor, get_confirm_direction_patient_year, get_patient_contract
from api.stationar.stationar_func import hosp_get_hosp_direction, hosp_get_text_iss
from forms.forms_func import hosp_get_operation_data
from medical_certificates.models import ResearchesCertificate, MedicalCertificates
from utils.data_verification import data_parse
from utils.expertise import get_expertise


@login_required
@group_required("Лечащий врач", "Врач-лаборант", "Оператор лечащего врача", "Заполнение мониторингов", "Свидетельство о смерти-доступ")
def directions_generate(request):
    result = {"ok": False, "directions": [], "directionsStationar": [], "message": ""}
    if request.method == "POST":
        p = json.loads(request.body)
        card_pk = p.get("card_pk")
        card = None
        if card_pk == -1:
            hospital: Hospitals = request.user.doctorprofile.get_hospital()
            if hospital.client:
                card = hospital.client
            else:
                card = Individual.import_from_tfoms(
                    {
                        "enp": f"1010{hospital.code_tfoms}",
                        "family": "Больница",
                        "given": hospital.safe_short_title[:120],
                        "patronymic": "",
                        "gender": 'м',
                        "birthdate": '2000-01-01',
                    },
                    need_return_card=True,
                )
                hospital.client = card
                hospital.save()
            if card:
                card_pk = card.pk
        else:
            card = Card.objects.get(pk=card_pk)
        if card.base.forbidden_create_napr:
            result["message"] = "Для данного типа карт нельзя создать направления"
            return JsonResponse(result)
        fin_source = p.get("fin_source", -1)
        fin_source_pk = int(fin_source) if (isinstance(fin_source, int) or str(fin_source).isdigit()) else fin_source
        args = [
            card_pk,
            p.get("diagnos"),
            fin_source_pk,
            p.get("history_num"),
            p.get("ofname_pk"),
            request.user.doctorprofile,
            p.get("researches"),
            p.get("comments"),
            p.get("for_rmis"),
            p.get("rmis_data", {}),
        ]
        kwargs = dict(
            vich_code=p.get("vich_code", ""),
            count=p.get("count", 1),
            discount=p.get("discount", 0),
            parent_iss=p.get("parent_iss", None),
            parent_slave_hosp=p.get("parent_slave_hosp", None),
            counts=p.get("counts", {}),
            localizations=p.get("localizations", {}),
            service_locations=p.get("service_locations", {}),
            direction_purpose=p.get("direction_purpose", "NONE"),
            external_organization=p.get("external_organization", "NONE"),
            direction_form_params=p.get("direction_form_params", {}),
            current_global_direction_params=p.get("current_global_direction_params", {}),
            hospital_department_override=p.get("hospital_department_override", -1),
        )
        for _ in range(p.get("directions_count", 1)):
            rc = Napravleniya.gen_napravleniya_by_issledovaniya(*args, **kwargs)
            result["ok"] = rc["r"]
            if "message" in rc:
                result["message"] = rc["message"]
            result["directions"].extend(rc["list_id"])
            result["directionsStationar"].extend(rc["list_stationar_id"])
            if not result["ok"]:
                break

        if result["ok"]:
            for pk in result["directions"]:
                d: Napravleniya = Napravleniya.objects.get(pk=pk)
                d.fill_acsn()
    return JsonResponse(result)


@login_required
@group_required("Лечащий врач", "Врач-лаборант", "Врач консультаций")
def add_additional_issledovaniye(request):
    saved = False
    p = json.loads(request.body)
    direction_pk = p.get("direction_pk", None)
    who_add = request.user.doctorprofile
    researches = p.get("researches", None)
    pks = []
    created_later_research = {x: True for x in Issledovaniya.objects.values_list("research_id", flat=True).filter(napravleniye_id=direction_pk)}
    with transaction.atomic():
        for research_pk in researches:
            if research_pk not in created_later_research:
                iss = Issledovaniya(napravleniye_id=direction_pk, research_id=research_pk, doc_add_additional=who_add)
                iss.save()
                pks.append(iss.pk)
                saved = True
    if saved:
        return status_response(True, data={"pks": pks})
    return status_response(False, "Операция не выполнена")


@login_required
def directions_history(request):
    # SQL-query
    res = {"directions": []}
    request_data = json.loads(request.body)
    pk = request_data.get("patient", -1)
    req_status = request_data.get("type", 4)
    iss_pk = request_data.get("iss_pk", None)
    for_slave_hosp = request_data.get("forHospSlave", False)
    services = request_data.get("services", [])
    services = list(map(int, services or []))

    date_start, date_end = try_pars