import pdfkit
import pytz
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.shortcuts import render, redirect, get_object_or_404
from django.http import FileResponse, HttpResponse

# Create your views here.
from datetime import date, datetime, timedelta

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils import timezone

from bpjs.bpjs import AntrianBPJS, Vclaim
from faskes.models import InformasiDasarFaskes
from otentifikasi.models import Biodata, MenuItem
from pelayanan.models import CaraBayar, Kelas, TarifLayanan, InvoiceLayanan, Dokumenlab, TarifLab, InvoiceLab, InvoiceBed, Kamar, JasaMedis, SubLayanan
from pemeriksaan.models import Antrian, Loket, TaskId, CaraMasuk, Pendaftaran, LogTaskId, \
    Icd10, InputIcd10, AntrianBpjs, AnalisaMasalahKeperawatan, Edukasi, Dirujuk, PemeriksaanPendaftaranViews, \
    Odontogram, Provinsi, Kabupaten, Kecamatan, Desa, Checkeropname, Opname, PendaftaranViews, PemeriksaanLabUmum, \
    PemeriksaanLabTripleE, PemeriksaanLabUmumHistory, PemeriksaanLabTripleEHistory, Bidan, Pekerjaan
from penjualan.models import InvoiceBarang, Barang, HargaList, HargaListHistory
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django_serverside_datatable.views import ServerSideDatatableView

# rydev
from collections import Counter
from django.http import JsonResponse
from django.core import serializers
from django.db.models import OuterRef, Subquery, F, Q, Sum, DecimalField, IntegerField, Case, When, Value
from dateutil.relativedelta import relativedelta
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font, PatternFill, Border, Side
from openpyxl.utils import get_column_letter
from django.views.decorators.csrf import csrf_exempt
from django.db import transaction, OperationalError
import time
import json
from pembayaran.models import CekPembayaran, Pembayaran
import os
import pandas as pd
import calendar
from django.conf import settings
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from django.core.files.storage import default_storage
from django.db.models import Count
from promotion.models import PromotionDiskonHistory
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
channel_layer = get_channel_layer()
# status:
# progress
# selesai
# batal


@login_required
def pilihantrian(request):
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()

    return render(request, 'antrian/pilihantrian.html', {'menu_items': menu_items})


@login_required
def antrian(request):
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()

    return render(request, 'antrian/antrian.html', {'menu_items': menu_items})


@login_required
def antrianbpjs(request):
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()

    return render(request, 'antrian/antrianbpjs.html', {'menu_items': menu_items})


@login_required
def antrianambilnomor(request):
    current_datetime = timezone.now()
    formatted_date = current_datetime.strftime("%Y%m%d")
    antrian = Antrian.objects.filter(tanggal_mengantri=timezone.now().date())
    if antrian.exists():
        text = antrian.last().nomor_antrian
        a_index = text.index("A")
        result = text[a_index + 1:]
        last_no_antrian = int(result)
    else:
        last_no_antrian = 0
    urutan_antrian = last_no_antrian + 1
    new_no_antrian = 'A' + str(urutan_antrian)
    kode_booking = "{0}{1}".format(formatted_date, new_no_antrian)
    antriancreate = Antrian(
        nomor_antrian=new_no_antrian,
        kode_booking=kode_booking,
        tanggal_mengantri=timezone.now().date(),
        status='progress',
    )
    taskidcreate = TaskId(
        kode_booking=kode_booking,
        status=1,
        catatan='mulai waktu tunggu admisi',
    )
    logtaskid = LogTaskId(
        relasi=taskidcreate,
        status=1,
        catatan='mulai waktu tunggu admisi'
    )
    antriancreate.save()
    taskidcreate.save()
    logtaskid.save()
    return redirect('pilihantrian')


@login_required
def antrianambilnomorbpjs(request):
    current_datetime = timezone.now()
    formatted_date = current_datetime.strftime("%Y%m%d")
    antrianbpjs = AntrianBpjs.objects.filter(tanggal_mengantri=timezone.now().date())
    if antrianbpjs.exists():
        text = antrianbpjs.last().nomor_antrian
        a_index = text.index("B")
        result = text[a_index + 1:]
        last_no_antrian = int(result)
    else:
        last_no_antrian = 0
    urutan_antrian = last_no_antrian + 1
    new_no_antrian = 'B' + str(urutan_antrian)
    kode_booking = "{0}{1}".format(formatted_date, new_no_antrian)
    antriancreate = AntrianBpjs(
        nomor_antrian=new_no_antrian,
        kode_booking=kode_booking,
        tanggal_mengantri=timezone.now().date(),
        status='progress',
    )
    taskidcreate = TaskId(
        kode_booking=kode_booking,
        status=1,
        catatan='mulai waktu tunggu admisi',
    )
    logtaskid = LogTaskId(
        relasi=taskidcreate,
        status=1,
        catatan='mulai waktu tunggu admisi'
    )
    antriancreate.save()
    taskidcreate.save()
    logtaskid.save()
    return redirect('pilihantrian')


@login_required
def antrianloketpemanggil(request):
    antrian = Antrian.objects.filter(tanggal_mengantri=timezone.now().date(), status='progress').order_by('id')
    antrianbpjs = AntrianBpjs.objects.filter(tanggal_mengantri=timezone.now().date(), status='progress').order_by('id')
    loketanda = Loket.objects.filter(petugas__username=request.user.username).first()
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        "loketanda": loketanda,
        "antrian": antrian,
        "antrianbpjs": antrianbpjs,
        "menu_items": menu_items,
    }

    return render(request, 'antrian/loketpemanggil.html', context)


@login_required
def antrianclaim(request):
    data = request.POST
    antrian = Antrian.objects.get(id=request.POST.get('id'))
    loket = Loket.objects.get(petugas__username=request.user.username)
    antrian.loket = loket
    if TaskId.objects.filter(kode_booking=data.get('kode_booking')).exists():
        taskid = TaskId.objects.get(kode_booking=data.get('kode_booking'))
        taskid.status = 2
        taskid.save()
        logtaskid = LogTaskId(
            relasi=taskid,
            status=2,
            catatan='akhir waktu tunggu admisi/mulai waktu layan admisi'
        )
        logtaskid.save()
    else:
        taskid = TaskId(
            kode_booking=data.get('kode_booking'),
            status=2,
            catatan='akhir waktu tunggu admisi/mulai waktu layan admisi'
        )
        taskid.save()
        logtaskid = LogTaskId(
            relasi=taskid,
            status=2,
            catatan='akhir waktu tunggu admisi/mulai waktu layan admisi'
        )
        logtaskid.save()
    antrian.save()
    return redirect('antrianloketpemanggil')


@login_required
def antrianclaimbpjs(request):
    data = request.POST
    antrian = AntrianBpjs.objects.get(id=request.POST.get('id'))
    loket = Loket.objects.get(petugas__username=request.user.username)
    antrian.loket = loket
    if TaskId.objects.filter(kode_booking=data.get('kode_booking')).exists():
        taskid = TaskId.objects.get(kode_booking=data.get('kode_booking'))
        taskid.status = 2
        taskid.save()
        logtaskid = LogTaskId(
            relasi=taskid,
            status=2,
            catatan='akhir waktu tunggu admisi/mulai waktu layan admisi'
        )
        logtaskid.save()
    else:
        taskid = TaskId(
            kode_booking=data.get('kode_booking'),
            status=2,
            catatan='akhir waktu tunggu admisi/mulai waktu layan admisi'
        )
        taskid.save()
        logtaskid = LogTaskId(
            relasi=taskid,
            status=2,
            catatan='akhir waktu tunggu admisi/mulai waktu layan admisi'
        )
        logtaskid.save()
    antrian.save()
    return redirect('antrianloketpemanggil')


@login_required
def antrianbatal(request):
    antrian = Antrian.objects.get(id=request.POST.get('id'))
    antrian.status = 'batal'
    antrian.save()
    return redirect('antrianloketpemanggil')


@login_required
def antrianbatalbpjs(request):
    antrian = AntrianBpjs.objects.get(id=request.POST.get('id'))
    antrian.status = 'batal'
    antrian.save()
    return redirect('antrianloketpemanggil')


@login_required
def antrianpilihloket(request):
    if Loket.objects.filter(petugas__username=request.user.username).exists():
        loketanda = Loket.objects.get(petugas__username=request.user.username)
        loketanda.nama = request.POST.get('nama')
        loketanda.save()
        return redirect('antrianloketpemanggil')
    else:
        petugas_loket = Biodata.objects.get(username=request.user.username)
        buatloket = Loket(
            nama=request.POST.get('nama'),
            petugas=petugas_loket
        )
        buatloket.save()
        return redirect('antrianloketpemanggil')


@login_required
def automengantri(request):
    waktusekarang = datetime.now()
    antrian = Antrian.objects.filter(tanggal_mengantri=timezone.now().date()).order_by('id')
    if antrian.exists():
        text = antrian.last().nomor_antrian
        a_index = text.index("A")
        result = text[a_index + 1:]
        nomor_sekarang = int(result)
    else:
        nomor_sekarang = 0
        print('masuk sini')
    hitungan = nomor_sekarang + 1
    nomor_antrian = 'A' + str(hitungan)
    context = {
        'waktusekarang': waktusekarang,
        'antrian': antrian,
        'nomor_antrian': nomor_antrian,
    }
    print(nomor_sekarang)
    return render(request, 'snippets/automengantri.html', context)


@login_required
def automengantribpjs(request):
    waktusekarang = datetime.now()
    antrian = AntrianBpjs.objects.filter(tanggal_mengantri=timezone.now().date()).order_by('id')
    if antrian.exists():
        text = antrian.last().nomor_antrian
        a_index = text.index("B")
        result = text[a_index + 1:]
        nomor_sekarang = int(result)
    else:
        nomor_sekarang = 0
        print('masuk sini')
    hitungan = nomor_sekarang + 1
    nomor_antrian = 'B' + str(hitungan)
    context = {
        'waktusekarang': waktusekarang,
        'antrian': antrian,
        'nomor_antrian': nomor_antrian,
    }
    print(nomor_sekarang)
    return render(request, 'snippets/automengantribpjs.html', context)


@login_required
def autowaktusekarang(request):
    data = timezone.now()
    return render(request, 'snippets/autowaktusekarang.html', {"data": data})


@login_required
def cekkepesertaan(request):
    data = request.POST
    current_date = timezone.now()
    formatted_date = current_date.strftime('%Y-%m-%d')
    route = 'Peserta/{0}/{1}/tglSEP/{2}'.format(data.get('cekkepesertaan'), data.get('nomor'), formatted_date)
    req = Vclaim(route=route)
    req.get()
    print(req.response)
    if req.data:
        data = req.data
        nokartu = data['peserta']['noKartu']
        nik = data['peserta']['nik']
        nama = data['peserta']['nama']
        pisa = data['peserta']['pisa']
        sex = data['peserta']['sex']
        noMR = data['peserta']['mr']['noMR']
        noTelepon = data['peserta']['mr']['noTelepon']
        tglLahir = data['peserta']['tglLahir']
        tglCetakKartu = data['peserta']['tglCetakKartu']
        tglTAT = data['peserta']['tglTAT']
        tglTMT = data['peserta']['tglTMT']
        kodeStatusPeserta = data['peserta']['statusPeserta']['kode']
        keteranganStatusPeserta = data['peserta']['statusPeserta']['keterangan']
        kdProvider = data['peserta']['provUmum']['kdProvider']
        nmProvider = data['peserta']['provUmum']['nmProvider']
        kodeJenisPeserta = data['peserta']['jenisPeserta']['kode']
        keteranganJenisPeserta = data['peserta']['jenisPeserta']['keterangan']
        kodeHakKelas = data['peserta']['hakKelas']['kode']
        keteranganHakKelas = data['peserta']['hakKelas']['keterangan']
        umurSekarang = data['peserta']['umur']['umurSekarang']
        umurSaatPelayanan = data['peserta']['umur']['umurSaatPelayanan']
        dinsos = data['peserta']['informasi']['dinsos']
        prolanisPRB = data['peserta']['informasi']['prolanisPRB']
        noSKTM = data['peserta']['informasi']['noSKTM']
        eSEP = data['peserta']['informasi']['eSEP']
        noAsuransi = data['peserta']['cob']['noAsuransi']
        nmAsuransi = data['peserta']['cob']['nmAsuransi']
        tglTMT_COB = data['peserta']['cob']['tglTMT']
        tglTAT_COB = data['peserta']['cob']['tglTAT']
        current_datetime = timezone.now()
        anyformatted_datetime = current_datetime.strftime("%Y%m%d%H%M%S")
        if request.POST.get('kode_booking'):
            kode_booking = request.POST.get('kode_booking')
        else:
            kode_booking = "{0}".format(anyformatted_datetime)
        pasien = Biodata.objects.filter(groups__name='PASIEN').last()
        nomor_rekam_medis = int(pasien.nomor_rekam_medis) + 1
        nomor_rekam_medis_str = str(nomor_rekam_medis).zfill(6)
        while Biodata.objects.filter(nomor_rekam_medis=nomor_rekam_medis_str).exists():
            nomor_rekam_medis += 1
            nomor_rekam_medis_str = str(nomor_rekam_medis).zfill(6)
        dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
        carabayar = CaraBayar.objects.all()
        caramasuk = CaraMasuk.objects.all()
        kelas = Kelas.objects.all()
        user_groups = request.user.groups.all()

        # GET MENU BY GROUPS #RYDEV
        menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
        context = {
            'kode_booking': kode_booking,
            'pasien': pasien,
            'nomor_rekam_medis_str': nomor_rekam_medis_str,
            'dokter': dokter,
            'carabayar': carabayar,
            'caramasuk': caramasuk,
            'kelas': kelas,
            'nokartu': nokartu,
            'nik': nik,
            'nama': nama,
            'pisa': pisa,
            'sex': sex,
            'noMR': noMR,
            'noTelepon': noTelepon,
            'tglLahir': tglLahir,
            'tglCetakKartu': tglCetakKartu,
            'tglTAT': tglTAT,
            'tglTMT': tglTMT,
            'kodeStatusPeserta': kodeStatusPeserta,
            'keteranganStatusPeserta': keteranganStatusPeserta,
            'kdProvider': kdProvider,
            'nmProvider': nmProvider,
            'kodeJenisPeserta': kodeJenisPeserta,
            'keteranganJenisPeserta': keteranganJenisPeserta,
            'kodeHakKelas': kodeHakKelas,
            'keteranganHakKelas': keteranganHakKelas,
            'umurSekarang': umurSekarang,
            'umurSaatPelayanan': umurSaatPelayanan,
            'dinsos': dinsos,
            'prolanisPRB': prolanisPRB,
            'noSKTM': noSKTM,
            'eSEP': eSEP,
            'noAsuransi': noAsuransi,
            'nmAsuransi': nmAsuransi,
            'tglTMT_COB': tglTMT_COB,
            'tglTAT_COB': tglTAT_COB,
            'menu_items':menu_items
        }
        return render(request, 'pemeriksaan/pendaftaran/pendaftaran.html', context)
    else:
        messages.info(request, 'DATA KEPESERTAAN TIDAK DITEMUKAN')
        return redirect('/pemeriksaan/pendaftaran')


# pendaftaran ------------------------------------------------------------------------------->
# rydev ------------------------------------------------------------------------------->

def get_kota(request):
    if request.POST.get('parent_id'):
        parent_id = request.POST.get('parent_id')
    else:
        parent_id = 0

    arr_kota = Kabupaten.objects.filter(parent_id=parent_id).values()
    return JsonResponse(list(arr_kota), safe=False)

def get_kecamatan(request):
    if request.POST.get('parent_id'):
        parent_id = request.POST.get('parent_id')
    else:
        parent_id = 0

    arr_kecamatan = Kecamatan.objects.filter(parent_id=parent_id).values()
    return JsonResponse(list(arr_kecamatan), safe=False)

def get_kelurahan(request):
    if request.POST.get('parent_id'):
        parent_id = request.POST.get('parent_id')
    else:
        parent_id = 0

    arr_desa = Desa.objects.filter(parent_id=parent_id).values()
    return JsonResponse(list(arr_desa), safe=False)

@login_required
def modalpendaftaran(request):
    current_datetime = timezone.now()
    jakarta_tz = pytz.timezone('Asia/Jakarta')
    current_datetimez = timezone.now().astimezone(jakarta_tz)
    current_date = current_datetimez.strftime('%d-%m-%Y')
    anyformatted_datetime = current_datetime.strftime("%d%m%Y%H%M%S")
    if request.POST.get('kode_booking'):
        kode_booking = request.POST.get('kode_booking')
    else:
        kode_booking = "{0}".format(anyformatted_datetime)
    pasien = Biodata.objects.filter(groups__name='PASIEN').last()
    if pasien is None:
        nomor_rekam_medis = 000000
    else:
        nomor_rekam_medis = pasien.nomor_rekam_medis

    nomor_rekam_medis = int(nomor_rekam_medis) + 1
    nomor_rekam_medis_str = str(nomor_rekam_medis).zfill(6)
    while Biodata.objects.filter(nomor_rekam_medis=nomor_rekam_medis_str).exists():
        nomor_rekam_medis += 1
        nomor_rekam_medis_str = str(nomor_rekam_medis).zfill(6)
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
    carabayar = CaraBayar.objects.all()
    caramasuk = CaraMasuk.objects.all()
    kelas = Kelas.objects.all()
    user_groups = request.user.groups.all()

    arr_province = Provinsi.objects.all()
    semuapendaftaran = Pendaftaran.objects.all()
    pekerjaan = Pekerjaan.objects.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'current_date': current_date,
        'kode_booking': kode_booking,
        'pasien': pasien,
        'nomor_rekam_medis_str': nomor_rekam_medis_str,
        'dokter': dokter,
        'carabayar': carabayar,
        'caramasuk': caramasuk,
        'kelas': kelas,
        'menu_items': menu_items,
        'arr_province' : arr_province,
        'semuapendaftaran': semuapendaftaran,
        'pekerjaan': pekerjaan,
    }
    return render(request, 'pemeriksaan/pendaftaran/form-daftar-pasien-existing.html', context)

@login_required
def panggil_pasien(request, id):
    get_pasien = Pendaftaran.objects.get(id=id)

    get_pasien.status = 'progress'
    get_pasien.save() 

    return JsonResponse({'status': 'berhasil'}, safe=False)

@login_required
def pendaftaran(request):
    current_datetime = timezone.now()
    anyformatted_datetime = current_datetime.strftime("%Y%m%d%H%M%S")
    if request.POST.get('kode_booking'):
        kode_booking = request.POST.get('kode_booking')
    else:
        kode_booking = "{0}".format(anyformatted_datetime)
    pasien = Biodata.objects.filter(groups__name='PASIEN').last()
    if pasien is None:
        nomor_rekam_medis = 000000
    else:
        nomor_rekam_medis = pasien.nomor_rekam_medis

    nomor_rekam_medis = int(nomor_rekam_medis) + 1
    nomor_rekam_medis_str = str(nomor_rekam_medis).zfill(6)
    while Biodata.objects.filter(nomor_rekam_medis=nomor_rekam_medis_str).exists():
        nomor_rekam_medis += 1
        nomor_rekam_medis_str = str(nomor_rekam_medis).zfill(6)
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
    carabayar = CaraBayar.objects.all()
    caramasuk = CaraMasuk.objects.all()
    kelas = Kelas.objects.all()
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'kode_booking': kode_booking,
        'pasien': pasien,
        'nomor_rekam_medis_str': nomor_rekam_medis_str,
        'dokter': dokter,
        'carabayar': carabayar,
        'caramasuk': caramasuk,
        'kelas': kelas,
        'menu_items': menu_items,
    }
    return render(request, 'pemeriksaan/pendaftaran/pendaftaran.html', context)


@login_required
def post_pendaftaran(request):
    current_datetime = datetime.now()
    data = request.POST
    time = current_datetime.strftime('%H:%M:%S')
    if data.get('tanggal_masuk') is None or data.get('tanggal_masuk') == '':
        backdate = current_datetime.strftime('%Y-%m-%d')
    else:
        backdate = datetime.strptime(data.get('tanggal_masuk'), '%d-%m-%Y').strftime('%Y-%m-%d')
    dibuat_tanggal = f"{backdate} {time}"
    combined_datetime_obj = datetime.strptime(dibuat_tanggal, '%Y-%m-%d %H:%M:%S')
    combined_datetime_obj_utc = combined_datetime_obj.astimezone(timezone.utc)
    tanggal_masuk = combined_datetime_obj_utc + timedelta(minutes=10)
    tanggal_keluar = combined_datetime_obj_utc + timedelta(minutes=30)
    if data.get('cara_bayar') == 'JKN' or data.get('cara_bayar') == 1:
        print('masuk sini masuk sini')
        print('masuk sini masuk sini')
        print('masuk sini masuk sini')
        print('masuk sini masuk sini')
        print('masuk sini masuk sini')
        current_datetime = timezone.now()
        formatted_date = current_datetime.strftime("%Y-%m-%d")
        if data.get('nomor_induk_kependudukan'):
            route = 'Peserta/nik/{0}/tglSEP/{1}'.format(data.get('nomor_induk_kependudukan'), formatted_date)
            req = Vclaim(route=route)
            req.get()
            if req.response.status_code == 200:
                data = req.data
                hakkelas = data["peserta"]["hakKelas"]["kode"]
                if hakkelas == '1' or hakkelas == '2' or hakkelas == '3' or hakkelas == 1 or hakkelas == 2 or hakkelas == 3:
                    pass
                else:
                    messages.info('Nomor NIK tidak ditemukan, harap cek kembali NIK anda')
                    return HttpResponse('#')
            else:
                messages.info('Nomor NIK tidak ditemukan')
                return HttpResponse('#')
        elif data.get('nomor_kartu_bpjs'):
            route = 'Peserta/nokartu/{0}/tglSEP/{1}'.format(data.get('nomor_kartu_bpjs'), formatted_date)
            req = Vclaim(route=route)
            req.get()
            if req.response.status_code == 200:
                data = req.data
                hakkelas = data["peserta"]["hakKelas"]["kode"]
                if hakkelas is None:
                    messages.info('Nomor Kartu BPJS tidak ditemukan, harap cek kembali NOKA BPJS anda')
                    return HttpResponse('#')
            else:
                messages.info('Nomor Kartu BPJS tidak ditemukan')
                return HttpResponse('#')
    anyformatted_datetime = current_datetime.strftime("%Y%m%d%H%M%S")
    if Antrian.objects.filter(kode_booking=data.get('kode_booking')).exists():
        antriandimaksud = Antrian.objects.get(kode_booking=data.get('kode_booking'))
        antriandimaksud.status = 'selesai'
        antriandimaksud.catatan = 'Sudah selesai dilayani di loket pemanggilan'
        antriandimaksud.save()
    if AntrianBpjs.objects.filter(kode_booking=data.get('kode_booking')).exists():
        antriandimaksud = AntrianBpjs.objects.get(kode_booking=data.get('kode_booking'))
        antriandimaksud.status = 'selesai'
        antriandimaksud.catatan = 'Sudah selesai dilayani di loket pemanggilan'
        antriandimaksud.save()
    if request.method == 'POST':
        nomor_rekam_medis = data.get('nomor_rekam_medis')
        pasien_ada = Biodata.objects.filter(groups__name='PASIEN').last()
        if pasien_ada is None:
            nomor_rme = data.get('nomor_rekam_medis_post_exist')
        else:
            pasien_ada = Biodata.objects.filter(groups__name='PASIEN').last()
            # nomor_rme = int(pasien_ada.nomor_rekam_medis) + 1
            nomor_rme = data.get('nomor_rekam_medis_post_exist')
            
        nomor_rekam_medis_ada = int(nomor_rme)
        nomor_rekam_medis_ada_str = str(nomor_rekam_medis_ada).zfill(6)
        if nomor_rekam_medis is None:
            pasien = Biodata(
                username=f'PS{nomor_rekam_medis_ada_str}',
                first_name=data.get('first_name_lama'),
                last_name='PS',
                password='pbkdf2_sha256$600000$0HrEDsM4YKfdoHIJAhE9rB$TNWkd4V6T7zWPFmZJAONbX/THc6pSfx/3I698ZKNmFI=',
                nomor_rekam_medis=nomor_rekam_medis_ada_str,
                nomor_induk_kependudukan=data.get('nomor_induk_kependudukan_lama'),
                nomor_kartu_bpjs=data.get('nomor_kartu_bpjs_lama'),
                jenis_kelamin=data.get('jenis_kelamin_lama'),
                tempat_lahir=data.get('tempat_lahir_lama'),
                tanggal_lahir=data.get('tanggal_lahir_lama'),
                negara=data.get('negara_lama'),
                provinsi=data.get('provinsi_lama'),
                kota=data.get('kota_lama'),
                kecamatan=data.get('kecamatan_lama'),
                kelurahan=data.get('kelurahan_lama'),
                alamat=data.get('alamat_lama'),
                kontak=data.get('kontak_lama'),
                nama_ibu_kandung=data.get('nama_ibu_kandung_lama'),
                kepala_keluarga=data.get('kepala_keluarga_lama'),
                pekerjaan=data.get('pekerjaan_lama'),
                pendidikan=data.get('pendidikan_lama'),
                nama_kontak_darurat=data.get('nama_kontak_darurat_lama'),
                kontak_darurat=data.get('kontak_darurat_lama'),
                agama=data.get('agama_lama'),
                catatan=data.get('catatan_lama'),
                alias=data.get('alias_text'),
            )
            pendaftaran = Pendaftaran(
                kode=anyformatted_datetime,
                nomor_surat_rujukan=data.get('nomor_surat_rujukan'),
                kode_booking=data.get('kode_booking'),
                rujukan_dari=data.get('rujukan_dari'),
                catatan=data.get('catatan'),
                status='arrived',
                dokter=Biodata.objects.get(id=data.get('dokter')),
                petugas=Biodata.objects.get(username=request.user.username),
                pasien=pasien,
                ruang_rawat_pasien=data.get('ruang_rawat_pasien'),
                nama_penandatangan_pasien=pasien.first_name,
                hubungan_dengan_pasien=data.get('hubungan_dengan_pasien'),
                cara_bayar=data.get('cara_bayar'),
                diagnosa_awal=data.get('diagnosa_awal'),
                kelas='3',
                cara_masuk=CaraMasuk.objects.get(id=data.get('cara_masuk')),
                keadaan_masuk=data.get('keadaan_masuk'),
                laka_lantas=data.get('laka_lantas'),
                cob=data.get('cob'),
                katarak=data.get('katarak'),
                created_at=dibuat_tanggal,
                waktu_masuk=tanggal_masuk,
                waktu_keluar=tanggal_keluar,
                is_new_pasien=True,
                tindakan_lab=data.get('tindakan_lab'),
            )
            pasien.save()
            pendaftaran.save()
            group = Group.objects.get(id=2)  # Dapatkan objek grup yang sesuai dengan ID 2
            pasien.groups.set([group])  # Tetapkan grup yang ditemukan ke objek pasien
            pasien.save()
            if TaskId.objects.filter(kode_booking=data.get('kode_booking')).exists():
                taskid = TaskId.objects.get(kode_booking=data.get('kode_booking'))
                taskid.pasien = pendaftaran.pasien
                taskid.status = 3
                logtaskid = LogTaskId(
                    relasi=taskid,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                taskid.save()
                logtaskid.save()
            else:
                taskid = TaskId(
                    kode_booking=data.get('kode_booking'),
                    pasien=pendaftaran.pasien,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                logtaskid = LogTaskId(
                    relasi=taskid,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                taskid.save()
                logtaskid.save()
        elif Biodata.objects.filter(nomor_rekam_medis=nomor_rekam_medis, groups__name='PASIEN').exists():
            pasien = Biodata.objects.get(nomor_rekam_medis=nomor_rekam_medis)
            is_new_pasien = False
            pasien.first_name = data.get('first_name_lama')
            pasien.nomor_induk_kependudukan = data.get('nomor_induk_kependudukan_lama')
            pasien.nomor_kartu_bpjs = data.get('nomor_kartu_bpjs_lama')
            pasien.jenis_kelamin = data.get('jenis_kelamin_lama')
            pasien.tempat_lahir = data.get('tempat_lahir_lama')
            pasien.tanggal_lahir = data.get('tanggal_lahir_lama')
            pasien.negara = data.get('negara_lama')
            pasien.provinsi = data.get('provinsi_lama')
            pasien.kota = data.get('kota_lama')
            pasien.kecamatan = data.get('kecamatan_lama')
            pasien.kelurahan = data.get('kelurahan_lama')
            pasien.alamat = data.get('alamat_lama')
            pasien.kontak = data.get('kontak_lama')
            pasien.nama_ibu_kandung = data.get('nama_ibu_kandung_lama')
            pasien.kepala_keluarga = data.get('kepala_keluarga_lama')
            pasien.pekerjaan = data.get('pekerjaan_lama')
            pasien.pendidikan = data.get('pendidikan_lama')
            pasien.agama = data.get('agama_lama')
            pasien.nama_kontak_darurat = data.get('nama_kontak_darurat_lama')
            pasien.kontak_darurat = data.get('kontak_darurat_lama')
            pasien.catatan = data.get('catatan_lama')
            pasien.alias = data.get('alias_text')
            pasien.save()
            pendaftaran = Pendaftaran(
                kode=anyformatted_datetime,
                nomor_surat_rujukan=data.get('nomor_surat_rujukan'),
                kode_booking=data.get('kode_booking'),
                rujukan_dari=data.get('rujukan_dari'),
                catatan=data.get('catatan'),
                status='arrived',
                dokter=Biodata.objects.get(id=data.get('dokter')),
                petugas=Biodata.objects.get(username=request.user.username),
                pasien=pasien,
                ruang_rawat_pasien=data.get('ruang_rawat_pasien'),
                nama_penandatangan_pasien=pasien.first_name,
                hubungan_dengan_pasien=data.get('hubungan_dengan_pasien'),
                cara_bayar=data.get('cara_bayar'),
                diagnosa_awal=data.get('diagnosa_awal'),
                kelas='3',
                cara_masuk=CaraMasuk.objects.get(id=data.get('cara_masuk')),
                keadaan_masuk=data.get('keadaan_masuk'),
                laka_lantas=data.get('laka_lantas'),
                cob=data.get('cob'),
                katarak=data.get('katarak'),
                tindakan_lab=data.get('tindakan_lab'),
                created_at=dibuat_tanggal,
                waktu_masuk=tanggal_masuk,
                waktu_keluar=tanggal_keluar,
                is_new_pasien=is_new_pasien,
            )
            pendaftaran.save()
            if TaskId.objects.filter(kode_booking=data.get('kode_booking')).exists():
                taskid = TaskId.objects.get(kode_booking=data.get('kode_booking'))
                taskid.pasien = pendaftaran.pasien
                taskid.status = 3
                logtaskid = LogTaskId(
                    relasi=taskid,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                taskid.save()
                logtaskid.save()
            else:
                taskid = TaskId(
                    kode_booking=data.get('kode_booking'),
                    pasien=pendaftaran.pasien,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                logtaskid = LogTaskId(
                    relasi=taskid,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                taskid.save()
                logtaskid.save()
        else:
            pasien = Biodata(
                username=f'PS{nomor_rekam_medis_ada_str}',
                first_name=data.get('first_name_lama'),
                last_name='PS',
                password='pbkdf2_sha256$600000$0HrEDsM4YKfdoHIJAhE9rB$TNWkd4V6T7zWPFmZJAONbX/THc6pSfx/3I698ZKNmFI=',
                nomor_rekam_medis=nomor_rekam_medis_ada_str,
                nomor_induk_kependudukan=data.get('nomor_induk_kependudukan_lama'),
                nomor_kartu_bpjs=data.get('nomor_kartu_bpjs_lama'),
                jenis_kelamin=data.get('jenis_kelamin_lama'),
                tempat_lahir=data.get('tempat_lahir_lama'),
                tanggal_lahir=data.get('tanggal_lahir_lama'),
                negara=data.get('negara_lama'),
                provinsi=data.get('provinsi_lama'),
                kota=data.get('kota_lama'),
                kecamatan=data.get('kecamatan_lama'),
                kelurahan=data.get('kelurahan_lama'),
                alamat=data.get('alamat_lama'),
                kontak=data.get('kontak_lama'),
                nama_ibu_kandung=data.get('nama_ibu_kandung_lama'),
                kepala_keluarga=data.get('kepala_keluarga_lama'),
                pekerjaan=data.get('pekerjaan_lama'),
                pendidikan=data.get('pendidikan_lama'),
                nama_kontak_darurat=data.get('nama_kontak_darurat_lama'),
                kontak_darurat=data.get('kontak_darurat_lama'),
                agama=data.get('agama_lama'),
                catatan=data.get('catatan_lama'),
                alias=data.get('alias_text'),
            )
            pendaftaran = Pendaftaran(
                kode=anyformatted_datetime,
                nomor_surat_rujukan=data.get('nomor_surat_rujukan'),
                kode_booking=data.get('kode_booking'),
                rujukan_dari=data.get('rujukan_dari'),
                catatan=data.get('catatan'),
                status='arrived',
                dokter=Biodata.objects.get(id=data.get('dokter')),
                petugas=Biodata.objects.get(username=request.user.username),
                pasien=pasien,
                ruang_rawat_pasien=data.get('ruang_rawat_pasien'),
                nama_penandatangan_pasien=pasien.first_name,
                hubungan_dengan_pasien=data.get('hubungan_dengan_pasien'),
                cara_bayar=data.get('cara_bayar'),
                diagnosa_awal=data.get('diagnosa_awal'),
                kelas='3',
                cara_masuk=CaraMasuk.objects.get(id=data.get('cara_masuk')),
                keadaan_masuk=data.get('keadaan_masuk'),
                laka_lantas=data.get('laka_lantas'),
                cob=data.get('cob'),
                katarak=data.get('katarak'),
                tindakan_lab=data.get('tindakan_lab'),
                created_at=dibuat_tanggal,
                waktu_masuk=tanggal_masuk,
                waktu_keluar=tanggal_keluar,
                is_new_pasien=True,
            )
            pasien.save()
            pendaftaran.save()
            group = Group.objects.get(id=2)  # Dapatkan objek grup yang sesuai dengan ID 2
            pasien.groups.set([group])  # Tetapkan grup yang ditemukan ke objek pasien
            pasien.save()
            if TaskId.objects.filter(kode_booking=data.get('kode_booking')).exists():
                taskid = TaskId.objects.get(kode_booking=data.get('kode_booking'))
                taskid.pasien = pendaftaran.pasien
                taskid.status = 3
                logtaskid = LogTaskId(
                    relasi=taskid,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                taskid.save()
                logtaskid.save()
            else:
                taskid = TaskId(
                    kode_booking=data.get('kode_booking'),
                    pasien=pendaftaran.pasien,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                logtaskid = LogTaskId(
                    relasi=taskid,
                    status=3,
                    catatan='akhir waktu layan admisi/mulai waktu tunggu poli'
                )
                taskid.save()
                logtaskid.save()
        carabayarnya = CaraBayar.objects.filter(id=pendaftaran.cara_bayar).first()
        # if carabayarnya.nama == 'JKN' and pendaftaran.ruang_rawat_pasien == 'UGD':
        if carabayarnya.nama == 'JKN':
            current_datetime = timezone.now()
            formatted_date = current_datetime.strftime("%Y-%m-%d")
            if pasien.nomor_induk_kependudukan:
                route = 'Peserta/nik/{0}/tglSEP/{1}'.format(pasien.nomor_induk_kependudukan, formatted_date)
                req = Vclaim(route=route)
                req.get()
                if req.response.status_code == 200:
                    data = req.data
                    if data is not None:
                        nomor_kartu_bpjs = data["peserta"]["noKartu"]
                        hakkelas = data["peserta"]["hakKelas"]["kode"]
                        pasien.nomor_kartu_bpjs = nomor_kartu_bpjs
                        pasien.hak_kelas = hakkelas
                        pasien.save()
                    else:
                        pendaftaran.cara_bayar = 1
                        pendaftaran.save()
                        messages.info(request,
                                      'KTP Terdaftar di Disdukcapil namun tidak di BPJS, dan cara bayar otomatis '
                                      'terubah ke NON JKN')
                else:
                    messages.info('Nomor NIK tidak ditemukan')
            elif pasien.nomor_kartu_bpjs:
                route = 'Peserta/nokartu/{0}/tglSEP/{1}'.format(pasien.nomor_kartu_bpjs, formatted_date)
                req = Vclaim(route=route)
                req.get()
                if req.response.status_code == 200:
                    data = req.data
                    nomor_induk_kependudukan = data["peserta"]["nik"]
                    hakkelas = data["peserta"]["hakKelas"]["kode"]
                    pasien.nomor_induk_kependudukan = nomor_induk_kependudukan
                    pasien.hak_kelas = hakkelas
                    pasien.save()
                else:
                    messages.info('Nomor Kartu BPJS tidak ditemukan')
        messages.info(request,
                      'Pasien {0} sudah di daftarkan dengan No RM {1}'.format(pasien.first_name,
                                                                              pasien.nomor_rekam_medis))
        return redirect('/pemeriksaan/daftarpasien')
    return redirect('/pemeriksaan/daftarpasien')

@csrf_exempt
def daftarpasien(request):
    caramasuk = CaraMasuk.objects.all()
    semuapendaftaran = Pendaftaran.objects.filter(status='progress')
    dokter_nama = ''
    pasien_nama = ''
    pasien_norm = ''
    if request.POST:
        dokter_nama = request.POST.get('dokter')
        pasien_nama = request.POST.get('pasien')
        pasien_norm = request.POST.get('norm')
        if dokter_nama:
            semuapendaftaran = semuapendaftaran.filter(status='progress', dokter__first_name__icontains=dokter_nama)
        if pasien_nama:
            semuapendaftaran = semuapendaftaran.filter(status='progress', pasien__first_name__icontains=pasien_nama)
        if pasien_norm:
            semuapendaftaran = semuapendaftaran.filter(status='progress',
                                                       pasien__nomor_rekam_medis__icontains=pasien_norm)
    semuapendaftaranrajal = Pendaftaran.objects.filter(status='progress', ruang_rawat_pasien='Rawat Jalan')
    semuapendaftaranranap = Pendaftaran.objects.filter(status='progress')
    semuapendaftaranigd = Pendaftaran.objects.filter(status='progress', ruang_rawat_pasien='IGD')
    # semuapendaftaranhistory = Pendaftaran.objects.filter(status='selesai').order_by('-created_at')
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
    invoicelayanan = InvoiceLayanan.objects.filter(progress='progress')
    invoicelayananlab = InvoiceLayanan.objects.filter(progress='progress',
                                                      tarif_layanan__relasi__relasi__nama='LABORATORIUM')
    invoicelayananradiologi = InvoiceLayanan.objects.filter(progress='progress',
                                                            tarif_layanan__relasi__relasi__nama='RADIOLOGI')
    invoicebarang = InvoiceBarang.objects.filter(progress='progress')
    invoicebed = InvoiceBed.objects.filter(progress='progress')
    current_datetime = timezone.now()
    formatted_date = current_datetime.strftime("%Y-%m-%d")
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'caramasuk': caramasuk,
        'dokter_nama': dokter_nama,
        'pasien_nama': pasien_nama,
        'pasien_norm': pasien_norm,
        'semuapendaftaran': semuapendaftaran,
        'semuapendaftaranrajal': semuapendaftaranrajal,
        'semuapendaftaranranap': semuapendaftaranranap,
        'semuapendaftaranigd': semuapendaftaranigd,
        # 'semuapendaftaranhistory': semuapendaftaranhistory,
        'dokter': dokter,
        'formatted_date': formatted_date,
        'invoicelayanan': invoicelayanan,
        'invoicebarang': invoicebarang,
        'invoicebed': invoicebed,
        'invoicelayananlab': invoicelayananlab,
        'invoicelayananradiologi': invoicelayananradiologi,
        'menu_items': menu_items,
    }
    return render(request, 'pemeriksaan/daftar_pasien.html', context)

def cek_pembayaran(request, id):
    get_cek = CekPembayaran.objects.filter(pendaftaran_id=id).values()
    if not get_cek or get_cek is None:
        cek_pembayaran = False
        is_dp = False  # Assume is_dp is False if no payment information found
    else:
        cek_pembayaran = list(get_cek)[0]['is_dibayar']
        is_dp = list(get_cek)[0]['is_dp']  # Fetch is_dp value from the database
    return JsonResponse({'cek_pembayaran': cek_pembayaran, 'is_dp': is_dp}, safe=False)

@login_required
def bulk_input(request):
    data_pasien = Pendaftaran.objects.filter(status='progress')
    # return JsonResponse(list(data_pasien), safe=False)
    
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'pasien': data_pasien,
        'menu_items': menu_items,
    }
    return render(request, 'pemeriksaan/backdoor/bulk_input.html', context)

@login_required
def get_rajal(request):
    user_id = request.user.id
    usergroups = request.user.groups.all().values()
    get_usergroup = list(usergroups)
    for x in get_usergroup:
        usergroup = x['name']

    base_query = Pendaftaran.objects.all()

    if usergroup == "DOKTER":
        base_query = base_query.filter(dokter_id=user_id)

    if request.GET.get('dokter_id'):
        dokter_id = request.GET.get('dokter_id')
        # Append conditions
        base_query = base_query.filter(dokter_id=dokter_id)
    if request.GET.get('ruang_rawat_pasien'):
        ruang_rawat_pasien = request.GET.get('ruang_rawat_pasien')
        base_query = base_query.filter(ruang_rawat_pasien=ruang_rawat_pasien)
    
    base_query = base_query.filter(
        pasien__nomor_rekam_medis=OuterRef('pasien__nomor_rekam_medis')
    )

    subquery = base_query.order_by('-created_at').values('id')[:1]

    # Use the subquery to filter the main queryset
    history = Pendaftaran.objects.filter(
        id__in=Subquery(subquery),
        status__in=['arrived', 'progress']
    ).values()

    # Annotate the related data
    history = history.annotate(
        nomor_rekam_medis=F('pasien__nomor_rekam_medis'),
        alamat=F('pasien__alamat'),
        tanggal_lahir=F('pasien__tanggal_lahir'),
        nama_pasien=F('pasien__first_name'),
        nama_dokter=F('dokter__first_name'),
    )

    return JsonResponse(list(history), safe=False)

@login_required
# def get_history(request):
#     # Parse DataTables parameters
#     draw = int(request.GET.get('draw', 1))
#     start = int(request.GET.get('start', 0))
#     length = int(request.GET.get('length', 10))
#     search_value = request.GET.get('search[value]', '')

#     # Base queryset
#     base_query = Pendaftaran.objects.filter(
#         status='selesai',
#         pasien__nomor_rekam_medis=OuterRef('pasien__nomor_rekam_medis')
#     )

#     # Subquery to get the latest record for each patient
#     subquery = base_query.order_by('-created_at').values('id')[:1]

#     # Use the subquery to filter the main queryset
#     history = Pendaftaran.objects.filter(id__in=Subquery(subquery))

#     # Apply search filter if any
#     if search_value:
#         history = history.filter(
#             Q(pasien__nomor_rekam_medis__icontains=search_value) |
#             Q(pasien__alamat__icontains=search_value) |
#             Q(pasien__first_name__icontains=search_value)
#         )

#     # Get the total number of records (without filtering)
#     total_records = history.count()

#     # Apply pagination
#     history = history[start:start + length]

#     # Annotate the related data
#     history = history.annotate(
#         nomor_rekam_medis=F('pasien__nomor_rekam_medis'),
#         alamat=F('pasien__alamat'),
#         nama_pasien=F('pasien__first_name'),
#         jenis_kelamin=F('pasien__jenis_kelamin'),
#         nama_dokter=F('dokter__first_name'),
#         polinama=F('dokter__poli__nama'),
#         tanggal_lahir=F('pasien__tanggal_lahir'),
#         biaya=F('pembayaran__total_pembayaran')
#     )

#     # Prepare data for DataTables response
#     data = list(history.values())
#     response_data = {
#         'draw': draw,
#         'recordsTotal': total_records,
#         'recordsFiltered': total_records,
#         'data': data
#     }

#     return JsonResponse(response_data, safe=False)
def get_history(request):
    # Query data from the view
    data = PemeriksaanPendaftaranViews.objects.filter(status__in=['arrived', 'progress', 'selesai']).values()

    return JsonResponse(list(data), safe=False)

@login_required
def get_pasien_daily(request):
    # start_date = date.today()

    # Calculate the next day to create a range (start_date, start_date + 1 day)
    # end_date = start_date + timedelta(days=1)

    date = request.GET.get('date')
    start_date = request.GET.get('start_date') + ' 00:00:00'
    end_date = request.GET.get('end_date') + ' 00:00:00'

    if date == 'today':
        today_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
        today_end = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=999999)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(today_start, today_end), status='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(today_start, today_end)).values()

    elif date == 'week':
        week_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=timezone.localtime(timezone.now()).weekday())
        week_end = week_start + timezone.timedelta(days=6)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(week_start, week_end), status='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(week_start, week_end)).values()
        
    elif date == 'currentmonth':
        month_start = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        _, last_day_of_month = calendar.monthrange(month_start.year, month_start.month)
        month_end = timezone.localtime(timezone.now()).replace(day=last_day_of_month, hour=23, minute=59, second=59, microsecond=999999)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(month_start, month_end), status='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(month_start, month_end)).values()

    elif date == 'lastmonth':
        last_month_end = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=1)
        last_month_start = last_month_end.replace(day=1)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(last_month_start, last_month_end), status='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(last_month_start, last_month_end)).values()

    elif date == 'range':
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(start_date, end_date), status='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(start_date, end_date)).values()

    else:
        today_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
        today_end = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=999999)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(today_start, today_end), status='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(today_start, today_end)).values()

    total_progress = len(progress)
    total_all = len(show_all)
    
    return JsonResponse({'total_progress': total_progress, 'total': total_all}, safe=False)

@login_required
def get_farmasi_daily(request):
    date = request.GET.get('date')
    start_date = request.GET.get('start_date') + ' 00:00:00'
    end_date = request.GET.get('end_date') + ' 00:00:00'

    if date == 'today':
        today_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
        today_end = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=999999)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(today_start, today_end), status_plan='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(today_start, today_end)).values()

    elif date == 'week':
        week_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=timezone.localtime(timezone.now()).weekday())
        week_end = week_start + timezone.timedelta(days=6)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(week_start, week_end), status_plan='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(week_start, week_end)).values()
        
    elif date == 'currentmonth':
        month_start = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        _, last_day_of_month = calendar.monthrange(month_start.year, month_start.month)
        month_end = timezone.localtime(timezone.now()).replace(day=last_day_of_month, hour=23, minute=59, second=59, microsecond=999999)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(month_start, month_end), status_plan='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(month_start, month_end)).values()

    elif date == 'lastmonth':
        last_month_end = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=1)
        last_month_start = last_month_end.replace(day=1)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(last_month_start, last_month_end), status_plan='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(last_month_start, last_month_end)).values()
    
    elif date == 'range':
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(start_date, end_date), status_plan='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(start_date, end_date)).values()

    else:
        today_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
        today_end = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=999999)
        progress = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(today_start, today_end), status_plan='selesai').values()
        show_all = PemeriksaanPendaftaranViews.objects.filter(created_at__range=(today_start, today_end)).values()

    total_progress = len(progress)
    total_all = len(show_all)
    
    return JsonResponse({'total_progress': total_progress, 'total': total_all}, safe=False)

@login_required
def get_chart_daily(request):
     # Calculate start_date (10 days ago)
    # start_date = date.today() - timedelta(days=10)
    # end_date = date.today() + timedelta(days=1)

    filter_date = request.GET.get('filter_date')

    if filter_date == 'today':
        start_date = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
        end_date = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=999999)

    elif filter_date == 'week':
        start_date = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=timezone.localtime(timezone.now()).weekday())
        end_date = start_date + timezone.timedelta(days=6)
        
    elif filter_date == 'currentmonth':
        start_date = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        _, last_day_of_month = calendar.monthrange(start_date.year, start_date.month)
        end_date = timezone.localtime(timezone.now()).replace(day=last_day_of_month, hour=23, minute=59, second=59, microsecond=999999)

    elif filter_date == 'lastmonth':
        end_date = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=1)
        start_date = end_date.replace(day=1)
    
    elif filter_date == 'range':
        start_date = request.GET.get('start_date') + ' 00:00:00'
        end_date = request.GET.get('end_date') + ' 00:00:00'
    
    else:
        start_date = date.today() - timedelta(days=10)
        end_date = date.today() + timedelta(days=1)

    data_queryset = PemeriksaanPendaftaranViews.objects.filter(created_at__range=[start_date, end_date])

    date_totals = {}

    for record in data_queryset:
        record_date = record.created_at.date()
        formatted_date = record_date.strftime("%d %b")

        date_totals.setdefault(formatted_date, []).append(record.id)

    totals = {date_key: len(record_ids) for date_key, record_ids in date_totals.items()}

    final_data = {'date': list(reversed(date_totals.keys())), 'total': list(reversed(totals.values()))}

    # data as JSON
    return JsonResponse(final_data, safe=False)

@login_required
def get_pasien_status(request):
    filter_date = request.GET.get('filter_date')

    if filter_date == 'today':
        start_date = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
        end_date = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=999999)

    elif filter_date == 'week':
        start_date = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=timezone.localtime(timezone.now()).weekday())
        end_date = start_date + timezone.timedelta(days=6)
        
    elif filter_date == 'currentmonth':
        start_date = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        _, last_day_of_month = calendar.monthrange(start_date.year, start_date.month)
        end_date = timezone.localtime(timezone.now()).replace(day=last_day_of_month, hour=23, minute=59, second=59, microsecond=999999)

    elif filter_date == 'lastmonth':
        end_date = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=1)
        start_date = end_date.replace(day=1)
    
    elif filter_date == 'range':
        start_date = request.GET.get('start_date') + ' 00:00:00'
        end_date = request.GET.get('end_date') + ' 00:00:00'
    
    else:
        today = date.today()
        start_date = today.replace(month=today.month, day=1)
        end_date = today + timedelta(days=1)
    # Fetch data from the database for the specified date range
    get_baru = PemeriksaanPendaftaranViews.objects.filter(created_at__range=[start_date, end_date], is_new_pasien=1)

    # Initialize a dictionary to store totals for each month
    month_baru_total = {}

    # Loop through each data record and update the month_baru_total dictionary
    for record in get_baru:
        record_month = record.created_at.strftime("%b")

        # Update or initialize the month_baru_total dictionary
        month_baru_total.setdefault(record_month, 0)
        month_baru_total[record_month] += 1

    # Prepare the final data dictionary
    today = date.today()
    arr_monthb_check = [today.strftime("%b")] if not list(reversed(month_baru_total.keys())) else list(reversed(month_baru_total.keys()))
    arr_totalb_check = [0] if not list(reversed(month_baru_total.values())) else list(reversed(month_baru_total.values()))
    pasien_baru = {'month': arr_monthb_check, 'total': arr_totalb_check}

    # Fetch data from the database for the specified date range
    get_lama = PemeriksaanPendaftaranViews.objects.filter(created_at__range=[start_date, end_date], is_new_pasien=0)

    # Initialize a dictionary to store totals for each month
    month_lama_total = {}

    # Loop through each data record and update the month_lama_total dictionary
    for record in get_lama:
        record_month = record.created_at.strftime("%b")

        # Update or initialize the month_lama_total dictionary
        month_lama_total.setdefault(record_month, 0)
        month_lama_total[record_month] += 1

    # Prepare the final data dictionary
    today = date.today()
    arr_monthb_check = [today.strftime("%b")] if not list(reversed(month_lama_total.keys())) else list(reversed(month_lama_total.keys()))
    arr_totalb_check = [0] if not list(reversed(month_lama_total.values())) else list(reversed(month_lama_total.values()))
    pasien_lama = {'month': arr_monthb_check, 'total': arr_totalb_check}

    return JsonResponse({'pasien_baru': pasien_baru, 'pasien_lama': pasien_lama}, safe=False)

@login_required
def get_stok_obat(request): 
    barang_objects = Barang.objects.all()

    # Calculate the total stok, treating None as 0
    total_stok = sum(barang.stok if barang.stok is not None else 0 for barang in barang_objects)

    # Prepare the response
    response_data = {'total_stok': int(total_stok)}

    return JsonResponse(response_data, safe=False)

@login_required
def history_detail(request):
    if request.POST.get('id'):
        id = request.POST.get('id')
    else:
        id = 1
    # Create a subquery to get the latest Pendaftaran record for each unique nomor_rekam_medis
    subquery = Pendaftaran.objects.filter(
        status='selesai',
        pasien_id=id,
        pasien__nomor_rekam_medis=OuterRef('pasien__nomor_rekam_medis')
    ).order_by('-created_at').values('id')

    # Use the subquery to filter the main queryset
    history = Pendaftaran.objects.filter(
        id__in=Subquery(subquery)
    ).values()

    # Annotate the related data
    history = history.annotate(
        nomor_rekam_medis=F('pasien__nomor_rekam_medis'),
        alamat=F('pasien__alamat'),
        nama_pasien=F('pasien__first_name'),
        nama_dokter=F('dokter__first_name'),
        polinama=F('dokter__poli__nama'),
        biaya=F('pembayaran__total_pembayaran'),
        kontak_pasien=F('pasien__kontak'),
        kontrol=F('waktu_kontrol')
    )

    return JsonResponse(list(history), safe=False)

@login_required
def laporan_detail(request):
    if request.POST.get('id'):
        id = request.POST.get('id')
    else:
        id = 1
    # Create a subquery to get the latest Pendaftaran record for each unique nomor_rekam_medis
    subquery = Pendaftaran.objects.filter(
        pasien_id=id,
        pasien__nomor_rekam_medis=OuterRef('pasien__nomor_rekam_medis')
    ).order_by('-created_at').values('id')

    # Use the subquery to filter the main queryset
    history = Pendaftaran.objects.filter(
        id__in=Subquery(subquery)
    ).values()

    # Annotate the related data
    history = history.annotate(
        nomor_rekam_medis=F('pasien__nomor_rekam_medis'),
        alamat=F('pasien__alamat'),
        nama_pasien=F('pasien__first_name'),
        nama_dokter=F('dokter__first_name'),
        polinama=F('dokter__poli__nama'),
        biaya=F('pembayaran__total_pembayaran')
    )

    return JsonResponse(list(history), safe=False)

@login_required
def laporan_pasien(request):
    all_patient = Pendaftaran.objects.filter(status='progress')
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')

    current_datetime = timezone.now()
    formatted_date = current_datetime.strftime("%Y-%m-%d")
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'all_patient': all_patient,
        'dokter': dokter,
        'formatted_date': formatted_date,
        'menu_items': menu_items,
    }
    return render(request, 'pemeriksaan/laporan/laporan_pasien.html', context)
    
@login_required
def get_laporan(request):
    user_id = request.user.id
    usergroups = request.user.groups.all().values()
    get_usergroup = list(usergroups)
    for x in get_usergroup:
        usergroup = x['name']

    data = PemeriksaanPendaftaranViews.objects.filter(status='selesai')

    if request.POST.get('dokter_id'):
        dokter_id = request.POST.get('dokter_id')
        # Append conditions
        data = data.filter(dokter_id=dokter_id)
    if request.POST.get('pasien_id'):
        pasien_id = request.POST.get('pasien_id')
        data = data.filter(pasien_id=pasien_id)
    if request.POST.get('rm_no'):
        rm_no = request.POST.get('rm_no')
        data = data.filter(nomor_rekam_medis=rm_no)
    if request.POST.get('waktu_berobat'):
        waktu_berobat = request.POST.get('waktu_berobat')
        today = date.today()
        waktu_berobat_date = datetime.strptime(today.strftime('%Y-%m-%d'), '%Y-%m-%d').date()
        if waktu_berobat == "today":
                data = data.filter(created_at__date=waktu_berobat_date)
        if waktu_berobat == "week":
                data = data.filter(created_at__week=today.isocalendar()[1])
        if waktu_berobat == "month":
                data = data.filter(created_at__month=today.month)
        if waktu_berobat == "year":
                data = data.filter(created_at__year=today.year)

    if request.POST.get('start_date') or request.POST.get('finish_date'):
        start_date = request.POST.get('start_date')
        finish_date = request.POST.get('finish_date')
        start_date_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        finish_date_date = datetime.strptime(finish_date, '%Y-%m-%d').date()

        data = data.filter(created_at__range=[start_date_date, finish_date_date])

    return JsonResponse(list(data.values()), safe=False)

@login_required
def get_pendaftaran_views(request):
    user_id = request.user.id
    usergroups = request.user.groups.all().values()
    get_usergroup = list(usergroups)
    for x in get_usergroup:
        usergroup = x['name']
    if request.user.username == "superuser":
        pendaftaran = PendaftaranViews.objects.filter(status__in=['arrived', 'progress'])
    else:
        pendaftaran = PendaftaranViews.objects.filter(status__in=['arrived', 'progress'])

    if request.GET.get('ruang_rawat_pasien'):
        ruang_rawat_pasien = request.GET.get('ruang_rawat_pasien')
        pendaftaran = pendaftaran.filter(ruang_rawat_pasien=ruang_rawat_pasien)
    
    if usergroup == "DOKTER":
        pendaftaran = pendaftaran.filter(dokter_id=user_id)

    return JsonResponse(list(pendaftaran.values()), safe=False)

@login_required
def get_farmasi(request):
    farmasi = PendaftaranViews.objects.filter(status_plan__in=['arrived', 'progress']).values()

    return JsonResponse(list(farmasi), safe=False)

@login_required
def get_history_farmasi(request):
    farmasi = PendaftaranViews.objects.filter(status_plan="selesai").values()

    return JsonResponse(list(farmasi), safe=False)

def isRupiah(amount):
    try:
        # Convert the amount to a float if it's not already
        amount = float(amount)

        # Format the amount as Indonesian Rupiah
        rupiah = "Rp {:,.2f}".format(amount)
        
        return rupiah
    except (ValueError, TypeError):
        return "Invalid Amount"

def checkUsia(date_of_birth):
    # Convert the date of birth string to a datetime object
    dob = datetime.strptime(str(date_of_birth), '%Y-%m-%d')

    # Calculate the current date
    current_date = datetime.now()

    # Calculate the difference in years
    age = current_date.year - dob.year

    # Adjust the age if the birthdate has not occurred this year yet
    if current_date.month < dob.month or (current_date.month == dob.month and current_date.day < dob.day):
        age -= 1

    return age

def stringFromArray(name, array):
    lists = [getattr(item, name, "") for item in array]
    lists = [value for value in lists if value]
    if len(lists) > 1:
        concated = ', '.join(lists)
    else:
        concated = lists[0] if lists else ""
    
    return concated

@login_required
def export_excel(request):
    # Create a new workbook and select the active sheet
    wb = Workbook()
    ws = wb.active

    # Define the title
    ws.merge_cells("A1:P1")
    title = "LAPORAN DATA PASIEN"

    # Set the title in cell A1 with bold font
    title_cell = ws.cell(row=1, column=1, value=title)
    title_cell.alignment = Alignment(horizontal='center', vertical='center')
    title_cell.font = Font(bold=True)

    # Define the subtitle
    ws.merge_cells("A2:P2")
    info_dasar_faskes = InformasiDasarFaskes.objects.first()
    subtitle = info_dasar_faskes.nama

    # Set the subtitle in cell A1 with bold font
    subtitle_cell = ws.cell(row=2, column=1, value=subtitle)
    subtitle_cell.alignment = Alignment(horizontal='center', vertical='center')
    subtitle_cell.font = Font(bold=True)

    # Define the title
    ws.merge_cells("A3:P3")
    alamat = info_dasar_faskes.alamat

    # Set the alamat in cell A1 with bold font
    alamat_cell = ws.cell(row=3, column=1, value=alamat)
    alamat_cell.alignment = Alignment(horizontal='center', vertical='center')

    # Define the email
    ws.merge_cells("A4:P4")
    email = "email: -"

    # Set the email in cell A1 with bold font
    email_cell = ws.cell(row=4, column=1, value=email)
    email_cell.alignment = Alignment(horizontal='center', vertical='center')
    email_font = Font(bold=True, color="0000FF")  # "0000FF" is the code for blue
    email_cell.font = email_font

    # Define the column headers
    column_headers = [
        "Medrec", "Nama pasien", "Pekerjaan", "Tanggal Masuk", "Jenis Kelamin", "Usia", "Berat Badan", "Tinggi Badan", "Tensi", "Status Pasien",
        "Kunjungan POLI", "Layanan",  "Alamat",
        "Dokter", "Jenis tindakan",
        "Kode ICD 10", "Diagnosa", "No Telepon" 
    ]

    # Set the column headers in the worksheet
    for col_num, column_title in enumerate(column_headers, 1):
        cell = ws.cell(row=7, column=col_num, value=column_title)
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        
        col_letter = get_column_letter(col_num)
        max_width = max(len(str(column_title)), 15)  # Minimum width of 10 characters
        ws.column_dimensions[col_letter].width = max_width

        
    # # Merge cells for "JML Pembayaran" and add sub-columns
    # ws.merge_cells("K7:N7")
    # tindakan = ws.cell(row=8, column=11, value="Tindakan")
    # tindakan.font = Font(bold=True)
    # obat = ws.cell(row=8, column=12, value="Obat")
    # obat.font = Font(bold=True)
    # diagno = ws.cell(row=8, column=13, value="Diagnosa")
    # diagno.font = Font(bold=True)
    # jml = ws.cell(row=8, column=14, value="JML")
    # jml.font = Font(bold=True)

    user_id = request.user.id
    usergroups = request.user.groups.all().values()
    get_usergroup = list(usergroups)
    for x in get_usergroup:
        usergroup = x['name']
    
    base_query = PendaftaranViews.objects.all()

    if usergroup == "DOKTER":
        base_query = base_query.filter(dokter_id=user_id)

    if request.GET.get('dokter_id') and request.GET.get('dokter_id') != 'null':
        dokter_id = request.GET.get('dokter_id')
        # Append conditions
        base_query = base_query.filter(dokter_id=dokter_id)
    if request.GET.get('pasien_id'):
        pasien_id = request.GET.get('pasien_id')
        base_query = base_query.filter(pasien_id=pasien_id)
    if request.GET.get('rm_no'):
        rm_no = request.GET.get('rm_no')
        base_query = base_query.filter(pasien__nomor_rekam_medis=rm_no)
    if request.GET.get('waktu_berobat'):
        waktu_berobat = request.GET.get('waktu_berobat')
        today = date.today()
        waktu_berobat_date = datetime.strptime(today.strftime('%Y-%m-%d'), '%Y-%m-%d').date()
        if waktu_berobat == "today":
                base_query = base_query.filter(created_at__date=waktu_berobat_date)
        if waktu_berobat == "week":
                base_query = base_query.filter(created_at__week=today.isocalendar()[1])
        if waktu_berobat == "month":
                base_query = base_query.filter(created_at__month=today.month)
        if waktu_berobat == "year":
                base_query = base_query.filter(created_at__year=today.year)

    if request.GET.get('start_date') or request.GET.get('finish_date'):
        start_date = request.GET.get('start_date')
        finish_date = request.GET.get('finish_date')
        start_date_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        finish_date_date = datetime.strptime(finish_date, '%Y-%m-%d').date()

        base_query = base_query.filter(created_at__range=[start_date_date, finish_date_date]).order_by('created_at')
        # base_query = base_query.order_by('-created_at')


    for row_data in base_query:
        getDiagnosa = InputIcd10.objects.filter(pendaftaran_id=row_data.id)
        getDiagnosa = getDiagnosa.annotate(
            diagnosa=F('icd10__diagnosa'),
            kode_diagnosa=F('icd10__kode'),
        )
        # Evaluate the queryset, for example, by converting it to a list
        diagnosa_list = list(getDiagnosa)

        diagnosa = stringFromArray('diagnosa', diagnosa_list)
        kode_diagnosa = stringFromArray('kode_diagnosa', diagnosa_list)

        invoicelayanan = InvoiceLayanan.objects.filter(pendaftaran_id=row_data.id)
        invoicelayanan = invoicelayanan.annotate(
            harga_layanan=F('tarif_layanan__harga')
        )
        # Evaluate the queryset, for example, by converting it to a list
        invoice_list = list(invoicelayanan)
        # return JsonResponse(invoice_list, safe=False)
        total_harga_layanan = 0
        for item in invoice_list:
            total = item.harga_layanan * item.kuantitas
            total_harga_layanan += total
        
        invoicebarang = InvoiceBarang.objects.filter(pendaftaran_id=row_data.id)
        invoicebarang = invoicebarang.annotate(
            harga_barang=F('barang__harga_jual')
        )

        barang_list = list(invoicebarang)
        total_harga_barang = 0
        for item in barang_list:
            total = item.harga_barang * item.kuantitas
            total_harga_barang += total

        totalPembayaran = total_harga_layanan + total_harga_barang
        if row_data.is_new_pasien == 1:
            status_pasien = "LAMA"
        else: 
            status_pasien = "BARU"
            
        if row_data.jenis_kelamin == "female":
            jenis_kelamin = "P"
        else:
            jenis_kelamin = "L"

        row = [
            row_data.nomor_rekam_medis,
            row_data.nama_pasien,
            row_data.pekerjaan,
            date(row_data.created_at.year, row_data.created_at.month, row_data.created_at.day),
            jenis_kelamin,
            checkUsia(row_data.tanggal_lahir),
            row_data.bb,
            row_data.tb,
            row_data.tensi,
            status_pasien,
            "KLINIK UMUM",
            row_data.ruang_rawat_pasien,
            row_data.alamat,
            row_data.nama_dokter,
            row_data.tindakan,
            # isRupiah(total_harga_layanan),
            # isRupiah(total_harga_barang),
            # isRupiah(totalPembayaran),
            kode_diagnosa,
            diagnosa,
            row_data.kontak
        ]
        ws.append(row)


    # Apply style to "Pasien BPJS" column with a yellow background
    yellow_fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
    cell = ws['H7']
    cell.fill = yellow_fill
    
    border = Border(left=Side(style='thin'), 
                    right=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thin'))

    for row in ws.iter_rows(min_row=7, max_row=ws.max_row, min_col=1, max_col=ws.max_column):
        for cell in row:
            cell.border = border

    # Set response headers for Excel file download
    response = HttpResponse(content_type='application/ms-excel')
    current_date = datetime.now().strftime('%d_%b_%Y')

    filename = f"laporan_pasien_{current_date}.xlsx"

    response['Content-Disposition'] = f'attachment; filename="{filename}"'

    # Save the workbook to the response
    wb.save(response)

    return response
       
@login_required
def export_excel_farmasi(request):
    # Create a new workbook and select the active sheet
    wb = Workbook()
    ws = wb.active

    # Define the title
    ws.merge_cells("A1:P1")
    title = "LAPORAN DATA PASIEN DAN PEMASUKAN KEUANGAN PER HARI"

    # Set the title in cell A1 with bold font
    title_cell = ws.cell(row=1, column=1, value=title)
    title_cell.alignment = Alignment(horizontal='center', vertical='center')
    title_cell.font = Font(bold=True)

    # Define the subtitle
    ws.merge_cells("A2:P2")
    subtitle = "KLINIK PRATAMA AL ABINA"

    # Set the subtitle in cell A1 with bold font
    subtitle_cell = ws.cell(row=2, column=1, value=subtitle)
    subtitle_cell.alignment = Alignment(horizontal='center', vertical='center')
    subtitle_cell.font = Font(bold=True)

    # Define the title
    ws.merge_cells("A3:P3")
    alamat = "Alamat: Jl. Mega Indah No 9 Sukaraja, Kec. Cicendo, Kota Bandung, Jawa Barat 40175"

    # Set the alamat in cell A1 with bold font
    alamat_cell = ws.cell(row=3, column=1, value=alamat)
    alamat_cell.alignment = Alignment(horizontal='center', vertical='center')

    # Define the email
    ws.merge_cells("A4:P4")
    email = "email: alabina@aklik.id"

    # Set the email in cell A1 with bold font
    email_cell = ws.cell(row=4, column=1, value=email)
    email_cell.alignment = Alignment(horizontal='center', vertical='center')
    email_font = Font(bold=True, color="0000FF")  # "0000FF" is the code for blue
    email_cell.font = email_font

    # Define the column headers
    column_headers = [
        "Medrec", "Nama pasien", "Usia", "Jenis Kelamin", "Status Pasien",
        "Kunjungan POLI", "Layanan",  "Alamat",
        "Dokter", "Jenis tindakan", "JML Pembayaran", "", "", "", 
        "Kode ICD 10", "No Telepon"
    ]

    # Set the column headers in the worksheet
    for col_num, column_title in enumerate(column_headers, 1):
        cell = ws.cell(row=7, column=col_num, value=column_title)
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        
        col_letter = get_column_letter(col_num)
        max_width = max(len(str(column_title)), 15)  # Minimum width of 10 characters
        ws.column_dimensions[col_letter].width = max_width

        
    # Merge cells for "JML Pembayaran" and add sub-columns
    ws.merge_cells("K7:N7")
    tindakan = ws.cell(row=8, column=11, value="Tindakan")
    tindakan.font = Font(bold=True)
    obat = ws.cell(row=8, column=12, value="Obat")
    obat.font = Font(bold=True)
    diagno = ws.cell(row=8, column=13, value="Diagnosa")
    diagno.font = Font(bold=True)
    jml = ws.cell(row=8, column=14, value="JML")
    jml.font = Font(bold=True)

    base_query = Pendaftaran.objects.all()
    
    base_query = base_query.filter(
        status='progress',
        pasien__nomor_rekam_medis=OuterRef('pasien__nomor_rekam_medis')
    )

    subquery = base_query.order_by('-created_at').values('id')[:1]

    # Use the subquery to filter the main queryset
    history = Pendaftaran.objects.filter(
        id__in=Subquery(subquery)
    ).values()

    # Annotate the related data
    history = history.annotate(
        nomor_rekam_medis=F('pasien__nomor_rekam_medis'),
        alamat=F('pasien__alamat'),
        nama_pasien=F('pasien__first_name'),
        jenis_kelamin=F('pasien__jenis_kelamin'),
        nama_dokter=F('dokter__first_name'),
        polinama=F('dokter__poli__nama'),
        tanggal_lahir=F('pasien__tanggal_lahir'),
        biaya=F('pembayaran__total_pembayaran')
    )

    # return JsonResponse(list(history), safe=False)
    history_ids = history.values_list('id', flat=True)

    for row_data in history:
        # Extract the values for each column, including the custom field
        if row_data['cara_bayar'] == "2":
            statusPasien = "BPJS"
        else:
            statusPasien = "Umum"

        getDiagnosa = InputIcd10.objects.filter(pendaftaran_id=row_data['id'])
        getDiagnosa = getDiagnosa.annotate(
            diagnosa=F('icd10__diagnosa'),
            kode_diagnosa=F('icd10__kode'),
        )
        # Evaluate the queryset, for example, by converting it to a list
        diagnosa_list = list(getDiagnosa)

        diagnosa = stringFromArray('diagnosa', diagnosa_list)
        kode_diagnosa = stringFromArray('kode_diagnosa', diagnosa_list)

        invoicelayanan = InvoiceLayanan.objects.filter(pendaftaran_id=row_data['id'])
        invoicelayanan = invoicelayanan.annotate(
            harga_layanan=F('tarif_layanan__harga')
        )
        # Evaluate the queryset, for example, by converting it to a list
        invoice_list = list(invoicelayanan)
        # return JsonResponse(invoice_list, safe=False)
        total_harga_layanan = 0
        for item in invoice_list:
            total = item.harga_layanan * item.kuantitas
            total_harga_layanan += total
        
        invoicebarang = InvoiceBarang.objects.filter(pendaftaran_id=row_data['id'])
        invoicebarang = invoicebarang.annotate(
            harga_barang=F('barang__harga_jual')
        )

        barang_list = list(invoicebarang)
        total_harga_barang = 0
        for item in barang_list:
            total = item.harga_barang * item.kuantitas
            total_harga_barang += total

        totalPembayaran = total_harga_layanan + total_harga_barang

        row = [
            row_data['nomor_rekam_medis'],
            row_data['nama_pasien'],
            checkUsia(row_data['tanggal_lahir']),
            row_data['jenis_kelamin'],
            statusPasien,
            "KLINIK " + row_data['polinama'],
            row_data['ruang_rawat_pasien'],
            row_data['alamat'],
            row_data['nama_dokter'],
            row_data['tindakan'],
            isRupiah(total_harga_layanan),
            isRupiah(total_harga_barang),
            diagnosa,
            isRupiah(totalPembayaran),
            kode_diagnosa,
            "-"
        ]
        ws.append(row)


    # Apply style to "Pasien BPJS" column with a yellow background
    yellow_fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
    cell = ws['E7']
    cell.fill = yellow_fill
    
    border = Border(left=Side(style='thin'), 
                    right=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thin'))

    for row in ws.iter_rows(min_row=7, max_row=ws.max_row, min_col=1, max_col=ws.max_column):
        for cell in row:
            cell.border = border

    # Set response headers for Excel file download
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="farmasi_progress.xlsx"'

    # Save the workbook to the response
    wb.save(response)

    return response
   
@login_required
def export_excel_history(request):
    # Create a new workbook and select the active sheet
    wb = Workbook()
    ws = wb.active

    # Define the title
    ws.merge_cells("A1:P1")
    title = "LAPORAN DATA PASIEN DAN PEMASUKAN KEUANGAN PER HARI"

    # Set the title in cell A1 with bold font
    title_cell = ws.cell(row=1, column=1, value=title)
    title_cell.alignment = Alignment(horizontal='center', vertical='center')
    title_cell.font = Font(bold=True)

    # Define the subtitle
    ws.merge_cells("A2:P2")
    subtitle = "KLINIK PRATAMA AL ABINA"

    # Set the subtitle in cell A1 with bold font
    subtitle_cell = ws.cell(row=2, column=1, value=subtitle)
    subtitle_cell.alignment = Alignment(horizontal='center', vertical='center')
    subtitle_cell.font = Font(bold=True)

    # Define the title
    ws.merge_cells("A3:P3")
    alamat = "Alamat: Jl. Mega Indah No 9 Sukaraja, Kec. Cicendo, Kota Bandung, Jawa Barat 40175"

    # Set the alamat in cell A1 with bold font
    alamat_cell = ws.cell(row=3, column=1, value=alamat)
    alamat_cell.alignment = Alignment(horizontal='center', vertical='center')

    # Define the email
    ws.merge_cells("A4:P4")
    email = "email: alabina@aklik.id"

    # Set the email in cell A1 with bold font
    email_cell = ws.cell(row=4, column=1, value=email)
    email_cell.alignment = Alignment(horizontal='center', vertical='center')
    email_font = Font(bold=True, color="0000FF")  # "0000FF" is the code for blue
    email_cell.font = email_font

    # Define the column headers
    column_headers = [
        "Medrec", "Nama pasien", "Usia", "Jenis Kelamin", "Status Pasien",
        "Kunjungan POLI", "Layanan",  "Alamat",
        "Dokter", "Jenis tindakan", "JML Pembayaran", "", "", "", 
        "Kode ICD 10", "No Telepon"
    ]

    # Set the column headers in the worksheet
    for col_num, column_title in enumerate(column_headers, 1):
        cell = ws.cell(row=7, column=col_num, value=column_title)
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        
        col_letter = get_column_letter(col_num)
        max_width = max(len(str(column_title)), 15)  # Minimum width of 10 characters
        ws.column_dimensions[col_letter].width = max_width

        
    # Merge cells for "JML Pembayaran" and add sub-columns
    ws.merge_cells("K7:N7")
    tindakan = ws.cell(row=8, column=11, value="Tindakan")
    tindakan.font = Font(bold=True)
    obat = ws.cell(row=8, column=12, value="Obat")
    obat.font = Font(bold=True)
    diagno = ws.cell(row=8, column=13, value="Diagnosa")
    diagno.font = Font(bold=True)
    jml = ws.cell(row=8, column=14, value="JML")
    jml.font = Font(bold=True)

    base_query = Pendaftaran.objects.all()
    
    base_query = base_query.filter(
        status_plan='selesai',
        pasien__nomor_rekam_medis=OuterRef('pasien__nomor_rekam_medis')
    )

    subquery = base_query.order_by('-created_at').values('id')[:1]

    # Use the subquery to filter the main queryset
    history = Pendaftaran.objects.filter(
        id__in=Subquery(subquery)
    ).values()

    # Annotate the related data
    history = history.annotate(
        nomor_rekam_medis=F('pasien__nomor_rekam_medis'),
        alamat=F('pasien__alamat'),
        nama_pasien=F('pasien__first_name'),
        jenis_kelamin=F('pasien__jenis_kelamin'),
        nama_dokter=F('dokter__first_name'),
        polinama=F('dokter__poli__nama'),
        tanggal_lahir=F('pasien__tanggal_lahir'),
        biaya=F('pembayaran__total_pembayaran')
    )

    # return JsonResponse(list(history), safe=False)
    history_ids = history.values_list('id', flat=True)

    for row_data in history:
        # Extract the values for each column, including the custom field
        if row_data['cara_bayar'] == "2":
            statusPasien = "BPJS"
        else:
            statusPasien = "Umum"

        getDiagnosa = InputIcd10.objects.filter(pendaftaran_id=row_data['id'])
        getDiagnosa = getDiagnosa.annotate(
            diagnosa=F('icd10__diagnosa'),
            kode_diagnosa=F('icd10__kode'),
        )
        # Evaluate the queryset, for example, by converting it to a list
        diagnosa_list = list(getDiagnosa)

        diagnosa = stringFromArray('diagnosa', diagnosa_list)
        kode_diagnosa = stringFromArray('kode_diagnosa', diagnosa_list)

        invoicelayanan = InvoiceLayanan.objects.filter(pendaftaran_id=row_data['id'])
        invoicelayanan = invoicelayanan.annotate(
            harga_layanan=F('tarif_layanan__harga')
        )
        # Evaluate the queryset, for example, by converting it to a list
        invoice_list = list(invoicelayanan)
        # return JsonResponse(invoice_list, safe=False)
        total_harga_layanan = 0
        for item in invoice_list:
            total = item.harga_layanan * item.kuantitas
            total_harga_layanan += total
        
        invoicebarang = InvoiceBarang.objects.filter(pendaftaran_id=row_data['id'])
        invoicebarang = invoicebarang.annotate(
            harga_barang=F('barang__harga_jual')
        )

        barang_list = list(invoicebarang)
        total_harga_barang = 0
        for item in barang_list:
            total = item.harga_barang * item.kuantitas
            total_harga_barang += total

        totalPembayaran = total_harga_layanan + total_harga_barang

        row = [
            row_data['nomor_rekam_medis'],
            row_data['nama_pasien'],
            checkUsia(row_data['tanggal_lahir']),
            row_data['jenis_kelamin'],
            statusPasien,
            "KLINIK " + row_data['polinama'],
            row_data['ruang_rawat_pasien'],
            row_data['alamat'],
            row_data['nama_dokter'],
            row_data['tindakan'],
            isRupiah(total_harga_layanan),
            isRupiah(total_harga_barang),
            diagnosa,
            isRupiah(totalPembayaran),
            kode_diagnosa,
            "-"
        ]
        ws.append(row)


    # Apply style to "Pasien BPJS" column with a yellow background
    yellow_fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
    cell = ws['E7']
    cell.fill = yellow_fill
    
    border = Border(left=Side(style='thin'), 
                    right=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thin'))

    for row in ws.iter_rows(min_row=7, max_row=ws.max_row, min_col=1, max_col=ws.max_column):
        for cell in row:
            cell.border = border

    # Set response headers for Excel file download
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="farmasi_history.xlsx"'

    # Save the workbook to the response
    wb.save(response)

    return response 

@login_required
def postkeluarpendaftaran(request, id):
    data = request.POST
    today_date = timezone.localdate()
    # Operations outside of the atomic block
    pendaftaran = Pendaftaran.objects.get(id=id)
    try:
        # Operations inside the atomic block
        with transaction.atomic():
            pendaftaran.cara_keluar = data.get('cara_keluar')
            pendaftaran.waktu_kontrol = data.get('waktu_kontrol')
            pendaftaran.catatan_dirujuk = data.get('catatan_dirujuk')
            if pendaftaran.waktu_keluar.date() == today_date:
                pendaftaran.waktu_keluar = datetime.now(timezone.utc)
            pendaftaran.status = 'selesai'
            pendaftaran.save()

        messages.info(request, 'Pasien telah pulang')
        return redirect('/pemeriksaan/daftarpasien')

    except OperationalError as e:
        # Database is locked, retry after a short delay
        time.sleep(0.1)  # Adjust the delay as needed
        retry_count -= 1


@login_required
def postsksdanskd(request, id):
    data = request.POST
    pendaftaran = Pendaftaran.objects.get(id=id)
    if data.get('waktu_kontrol'):
        pendaftaran.waktu_kontrol = data.get('waktu_kontrol')
    if data.get('waktu_sks_awal'):
        pendaftaran.waktu_sks_awal = data.get('waktu_sks_awal')
    if data.get('waktu_sks_akhir'):
        pendaftaran.waktu_sks_akhir = data.get('waktu_sks_akhir')
    pendaftaran.save()
    messages.info(request, 'Surat Pasien sudah dibuat')
    return redirect('/pemeriksaan/daftarpasien')


@login_required
def sep(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/sep.html', context)


@login_required
def sepranap(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/sep-ranap.html', context)


@login_required
def resep(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    invoicebarang = InvoiceBarang.objects.filter(pendaftaran=pendaftaran)
    invoicebaranglast = InvoiceBarang.objects.filter(pendaftaran=pendaftaran).last()
    context = {
        'pendaftaran': pendaftaran,
        'invoicebarang': invoicebarang,
        'invoicebaranglast': invoicebaranglast,
    }
    return render(request, 'pemeriksaan/isian/resep.html', context)


@login_required
def daftarfarmasi(request):
    pendaftaran = Pendaftaran.objects.filter(status_plan='progress')
    pendaftaranhistory = Pendaftaran.objects.filter(status_plan='selesai').order_by('-created_at')
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'pendaftaran': pendaftaran,
        'pendaftaranhistory': pendaftaranhistory,
        'menu_items': menu_items,
    }
    return render(request, 'pemeriksaan/farmasi/daftar_pasien.html', context)


@login_required
def farmasi(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    carabayar = CaraBayar.objects.get(id=pendaftaran.cara_bayar)
    kelas = Kelas.objects.get(id=pendaftaran.kelas)
    invoicebarang = InvoiceBarang.objects.filter(pendaftaran=pendaftaran)
    barang = Barang.objects.all()
    harga_list = HargaList.objects.all().order_by('price')
    
    try:
        get_harga = HargaListHistory.objects.filter(pendaftaran_id=id).first()

        if get_harga and hasattr(get_harga.harga_list, 'price'):
            info_paket = get_harga.harga_list.title
            harga_paket = get_harga.harga_list.price
        else:
            info_paket = ''
            harga_paket = '0'

    except ObjectDoesNotExist:
        info_paket = ''
        harga_paket = '0'

    summaryinvoicebarang = 0
    for x in invoicebarang:
        x.total_harga =  (x.barang.harga_jual * x.kuantitas)
        summaryinvoicebarang = float(summaryinvoicebarang) + float(x.total_harga)

        check_diskon = PromotionDiskonHistory.objects.filter(layanan_diskon_id=x.barang.id, jenis_diskon="barang", diskon__is_active=1, diskon__min_qty__lte=x.kuantitas).exists()
        if check_diskon:
            if x.diskon_pembelian == 0:
                get_data = PromotionDiskonHistory.objects.get(layanan_diskon_id=x.barang.id, jenis_diskon="barang", diskon__is_active=1, diskon__min_qty__lte=x.kuantitas)
                x.diskon_layanan = get_data.diskon.diskon
                x.tipe_diskon = get_data.diskon.tipe_diskon
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (float(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicebarang -= potongan
                else: 
                    x.total_harga = x.total_harga - float(x.diskon_layanan)
                    summaryinvoicebarang -= float(x.diskon_layanan)

                if pendaftaran.status != "selesai":
                    InvoiceLayanan.objects.filter(harga_jual_id=x.harga_jual.id, pendaftaran_id=x.pendaftaran.id).update(diskon_pembelian=x.diskon_layanan, tipe_diskon=x.tipe_diskon)
            else:
                x.tipe_diskon = x.tipe_diskon
                x.diskon_layanan = x.diskon_pembelian
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (float(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicebarang -= potongan
                else: 
                    x.total_harga = x.total_harga - float(x.diskon_layanan)
                    summaryinvoicebarang -= float(x.diskon_layanan)
        else:
            if x.diskon_pembelian != 0:
                if x.diskon_pembelian == None:
                    x.diskon_pembelian = 0
                x.tipe_diskon = x.tipe_diskon
                x.diskon_layanan = x.diskon_pembelian
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (float(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicebarang -= potongan
                else: 
                    x.total_harga = x.total_harga - float(x.diskon_layanan)
                    summaryinvoicebarang -= float(x.diskon_layanan)
            else:
                x.diskon_layanan = 0
                x.tipe_diskon = '%'

    # GET MENU BY GROUPS #RYDEV
    user_groups = request.user.groups.all()
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'pendaftaran': pendaftaran,
        'invoicebarang': invoicebarang,
        'summaryinvoicebarang': summaryinvoicebarang,
        'barang': barang,
        'carabayar': carabayar,
        'kelas': kelas,
        'info_paket': info_paket,
        'harga_paket': harga_paket,
        'menu_items': menu_items,
        'harga_list': harga_list,
    }
    return render(request, 'pemeriksaan/isian/farmasi.html', context)


@login_required
def selesaifarmasi(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    pendaftaran.status_plan = 'selesai'
    pendaftaran.save()
    async_to_sync(channel_layer.group_send)(
        "group_chat_aklik",
        {
            "type" : "sendMessage",
            "action": "ADMIN", # Send TO 
            "pendaftaran_id": id,
            "nama_pasien": pendaftaran.nama_penandatangan_pasien,
            "message" : "Obat ditambahkan", 
            "username" : request.user.username,
            "sender" : request.user.first_name,
        }
    )
    messages.info(request, 'Pasien {0} telah selesai diinputkan obat'.format(pendaftaran.pasien.first_name))
    return redirect('/pemeriksaan/daftarfarmasi')


@login_required
def postinvoicebarang(request):
    data = request.POST
    current_datetime = timezone.now()
    formatted_date = current_datetime.strftime("%Y%m%d")
    pendaftaran = Pendaftaran.objects.get(id=data.get('id_pendaftaran'))
    barang_dimaksud = Barang.objects.get(id=data.get('barang'))
    id_paket_custom = data.get('id_paket_custom')
    faskes_info = InformasiDasarFaskes.objects.first()
    is_paket = faskes_info.is_paket
    if is_paket == 1:
        if not HargaListHistory.objects.filter(pendaftaran_id=data.get('id_pendaftaran')).exists():
            harga_list_history = HargaListHistory(
                                            pendaftaran_id=data.get('id_pendaftaran'),
                                            harga_list=HargaList.objects.get(id=id_paket_custom)
                                            )
            harga_list_history.save()
        else:
            harga_list_history = HargaListHistory.objects.get(pendaftaran_id=data.get('id_pendaftaran'))
            harga_list_history.harga_list=HargaList.objects.get(id=id_paket_custom)
            harga_list_history.save()
        
    invoicebarang = InvoiceBarang(
        kode=formatted_date,
        pendaftaran=pendaftaran,
        barang=barang_dimaksud,
        kuantitas=data.get('kuantitas'),
        progress='progress',
        diskon_pembelian=0,
        tipe_diskon='%',
        catatan=data.get('catatan'),
        dokter=pendaftaran.dokter,
    )
    invoicebarang.save()
    pendaftaran.status_plan = 'selesai'
    pendaftaran.save()
    messages.info(request, 'Obat sudah dimasukkan')
    return redirect('/pemeriksaan/farmasi/{0}/'.format(pendaftaran.id))


@login_required
def hapusinvoicebarang(request, id):
    invoicebarang = InvoiceBarang.objects.get(id=id)
    pendaftaran = Pendaftaran.objects.get(id=request.POST.get('id_pendaftaran'))
    checkbarang = InvoiceBarang.objects.filter(pendaftaran_id=invoicebarang.pendaftaran.id)
    if len(checkbarang) == 1:
        pendaftaran.status_plan = 'progress'
        pendaftaran.save()
    invoicebarang.delete()
    messages.info(request, "Obat / Barang Pasien {0} telah dihapus".format(invoicebarang.pendaftaran.pasien.first_name))
    return redirect('/pemeriksaan/farmasi/{0}/'.format(invoicebarang.pendaftaran.id))


@login_required
def hapusinvoicelayanan(request, id):
    invoicelayanan = InvoiceLayanan.objects.get(id=id)
    invoicelayanan.delete()
    messages.info(request, "Layanan Pasien {0} telah dihapus".format(invoicelayanan.pendaftaran.pasien.first_name))
    return redirect('/pemeriksaan/pembiayaanlayanan/{0}/'.format(invoicelayanan.pendaftaran.id))

@login_required
def labelobat(request, id):
    invoicebarang = InvoiceBarang.objects.get(id=id)
    context = {
        'invoicebarang': invoicebarang,
    }
    return render(request, 'pemeriksaan/isian/labelobat.html', context)


@login_required
def pembiayaanlayanan(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    carabayar = CaraBayar.objects.get(id=pendaftaran.cara_bayar)
    kelas = Kelas.objects.get(id=pendaftaran.kelas)
    invoicelayanan = InvoiceLayanan.objects.filter(pendaftaran=pendaftaran)
    # layanan = TarifLayanan.objects.filter(cara_bayar=carabayar, kelas=kelas)
    summaryinvoicelayanan = 0
    for x in invoicelayanan:
        x.total_harga = (x.tarif_layanan.harga * x.kuantitas)
        summaryinvoicelayanan += x.total_harga
        # check diskon greater than or equal to
        check_diskon = PromotionDiskonHistory.objects.filter(layanan_diskon_id=x.tarif_layanan.id, jenis_diskon="tindakan", diskon__is_active=1, diskon__min_qty__lte=x.kuantitas).exists()
        if check_diskon:
            if x.diskon_pembelian == 0:
                get_data = PromotionDiskonHistory.objects.get(layanan_diskon_id=x.tarif_layanan.id, jenis_diskon="tindakan", diskon__is_active=1, diskon__min_qty__lte=x.kuantitas)
                x.diskon_layanan = get_data.diskon.diskon
                x.tipe_diskon = get_data.diskon.tipe_diskon
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (float(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicelayanan -= potongan
                else: 
                    x.total_harga = x.total_harga - float(x.diskon_layanan)
                    summaryinvoicelayanan -= float(x.diskon_layanan)

                if pendaftaran.status != "selesai":
                    InvoiceLayanan.objects.filter(tarif_layanan_id=x.tarif_layanan.id, pendaftaran_id=x.pendaftaran.id).update(diskon_pembelian=x.diskon_layanan, tipe_diskon=x.tipe_diskon)
            else:
                x.tipe_diskon = x.tipe_diskon
                x.diskon_layanan = x.diskon_pembelian
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (float(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicelayanan -= potongan
                else: 
                    x.total_harga = x.total_harga - float(x.diskon_layanan)
                    summaryinvoicelayanan -= float(x.diskon_layanan)
        else:
            if x.diskon_pembelian != 0:
                if x.diskon_pembelian == None or x.diskon_pembelian == '':
                    x.diskon_pembelian = 0
                x.tipe_diskon = x.tipe_diskon
                x.diskon_layanan = x.diskon_pembelian
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (float(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicelayanan -= potongan
                else: 
                    x.total_harga = x.total_harga - float(x.diskon_layanan)
                    summaryinvoicelayanan -= float(x.diskon_layanan)
            else:
                x.diskon_layanan = 0
                x.tipe_diskon = '%'

    layanan = TarifLayanan.objects.filter()
    total_layanan = summaryinvoicelayanan
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    
    context = {
        'pendaftaran': pendaftaran,
        'invoicelayanan': invoicelayanan,
        'layanan': layanan,
        'carabayar': carabayar,
        'kelas': kelas,
        'total_layanan': total_layanan,
        'menu_items': menu_items,
    }
    return render(request, 'pemeriksaan/pembiayaanlayanan/pembiayaanlayanan.html', context)


@login_required
def postinvoicelayanan(request):
    data = request.POST
    current_datetime = timezone.now()
    formatted_date = current_datetime.strftime("%Y%m%d")
    pendaftaran = Pendaftaran.objects.get(id=data.get('id_pendaftaran'))
    layanan_dimaksud = TarifLayanan.objects.get(id=data.get('layanan'))
    check_qty = data.get('kuantitas')
    if check_qty == '':
        qty = 1
    else:
        qty = check_qty
    invoicelayanan = InvoiceLayanan(
        kode=formatted_date,
        pendaftaran=pendaftaran,
        tarif_layanan=layanan_dimaksud,
        kuantitas=qty,
        progress='progress',
        diskon_pembelian=0,
        tipe_diskon='%',
        dokter=pendaftaran.dokter,
    )
    invoicelayanan.save()
    messages.info(request, 'Layanan sudah dimasukkan')
    return redirect('/pemeriksaan/pembiayaanlayanan/{0}/'.format(pendaftaran.id))


@login_required
def rekammedis(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    invoicebed = InvoiceBed.objects.filter(pendaftaran=pendaftaran)
    inputicd10 = InputIcd10.objects.filter(pendaftaran=pendaftaran)

    if request.method == 'POST':
        # Update pasien data
        data = request.POST
        def save_pendaftaran(pendaftaran, data):
            pendaftaran.pasien.first_name = data.get('first_name')
            pendaftaran.pasien.jenis_kelamin = data.get('jenis_kelamin')
            pendaftaran.pasien.alamat = data.get('alamat')
            pendaftaran.pasien.kecamatan = data.get('kecamatan')
            pendaftaran.pasien.tanggal_lahir = data.get('tanggal_lahir')
            pendaftaran.pasien.created_at = data.get('created_at')
            pendaftaran.pasien.save()  # Save pasien data
            pendaftaran.waktu_kontrol = data.get('waktu_kontrol')
            pendaftaran.save()  # Save pendaftaran data

        save_pendaftaran(pendaftaran, data)

        return JsonResponse({'msg': 'success'}, safe=False)

    context = {
        'pendaftaran': pendaftaran,
        'invoicebed': invoicebed,
        'inputicd10': inputicd10,
    }
    return render(request, 'pemeriksaan/isian/rekam-medis.html', context)


@login_required
def lembarpertama(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    pendaftaransemua = Pendaftaran.objects.filter(pasien=pendaftaran.pasien).values()
    # return JsonResponse(list(pendaftaransemua), safe=False)
    for x in pendaftaransemua:
        get_d = InputIcd10.objects.filter(pendaftaran=Pendaftaran.objects.get(id=x['id'])).values()
        get_d = get_d.annotate(
            kode_diagnosa=F('icd10__kode'),
            nama_diagnosa=F('icd10__diagnosa')
        )
        x['diagnosa_list'] = list(get_d)
        x['nama_dokter'] = Biodata.objects.get(id=Pendaftaran.objects.get(id=x['id']).dokter.id).first_name
        # return JsonResponse({'nama_dokter': x['nama_dokter']}, safe=False)
    
    context = {
        'pendaftaran': pendaftaran,
        'pendaftaransemua': pendaftaransemua,
    }
    return render(request, 'pemeriksaan/isian/lembar-pertama.html', context)
    

@login_required
def post_lembarpertama(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    pendaftaran.subjektif = request.POST.get('subjektif')
    pendaftaran.objektif = request.POST.get('objektif')
    pendaftaran.asesmen = request.POST.get('asesmen')
    pendaftaran.plan = request.POST.get('plan')
    pendaftaran.instruction = request.POST.get('instruction')
    pendaftaran.catatan = request.POST.get('catatan')
    pendaftaran.save()
    messages.info(request, 'CPPT sudah di update')
    return redirect('/pemeriksaan/lembarpertama/{0}'.format(pendaftaran.id))
    

@login_required
def post_lembarpertama_perawat(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    pendaftaran.subjektif_perawat = request.POST.get('subjektif_perawat')
    pendaftaran.objektif_perawat = request.POST.get('objektif_perawat')
    pendaftaran.asesmen_perawat = request.POST.get('asesmen_perawat')
    pendaftaran.plan_perawat = request.POST.get('plan_perawat')
    pendaftaran.instruction_perawat = request.POST.get('instruction_perawat')
    pendaftaran.catatan_perawat = request.POST.get('catatan_perawat')
    pendaftaran.save()
    messages.info(request, 'CPPT sudah di update')
    return redirect('/pemeriksaan/lembarpertama/{0}'.format(pendaftaran.id))


@login_required
def informed(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/informed.html', context)


@login_required
def consent(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/consent.html', context)


@login_required
def refusal(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/refusal.html', context)


@login_required
def asesmenperawat(request, id):
    if request.method == 'POST':
        data = request.POST
        pendaftaran = get_object_or_404(Pendaftaran, id=id)
        autoanamnesisnya = data.get('autoanamnesis')
        if autoanamnesisnya != None:
            pendaftaran.autoanamnesis = True if autoanamnesisnya == 'on' else False
        pendaftaran.alloanamensis_dengan = data.get('alloanamensis_dengan')
        pendaftaran.keluhan_utama = data.get('keluhan_utama')
        pendaftaran.riwayat_penyakit_sekarang = data.get('riwayat_penyakit_sekarang')
        pendaftaran.riwayat_penyakit_terdahulu = data.get('riwayat_penyakit_terdahulu')
        pendaftaran.riwayat_alergi = data.get('riwayat_alergi')
        pendaftaran.riwayat_kehamilan = data.get('riwayat_kehamilan')
        rokoknya = data.get('rokok')
        if rokoknya != None:
            pendaftaran.rokok = True if rokoknya == 'on' else False
        alkoholnya = data.get('alkohol')
        if alkoholnya != None:
            pendaftaran.alkohol = True if alkoholnya == 'on' else False
        obat_tidurnya = data.get('obat_tidur')
        if obat_tidurnya != None:
            pendaftaran.obat_tidur = True if obat_tidurnya == 'on' else False
        olahraganya = data.get('olahraga')
        if olahraganya != None:
            pendaftaran.olahraga = True if olahraganya == 'on' else False
        pendaftaran.tensi = data.get('tensi')
        pendaftaran.nadi = data.get('nadi')
        pendaftaran.rr = data.get('rr')
        pendaftaran.suhu = data.get('suhu')
        pendaftaran.tb = data.get('tb')
        pendaftaran.bb = data.get('bb')
        pendaftaran.tindakan_lab = data.get('tindakan_lab')
        pendaftaran.riwayat_psikososial = data.get('riwayat_psikososial')
        pendaftaran.asesmen_nyeri = data.get('asesmen_nyeri')
        pendaftaran.asesmen_nyeri_select = data.get('asesmen_nyeri_select')
        pendaftaran.asesmen_resiko_jatuh = data.get('asesmen_resiko_jatuh')
        pendaftaran.asesmen_resiko_jatuh_select = data.get('asesmen_resiko_jatuh_select')
        pendaftaran.pemberi_tanda_tangan_petugas = data.get('pemberi_tanda_tangan_petugas')
        pendaftaran.pemberi_tanda_tangan_dpjp = data.get('pemberi_tanda_tangan_dpjp')
        perawat_id = Biodata.objects.get(id=data.get('perawat_id'))
        pendaftaran.user_perawat = perawat_id
        pendaftaran.save()
        if 'analisa_masalah_keperawatan' in data:
            analisa_ids = [int(analisa_id) for analisa_id in data.getlist('analisa_masalah_keperawatan')]
            pendaftaran.analisa_masalah_keperawatan.set(analisa_ids)

        return redirect('/pemeriksaan/asesmenperawat/{0}'.format(pendaftaran.id))

    pendaftaran = Pendaftaran.objects.get(id=id)
    analisamasalahkeperawatan = AnalisaMasalahKeperawatan.objects.all()
    edukasi = Edukasi.objects.all()
    dirujuk = Dirujuk.objects.all()
    riwayatpenyakitpasien = InputIcd10.objects.filter(pendaftaran__pasien=pendaftaran.pasien)
    riwayatalergi = Pendaftaran.objects.filter(pasien=pendaftaran.pasien)
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
    asisten_dokter = JasaMedis.objects.filter(group_id=5)

    subquery = Pendaftaran.objects.filter(status='selesai', pasien_id=pendaftaran.pasien_id, pasien__nomor_rekam_medis=OuterRef('pasien__nomor_rekam_medis')).order_by('-created_at').values('id')

    history = Pendaftaran.objects.filter(id__in=Subquery(subquery)).values()
    history = history.annotate(
        nomor_rekam_medis=F('pasien__nomor_rekam_medis'),
        alamat=F('pasien__alamat'),
        nama_pasien=F('pasien__first_name'),
        nama_dokter=F('dokter__first_name'),
        polinama=F('dokter__poli__nama'),
    )
    context = {
        'history': history,
        'pendaftaran': pendaftaran,
        'analisamasalahkeperawatan': analisamasalahkeperawatan,
        'edukasi': edukasi,
        'dirujuk': dirujuk,
        'riwayatpenyakitpasien': riwayatpenyakitpasien,
        'riwayatalergi': riwayatalergi,
        'dokter': dokter,
        'asisten_dokter': asisten_dokter,
    }
    return render(request, 'pemeriksaan/isian/asesmen-perawat.html', context)

MAX_RETRIES = 3
RETRY_DELAY_SECONDS = 1

@login_required
def postasesmenperawat(request, id):
    data = request.POST
    autoanamnesisnya = data.get('autoanamnesis')
    rokoknya = data.get('rokok')
    alkoholnya = data.get('alkohol')
    obat_tidurnya = data.get('obat_tidur')
    olahraganya = data.get('olahraga')
    retries = 0
    while retries < MAX_RETRIES:
        try:
            pendaftaran = Pendaftaran.objects.select_for_update().get(id=id)
            pendaftaran.autoanamnesis = True if autoanamnesisnya == 'on' else False
            pendaftaran.alloanamensis_dengan = data.get('alloanamensis_dengan')
            pendaftaran.keluhan_utama = data.get('keluhan_utama')
            pendaftaran.riwayat_penyakit_sekarang = data.get('riwayat_penyakit_sekarang')
            pendaftaran.riwayat_penyakit_terdahulu = data.get('riwayat_penyakit_terdahulu')
            pendaftaran.riwayat_penyakit_keluarga = data.get('riwayat_penyakit_keluarga')
            pendaftaran.riwayat_alergi = data.get('riwayat_alergi')
            pendaftaran.riwayat_kehamilan = data.get('riwayat_kehamilan')
            pendaftaran.rokok = True if rokoknya == 'on' else False
            pendaftaran.alkohol = True if alkoholnya == 'on' else False
            pendaftaran.obat_tidur = True if obat_tidurnya == 'on' else False
            pendaftaran.olahraga = True if olahraganya == 'on' else False
            pendaftaran.tensi = data.get('tensi')
            pendaftaran.nadi = data.get('nadi')
            pendaftaran.rr = data.get('rr')
            pendaftaran.suhu = data.get('suhu')
            pendaftaran.tb = data.get('tb')
            pendaftaran.bb = data.get('bb')
            pendaftaran.tindakan_lab = data.get('tindakan_lab')
            pendaftaran.riwayat_psikososial = data.get('riwayat_psikososial')
            pendaftaran.asesmen_nyeri = data.get('asesmen_nyeri')
            pendaftaran.asesmen_nyeri_select = data.get('asesmen_nyeri_select')
            pendaftaran.asesmen_resiko_jatuh = data.get('asesmen_resiko_jatuh')
            pendaftaran.asesmen_resiko_jatuh_select = data.get('asesmen_resiko_jatuh_select')
            pendaftaran.pemberi_tanda_tangan_petugas = data.get('pemberi_tanda_tangan_petugas')
            pendaftaran.pemberi_tanda_tangan_dpjp = data.get('pemberi_tanda_tangan_dpjp')
            pendaftaran.save()

            if 'analisa_masalah_keperawatan' in data:
                analisa_ids = [int(analisa_id) for analisa_id in data.getlist('analisa_masalah_keperawatan')]
                pendaftaran.analisa_masalah_keperawatan.set(analisa_ids)

            current_datetime = timezone.now() + timedelta(hours=7)
            formatted_date_log = current_datetime.strftime("%d %b %Y %H:%M:%S")
            data_to_write = f'Successfully update asesmen perawat - {id}-{pendaftaran.pasien.first_name} - {pendaftaran.keluhan_utama} - {formatted_date_log}'
            with open('/home/megagrou/sapanmedika.aklik.id/pemeriksaan_logs.txt', 'a') as file:
                file.write(data_to_write + '\n')
            return JsonResponse({'code': 200, 'msg': 'Success..'}, safe=False)
        except OperationalError as e:
            if 'deadlock' in str(e).lower():
                retries += 1
                time.sleep(RETRY_DELAY_SECONDS)
            else:
                raise
        except Exception as e:
            current_datetime = timezone.now() + timedelta(hours=7)
            formatted_date_log = current_datetime.strftime("%d %b %Y %H:%M:%S")
            data_to_write = f'ERROR - {id} - {formatted_date_log} -  {e}'
            with open('/home/megagrou/sapanmedika.aklik.id/pemeriksaan_logs.txt', 'a') as file:
                file.write(data_to_write + '\n')
            return JsonResponse({'error': str(e)}, status=500)
    
    data_to_write = f'MAXIMUM RETRIES REACHED - {id}'
    with open('/home/megagrou/sapanmedika.aklik.id/pemeriksaan_logs.txt', 'a') as file:
        file.write(data_to_write + '\n')
    return JsonResponse({'error': str(data_to_write)}, status=500)

@login_required
def postasesmendokter(request, id):
    data = request.POST
    kepalanya = data.get('kepala_select')
    matanya = data.get('mata_select')
    leher_select = data.get('leher_select')
    tht_select = data.get('tht_select')
    paru_select = data.get('paru_select')
    jantung_select = data.get('jantung_select')
    abdomen_select = data.get('abdomen_select')
    ekstrimitas_select = data.get('ekstrimitas_select')
    kulit_select = data.get('kulit_select')
    lainnya_select = data.get('lainnya_select')

    retries = 0
    while retries < MAX_RETRIES:
        try:
            # Memindahkan operasi ICD10 ke dalam blok atomic
            if data.get('icdx1'):
                current_datetime = timezone.now()
                formatted_date = current_datetime.strftime("%Y%m%d")
                InputIcd10.objects.create(
                    kode=formatted_date,
                    icd10=Icd10.objects.get(id=data.get('selectedId1')),
                    pendaftaran=Pendaftaran.objects.get(id=id),
                    petugas=Biodata.objects.get(id=request.user.id),
                )
            if data.get('icdx2'):
                current_datetime = timezone.now()
                formatted_date = current_datetime.strftime("%Y%m%d")
                InputIcd10.objects.create(
                    kode=formatted_date,
                    icd10=Icd10.objects.get(id=data.get('selectedId2')),
                    pendaftaran=Pendaftaran.objects.get(id=id),
                    petugas=Biodata.objects.get(id=request.user.id),
                )
            
            if data.get('icdx3'):
                current_datetime = timezone.now()
                formatted_date = current_datetime.strftime("%Y%m%d")
                InputIcd10.objects.create(
                    kode=formatted_date,
                    icd10=Icd10.objects.get(id=data.get('selectedId3')),
                    pendaftaran=Pendaftaran.objects.get(id=id),
                    petugas=Biodata.objects.get(id=request.user.id),
                )
                
            if data.get('icdx4'):
                current_datetime = timezone.now()
                formatted_date = current_datetime.strftime("%Y%m%d")
                InputIcd10.objects.create(
                    kode=formatted_date,
                    icd10=Icd10.objects.get(id=data.get('selectedId4')),
                    pendaftaran=Pendaftaran.objects.get(id=id),
                    petugas=Biodata.objects.get(id=request.user.id),
                )
            
            if data.get('icdx5'):
                current_datetime = timezone.now()
                formatted_date = current_datetime.strftime("%Y%m%d")
                InputIcd10.objects.create(
                    kode=formatted_date,
                    icd10=Icd10.objects.get(id=data.get('selectedId5')),
                    pendaftaran=Pendaftaran.objects.get(id=id),
                    petugas=Biodata.objects.get(id=request.user.id),
                )

            pendaftaran = Pendaftaran.objects.select_for_update().get(id=id)
            pendaftaran.keluhan_utama = data.get('keluhan_utama')
            pendaftaran.catatan_asesmen_dokter = data.get('catatan_asesmen_dokter')
            pendaftaran.catatan_dirujuk = data.get('catatan_dirujuk')
            pendaftaran.keadaan_umum = data.get('keadaan_umum')
            pendaftaran.kesadaran = data.get('kesadaran')
            pendaftaran.kepala = data.get('kepala')
            pendaftaran.kepala_select = kepalanya == 'on'
            pendaftaran.mata = data.get('mata')
            pendaftaran.mata_select = matanya == 'on'
            pendaftaran.leher = data.get('leher')
            pendaftaran.leher_select = leher_select == 'on'
            pendaftaran.tht = data.get('tht')
            pendaftaran.tht_select = tht_select == 'on'
            pendaftaran.paru = data.get('paru')
            pendaftaran.paru_select = paru_select == 'on'
            pendaftaran.jantung = data.get('jantung')
            pendaftaran.jantung_select = jantung_select == 'on'
            pendaftaran.abdomen = data.get('abdomen')
            pendaftaran.abdomen_select = abdomen_select == 'on'
            pendaftaran.ekstrimitas = data.get('ekstrimitas')
            pendaftaran.ekstrimitas_select = ekstrimitas_select == 'on'
            pendaftaran.kulit = data.get('kulit')
            pendaftaran.kulit_select = kulit_select == 'on'
            pendaftaran.lainnya = data.get('lainnya')
            pendaftaran.lainnya_select = lainnya_select == 'on'
            pendaftaran.pemeriksaan_fisik_khusus = data.get('pemeriksaan_fisik_khusus')
            pendaftaran.pemeriksaan_klinis = data.get('pemeriksaan_klinis')
            pendaftaran.pemeriksaan_klinis_ekstra_oral = data.get('pemeriksaan_klinis_ekstra_oral')
            pendaftaran.pemeriksaan_klinis_intra_oral = data.get('pemeriksaan_klinis_intra_oral')
            pendaftaran.rencana_terapi_pemeriksaan_penunjang_rujukan = data.get('rencana_terapi_pemeriksaan_penunjang_rujukan')
            pendaftaran.plan = data.get('rencana_terapi_pemeriksaan_penunjang_rujukan')
            pendaftaran.status_plan = 'progress'
            pendaftaran.cara_keluar = data.get('cara_keluar')
            pendaftaran.tindakan = data.get('tindakan')
            pendaftaran.tindakan_lab = data.get('tindakan_lab')
            pendaftaran.pemberi_tanda_tangan_pasien = data.get('pemberi_tanda_tangan_pasien')
            pendaftaran.pemberi_tanda_tangan_dpjp = data.get('pemberi_tanda_tangan_dpjp')
            pendaftaran.catatan_edukasi_pasien = data.get('catatan_edukasi')
            pendaftaran.save()

            if 'dirujuk' in data:
                dirujuk_ids = [int(dirujuk_id) for dirujuk_id in data.getlist('dirujuk')]
                pendaftaran.dirujuk.set(dirujuk_ids)

            if 'edukasi' in data:
                edukasi_ids = [int(edukasi_id) for edukasi_id in data.getlist('edukasi')]
                pendaftaran.edukasi_pasien.set(edukasi_ids)

            current_datetime = timezone.now() + timedelta(hours=7)
            formatted_date_log = current_datetime.strftime("%d %b %Y %H:%M:%S")
            data_to_write = f'Successfully update asesmen dokter - {id}-{pendaftaran.pasien.first_name} - {pendaftaran.rencana_terapi_pemeriksaan_penunjang_rujukan} - {formatted_date_log}'
            with open('/home/megagrou/sapanmedika.aklik.id/pemeriksaan_logs.txt', 'a') as file:
                file.write(data_to_write + '\n')
            return JsonResponse({'code': 200, 'msg': 'Success..'}, safe=False)
        except OperationalError as e:
            if 'deadlock' in str(e).lower():
                retries += 1
                time.sleep(RETRY_DELAY_SECONDS)
            else:
                raise
        except Exception as e:
            current_datetime = timezone.now() + timedelta(hours=7)
            formatted_date_log = current_datetime.strftime("%d %b %Y %H:%M:%S")
            data_to_write = f'ERROR - {id} - {formatted_date_log} - {e}'
            with open('/home/megagrou/sapanmedika.aklik.id/pemeriksaan_logs.txt', 'a') as file:
                file.write(data_to_write + '\n')
            return JsonResponse({'error': str(e)}, status=500)
    
    data_to_write = f'MAXIMUM RETRIES REACHED - {id}'
    with open('/home/megagrou/sapanmedika.aklik.id/pemeriksaan_logs.txt', 'a') as file:
        file.write(data_to_write + '\n')
    return JsonResponse({'error': str(data_to_write)}, status=500)

@login_required
def odontogram(request, id):
    if request.method == 'POST':
        odontogram_data = json.loads(request.body)
        with transaction.atomic():
            Odontogram.objects.filter(pendaftaran_id=id).delete()
            for odontogram_entry in odontogram_data:
                print(odontogram_entry)
                t_number = odontogram_entry.get('t_number')
                odontogram = Odontogram.objects.get_or_create(
                    pendaftaran_id=id, 
                    no_gigi=t_number,
                    base=odontogram_entry.get('base', ''),
                    center=odontogram_entry.get('center', ''),
                    left=odontogram_entry.get('left', ''),
                    right=odontogram_entry.get('right', ''),
                    bottom=odontogram_entry.get('bottom', ''),
                    top=odontogram_entry.get('top', ''),
                    status=odontogram_entry.get('status', ''),
                    ext=odontogram_entry.get('ext', '')
                )
    try:
        odontograms = Odontogram.objects.filter(pendaftaran_id=id)
        
        odontogram_list = [
            {
                'id': odontogram.id, 
                'pendaftaran_id': odontogram.pendaftaran_id,
                'no_gigi': odontogram.no_gigi,
                'ext': odontogram.ext,
                'base': odontogram.base,
                'center': odontogram.center,
                'left': odontogram.left,
                'right': odontogram.right,
                'bottom': odontogram.bottom,
                'top': odontogram.top,
                'status': odontogram.status
            } 
            for odontogram in odontograms
        ]

        return JsonResponse(odontogram_list, safe=False, status=200)

    except Odontogram.DoesNotExist:
        return JsonResponse({'message': 'Odontogram not found.'}, status=404)

    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

@login_required
def get_Icd10(request):
    search_query = request.GET.get('search_query')

    if search_query:
        icd10 = Icd10.objects.filter(Q(kode__icontains=search_query) | Q(diagnosa__icontains=search_query)).values()
    else:
        icd10 = Icd10.objects.all().values()

    return JsonResponse(list(icd10), safe=False)

@login_required
def check_layanan_lab(request, id):
    check_pdf_lab = Dokumenlab.objects.filter(pendaftaran_id=id).values()

    check_form_lab_umum = PemeriksaanLabUmumHistory.objects.filter(pendaftaran_id=id).values_list('lab_id', flat=True).distinct()
    check_form_lab_triplee = PemeriksaanLabTripleEHistory.objects.filter(pendaftaran_id=id).values_list('lab_id', flat=True).distinct()
    if len(check_pdf_lab) > 0 or len(check_form_lab_umum) > 0 or len(check_form_lab_triplee) > 0:
        is_lab = True
    else:
        is_lab = False

    lab_objects = {
        'pdf': list(check_pdf_lab),
        'umum': list(check_form_lab_umum),
        'triplee': list(check_form_lab_triplee),
        'pdf_total': len(check_pdf_lab),
        'umum_total': len(check_form_lab_umum),
        'triplee_total': len(check_form_lab_triplee)
    }

    return JsonResponse({'is_lab': is_lab, 'lab_objects': lab_objects}, safe=False)

@login_required
def asesmenbidan(request, id):
    data = request.POST
    pendaftaran = Pendaftaran.objects.get(id=id)
    get_bidan = Bidan.objects.filter(pendaftaran_id=id).first()
    # return JsonResponse(list(pendaftaran), safe=False)
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')

    if data:
        if get_bidan is None:
            # CREATE DATA APABILA DATA BIDAN TIDAK ADA
            create_bidan = Bidan(
                petugas = Biodata.objects.get(username=request.user.username),
                pendaftaran = pendaftaran,
                problem = data.get('problem'),
                hpht = data.get('hpht'),
                gravida = data.get('gravida'),
                riwayat_obstetri = data.get('riwayat_obstetri'),
                penunjang = data.get('penunjang'),
                pemeriksaan = data.get('pemeriksaan'),
                tfu = data.get('tfu'),
                pd = data.get('pd'),
                ketuban = data.get('ketuban'),
                usia_kehamilan = data.get('usia_kehamilan'),
                terapi_saat_ini = data.get('terapi_saat_ini'),
                djj = data.get('djj'),
                portio = data.get('portio'),
                presentasi = data.get('presentasi'),
                his = data.get('his'),
                pembukaan = data.get('pembukaan'),
                asesmen_bidan = data.get('asesmen_bidan'),
                rekomendasi = data.get('rekomendasi'),
            )
            create_bidan.save()

            pendaftaran.tindakan_lab = data.get('tindakan_lab')
            pendaftaran.save()
        else:
            # UPDATE DATA
            bidan = Bidan.objects.get(pendaftaran_id=id)
            bidan.problem = data.get('problem')
            bidan.hpht = data.get('hpht')
            bidan.gravida = data.get('gravida')
            bidan.riwayat_obstetri = data.get('riwayat_obstetri')
            bidan.penunjang = data.get('penunjang')
            bidan.pemeriksaan = data.get('pemeriksaan')
            bidan.tfu = data.get('tfu')
            bidan.pd = data.get('pd')
            bidan.ketuban = data.get('ketuban')
            bidan.usia_kehamilan = data.get('usia_kehamilan')
            bidan.terapi_saat_ini = data.get('terapi_saat_ini')
            bidan.djj = data.get('djj')
            bidan.portio = data.get('portio')
            bidan.presentasi = data.get('presentasi')
            bidan.his = data.get('his')
            bidan.pembukaan = data.get('pembukaan')
            bidan.asesmen_bidan = data.get('asesmen_bidan')
            bidan.rekomendasi = data.get('rekomendasi')
            bidan.save()
            pendaftaran.tindakan_lab = data.get('tindakan_lab')
            pendaftaran.save()

        return redirect('/pemeriksaan/asesmenbidan/{0}'.format(pendaftaran.id))

    if get_bidan is not None:
        bidan = Bidan.objects.get(pendaftaran_id=id)
    else:
        bidan = {}
    context = {
        'bidan': bidan,
        'pendaftaran': pendaftaran,
        'dokter': dokter,
    }
    return render(request, 'pemeriksaan/isian/asesmen-bidan.html', context)

@login_required
def asesmendokter(request, id):
    data = request.POST
    pendaftaran = Pendaftaran.objects.get(id=id)
    poli = pendaftaran.dokter.poli.nama
    analisamasalahkeperawatan = AnalisaMasalahKeperawatan.objects.all()
    edukasi = Edukasi.objects.all()
    dirujuk = Dirujuk.objects.all()
    # icd10 = Icd10.objects.all()
    daftaricd10 = InputIcd10.objects.filter(pendaftaran=pendaftaran)
    riwayatpenyakitpasien = InputIcd10.objects.filter(pendaftaran__pasien=pendaftaran.pasien)
    riwayatalergi = Pendaftaran.objects.filter(pasien=pendaftaran.pasien)
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
    if data:
        if data.get('icdx1'):
            current_datetime = timezone.now()
            formatted_date = current_datetime.strftime("%Y%m%d")
            inputicd10 = InputIcd10(
                kode=formatted_date,
                icd10=Icd10.objects.get(id=data.get('selectedId1')),
                pendaftaran=pendaftaran,
                petugas=Biodata.objects.get(id=request.user.id),
            )
            inputicd10.save()
        if data.get('icdx2'):
            current_datetime = timezone.now()
            formatted_date = current_datetime.strftime("%Y%m%d")
            inputicd10 = InputIcd10(
                kode=formatted_date,
                icd10=Icd10.objects.get(id=data.get('selectedId2')),
                pendaftaran=pendaftaran,
                petugas=Biodata.objects.get(id=request.user.id),
            )
            inputicd10.save()
        pendaftaran.keluhan_utama = data.get('keluhan_utama')
        pendaftaran.riwayat_penyakit_sekarang = data.get('riwayat_penyakit_sekarang')
        pendaftaran.riwayat_penyakit_terdahulu = data.get('riwayat_penyakit_terdahulu')
        pendaftaran.riwayat_penyakit_keluarga = data.get('riwayat_penyakit_keluarga')
        pendaftaran.riwayat_alergi = data.get('riwayat_alergi')
        pendaftaran.catatan_asesmen_dokter = data.get('catatan_asesmen_dokter')
        pendaftaran.catatan_dirujuk = data.get('catatan_dirujuk')
        pendaftaran.keadaan_umum = data.get('keadaan_umum')
        pendaftaran.kesadaran = data.get('kesadaran')
        pendaftaran.kepala = data.get('kepala')
        kepalanya = data.get('kepala_select')
        pendaftaran.kepala_select = True if kepalanya == 'on' else False
        pendaftaran.mata = data.get('mata')
        matanya = data.get('mata_select')
        pendaftaran.mata_select = True if matanya == 'on' else False
        pendaftaran.leher = data.get('leher')
        leher_select = data.get('leher_select')
        pendaftaran.leher_select = True if leher_select == 'on' else False
        pendaftaran.tht = data.get('tht')
        tht_select = data.get('tht_select')
        pendaftaran.tht_select = True if tht_select == 'on' else False
        pendaftaran.paru = data.get('paru')
        paru_select = data.get('paru_select')
        pendaftaran.paru_select = True if paru_select == 'on' else False
        pendaftaran.jantung = data.get('jantung')
        jantung_select = data.get('jantung_select')
        pendaftaran.jantung_select = True if jantung_select == 'on' else False
        pendaftaran.abdomen = data.get('abdomen')
        abdomen_select = data.get('abdomen_select')
        pendaftaran.abdomen_select = True if abdomen_select == 'on' else False
        pendaftaran.ekstrimitas = data.get('ekstrimitas')
        ekstrimitas_select = data.get('ekstrimitas_select')
        pendaftaran.ekstrimitas_select = True if ekstrimitas_select == 'on' else False
        pendaftaran.kulit = data.get('kulit')
        kulit_select = data.get('kulit_select')
        pendaftaran.kulit_select = True if kulit_select == 'on' else False
        pendaftaran.lainnya = data.get('lainnya')
        lainnya_select = data.get('lainnya_select')
        pendaftaran.lainnya_select = True if lainnya_select == 'on' else False
        pendaftaran.pemeriksaan_fisik_khusus = data.get('pemeriksaan_fisik_khusus')
        pendaftaran.pemeriksaan_klinis = data.get('pemeriksaan_klinis')
        pendaftaran.pemeriksaan_klinis_ekstra_oral = data.get('pemeriksaan_klinis_ekstra_oral')
        pendaftaran.pemeriksaan_klinis_intra_oral = data.get('pemeriksaan_klinis_intra_oral')
        pendaftaran.rencana_terapi_pemeriksaan_penunjang_rujukan = data.get(
            'rencana_terapi_pemeriksaan_penunjang_rujukan')
        pendaftaran.plan = data.get('rencana_terapi_pemerisaan_penunjang_rujukan')
        
        if request.user.username == "superuser":
            pendaftaran.status_plan = 'selesai'
        else:
            pendaftaran.status_plan = 'progress'
            
        # pendaftaran.status = 'selesai'
        pendaftaran.cara_keluar = data.get('cara_keluar')
        pendaftaran.tindakan = data.get('tindakan')
        pendaftaran.tindakan_lab = data.get('tindakan_lab')
        # pendaftaran.dirujuk.set(data.get('dirujuk')) # many to many
        # pendaftaran.edukasi_pasien.set(data.get('edukasi_pasien'))  # many to many
        pendaftaran.pemberi_tanda_tangan_pasien = data.get('pemberi_tanda_tangan_pasien')
        pendaftaran.pemberi_tanda_tangan_dpjp = data.get('pemberi_tanda_tangan_dpjp')
        pendaftaran.save()
        print(request.POST.getlist('dirujuk'))
        if data.getlist('dirujuk'):
            analisa_ids = [int(id) for id in data.getlist('dirujuk')]
            pendaftaran.dirujuk.set(analisa_ids)
            pendaftaran.save()
        print(request.POST.getlist('edukasi'))
        if data.getlist('edukasi'):
            analisa_ids = [int(id) for id in data.getlist('edukasi')]
            pendaftaran.edukasi_pasien.set(analisa_ids)
            pendaftaran.save()
        if data.get('catatan_edukasi'):
            pendaftaran.catatan_edukasi_pasien = data.get('catatan_edukasi')
            pendaftaran.save()
        # SEND NOTIF
        async_to_sync(channel_layer.group_send)(
            "group_chat_aklik",
            {
                "type" : "sendMessage",
                "action": "ALL",  # Send TO
                "pendaftaran_id": id,
                "nama_pasien": pendaftaran.nama_penandatangan_pasien,
                "message" : "Pasien diperiksa", 
                "username" : request.user.username,
                "sender" : request.user.first_name,
            }
        )
        return redirect('/pemeriksaan/asesmendokter/{0}'.format(pendaftaran.id))
    subquery = Pendaftaran.objects.filter(status='selesai', pasien_id=pendaftaran.pasien_id, pasien__nomor_rekam_medis=OuterRef('pasien__nomor_rekam_medis')).order_by('-created_at').values('id')

    history = Pendaftaran.objects.filter(id__in=Subquery(subquery)).values()
    history = history.annotate(
        nomor_rekam_medis=F('pasien__nomor_rekam_medis'),
        alamat=F('pasien__alamat'),
        nama_pasien=F('pasien__first_name'),
        nama_dokter=F('dokter__first_name'),
        polinama=F('dokter__poli__nama'),
    )

    context = {
        'history': history,
        'pendaftaran': pendaftaran,
        'analisamasalahkeperawatan': analisamasalahkeperawatan,
        'edukasi': edukasi,
        'dirujuk': dirujuk,
        'riwayatpenyakitpasien': riwayatpenyakitpasien,
        'riwayatalergi': riwayatalergi,
        'icd10': [],
        'daftaricd10': daftaricd10,
        'dokter': dokter,
    }
    if poli == "GIGI":
        return render(request, 'pemeriksaan/isian/asesmen-dokter-gigi.html', context)
    else: 
        return render(request, 'pemeriksaan/isian/asesmen-dokter.html', context)
        
@login_required
def check_asesmenperawat(request):
    pendaftaran_id = request.GET.get('pendaftaran_id')
    # return JsonResponse(pendaftaran_id, safe=False)
    cek_keluhan = Pendaftaran.objects.get(id=pendaftaran_id)
    if cek_keluhan.keluhan_utama == '' or cek_keluhan.keluhan_utama is None :
        return JsonResponse({'status_code' : 402 , 'msg' : 'Asesmen perawat sedang di isi!'}, safe=False )
    else:
        return JsonResponse({'status_code' : 200 , 'msg' : 'Asesmen perawat sudah di isi!'}, safe=False )

@login_required
def post_terapi_obat(request, id):
    data = request.POST
    if data.get('rencana_terapi_pemeriksaan_penunjang_rujukan'):
        Pendaftaran.objects.filter(id=id).update(rencana_terapi_pemeriksaan_penunjang_rujukan=data.get('rencana_terapi_pemeriksaan_penunjang_rujukan'))
    if data.get('tindakan'):
        Pendaftaran.objects.filter(id=id).update(tindakan=data.get('tindakan'))
    return JsonResponse("Ok", safe=False)

@login_required
def asuhangizi(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/asuhan-gizi.html', context)


@login_required
def perencanaanpulang(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/perencanaan-pulang.html', context)


@login_required
def suratpersetujuanrujukan(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/surat-persetujuan-rujukan.html', context)


@login_required
def hapuspendaftaran(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    if InvoiceBarang.objects.filter(pendaftaran_id=id).exists():
        InvoiceBarang.objects.filter(pendaftaran_id=id).delete()
    if InvoiceLayanan.objects.filter(pendaftaran_id=id).exists():
        InvoiceLayanan.objects.filter(pendaftaran_id=id).delete()
    if InvoiceLab.objects.filter(pendaftaran_id=id).exists():
        InvoiceLab.objects.filter(pendaftaran_id=id).delete()
    if Pembayaran.objects.filter(pendaftaran_id=id).exists():
        Pembayaran.objects.filter(pendaftaran_id=id).delete()
    pendaftaran.delete()
    messages.info(request, "Pendaftaran Pasien {0} telah dihapus".format(pendaftaran.pasien.first_name))
    return redirect('/pemeriksaan/daftarpasien')


@login_required
def suratperintahrawatinap(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/surat-perintah-rawat-inap.html', context)


@login_required
def suratrujukanbpjs(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/surat-rujukan-bpjs.html', context)


@login_required
def asesmennyeri(request):
    # pendaftaran = Pendaftaran.objects.get(id=id)
    # context = {
    #     'pendaftaran': pendaftaran,
    # }
    # return render(request, 'pemeriksaan/isian/surat-perintah-rawat-inap.html', context)
    return render(request, 'pemeriksaan/cppt/asesmen-nyeri.html')


def display(request):
    return render(request, 'pemeriksaan/display/display.html')


@login_required
def suratkontroldokter(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/surat-kontrol-dokter.html', context)


@login_required
def suratketerangansakit(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    getDiagnosa = InputIcd10.objects.filter(pendaftaran_id=id).first()
    if getDiagnosa:
        diagnosa_primer = getDiagnosa.icd10.diagnosa
    else:
        diagnosa_primer = "-"

    context = {
        'pendaftaran': pendaftaran,
        'diagnosa_primer': diagnosa_primer
    }
    return render(request, 'pemeriksaan/isian/surat-keterangan-sakit.html', context)
    
@login_required
def suratrujukan(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/surat-rujukan.html', context)

@login_required
def suratketerangansehat(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/surat-keterangan-sehat.html', context) 

@login_required
def kwitansi(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    context = {
        'pendaftaran': pendaftaran,
    }
    return render(request, 'pemeriksaan/isian/surat-kwitansi.html', context)
    

@login_required
def deleteicd10(request, id):
    inputicd10 = InputIcd10.objects.get(id=id)
    inputicd10.delete()
    messages.info(request, 'ICD10 Sudah di hapus')
    return redirect('/pemeriksaan/asesmendokter/{0}'.format(inputicd10.pendaftaran.id))

# inventory
@login_required
def inventory(request):
    checker = Checkeropname.objects.all()
    user_groups = request.user.groups.all()
    semuapendaftaran = Pendaftaran.objects.filter(status='progress')
    barang = Barang.objects.all()
    totalStok= barang.count()
    totalProses= semuapendaftaran.count() 

    jumlahSetiapObat =barang.aggregate(Sum('stok'))
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()

    # petugas=Biodata.objects.get(username=request.user.username)
    pengecekan_terakhir= Checkeropname.objects.last()
    
    list_paket = HargaList.objects.all().order_by('created_at')

    context = {
        'barang': barang,
        'totalStok' :totalStok,
        'jumlahSetiapObat' :jumlahSetiapObat,
        'totalProses': totalProses,
        'menu_items': menu_items,
        'pengecekan_terakhir':pengecekan_terakhir,
        'checker': checker,
        'list_paket': list_paket,
    }
    return render(request, 'pemeriksaan/inventory/base.html', context)

def update_expired(request):
    Barang.objects.all().update(expired_at='2024-12-30')

@login_required
def edit_stok(request, id):
    barang = Barang.objects.get(id=id)
    nama = request.POST.get('nama_baru')
    stok = request.POST.get('stok_baru')
    harga = request.POST.get('harga_baru')
    expired_date = request.POST.get('expired_date_baru')
    barang.nama = nama
    barang.stok = float(stok)
    barang.harga_jual = float(harga)
    barang.expired_at = expired_date
    barang.save()

    if stok != "" and harga != "":
        return JsonResponse({'message':"ok"})
    else:
        return JsonResponse({'message': 'Data anda Kosong'})

@login_required
@csrf_exempt
def hapus_obat(request, id):
    if request.method == 'POST':
        obat = Barang.objects.get(id=id)
        nama_obat = obat.nama
        obat.delete()
        return JsonResponse({'message': f'Obat "{nama_obat}" telah dihapus'})
    return JsonResponse({'message': 'Invalid request method'}, status=400)

@login_required
def tambah_obat(request):
    data = request.POST
    barang = Barang.objects.all()
    kode = data.get('kode')
    nama = data.get('nama')
    harga_jual = data.get('harga_jual')
    stok = data.get('stok')
    barang.stok = float(stok)
    barang.harga_jual = float(harga_jual)
    barang.nama = nama
    barang.kode = kode

    tambahObat = Barang(
        kode=kode,
        nama=nama,
        harga_jual=harga_jual,
        stok=stok,
    )
    tambahObat.save()

    return redirect('/pemeriksaan/inventory/')

@login_required
def formopname(request):
    barang = Barang.objects.all()

    context = {
        'barang': barang,
    }
    return render(request, 'pemeriksaan/inventory/form-opname.html', context)


@login_required
def checkingopname(request):
    opname = Opname.objects.all()
    barang = Barang.objects.all()
    pengecekan_terakhir = Checkeropname.objects.last()
    data = request.POST
    for ba in barang:
        nama            = data.get('nama'+ ba.kode)
        real_stok       = data.get('real_stok'+ ba.kode)
        note            = data.get('note'+ ba.kode)
        kesesuaian      = data.get('kesesuaian'+ ba.kode)
        stok_sistem     = data.get('stok_sistem'+ ba.kode)
        checker_id      = data.get('checker_id')
        insertOpname    = Opname(
            nama = nama,
            real_stok = real_stok,
            status = 0,
            note = note,
            kesesuaian = kesesuaian,
            stok_sistem = stok_sistem,
            checker_id = checker_id,
        )
        insertOpname.save()

        pengecekan_terakhir.end_date = timezone.now()
        pengecekan_terakhir.save()
    return redirect('/pemeriksaan/inventory/')

@login_required
def checkerop(request):
    data = request.POST
    created_at = data.get('created_at')
    end_date = data.get('end_date')
    created_by = data.get('created_by')
    deskripsi = data.get('deskripsi')
    # status == autofild
    insert = Checkeropname(
        created_at = created_at,
        created_by = created_by,
        deskripsi = deskripsi
    )
    insert.save()

    return redirect('/pemeriksaan/inventory/')

@login_required
def namapasien(request):
    norm = request.GET.get('no_rm')
    datanik = request.GET.get('nik')
    pasien_by_norm = Biodata.objects.filter(nomor_rekam_medis__exact=norm)
    # print(pasien_by_norm[0].nama_penandatangan_pasien)
    if pasien_by_norm.exists():
        nama = pasien_by_norm[0].first_name
        norme = pasien_by_norm[0].nomor_rekam_medis
        return JsonResponse({'status': 400, 'nama': nama, 'nomor': norme, 'msg': f'Nomor Rekam Medis ini sudah terdaftar sebelumnya dengan nama {nama}'}, safe=False)  # Respon kembali ke JavaScript
        
    pasien_by_nik = Biodata.objects.filter(nomor_induk_kependudukan__exact=datanik)
    # print(pasien_by_nik[0].nama_penandatangan_pasien)
    if pasien_by_nik.exists():
        nama = pasien_by_nik[0].first_name
        nonik = pasien_by_nik[0].nomor_induk_kependudukan
        return JsonResponse({'status': 400, 'nama': nama, 'nomor': nonik, 'msg': f'Data NIK ini sudah terdaftar sebelumnya dengan nama {nama}'}, safe=False)  # Respon kembali ke JavaScript

    return JsonResponse({'status': 200}, safe=False)

@login_required
def detail_opname(request, id):
    opname = Opname.objects.filter(checker_id=id)
    if opname.exists():
        for o in opname:
            status = o.status
    else: 
        status = 0

    context = {
        "opname": opname,
        "id" : id,
        "status" : status
    }
        
    return render(request, 'pemeriksaan/inventory/detail-opname.html', context)

@login_required
def sinkronisasi(request):
    id = request.POST.get('id') 
    opnames = Opname.objects.filter(checker_id=id)
    for opname in opnames:
        barang = Barang.objects.filter(nama=opname.nama).first()
        barang_byId = Barang.objects.get(id=barang.id)
        barang_byId.stok = opname.real_stok
        barang_byId.save()

        # update status
        status = Opname.objects.get(id=opname.id)
        status.status = 1
        status.save()

    return redirect('/pemeriksaan/inventory/')

# LABORATORIUM
@login_required
def daftarlab(request):
    pendaftaran = Pendaftaran.objects.filter(status='progress')
    pendaftaranhistory = Pendaftaran.objects.filter(status='selesai').order_by('-created_at')
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'pendaftaran': pendaftaran,
        'pendaftaranhistory': pendaftaranhistory,
        'menu_items': menu_items,
    }
    return render(request, 'pemeriksaan/laboratorium/daftar_pasien.html', context)

@login_required
def get_lab(request):
    base_query = PendaftaranViews.objects.filter(status__in=['arrived', 'progress']).values()
    base_query = base_query.exclude(Q(tindakan_lab__isnull=True) | Q(tindakan_lab=''))

    return JsonResponse(list(base_query), safe=False)

@login_required
def get_history_lab(request):
    base_query = PendaftaranViews.objects.filter(status='selesai').values()
    base_query = base_query.exclude(Q(tindakan_lab__isnull=True) | Q(tindakan_lab=''))

    return JsonResponse(list(base_query), safe=False)

@login_required
def laboratorium(request, id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    carabayar = CaraBayar.objects.get(id=pendaftaran.cara_bayar)
    kelas = Kelas.objects.get(id=pendaftaran.kelas)
    lab = TarifLab.objects.all().values()
    # return JsonResponse(list(lab), safe=False)
    invoicelab = InvoiceLab.objects.filter(pendaftaran=pendaftaran)
    # layanan = TarifLayanan.objects.filter(cara_bayar=carabayar, kelas=kelas)
    summaryinvoicelab = 0
    for x in invoicelab:
        document_exists = Dokumenlab.objects.filter(lab_id=x.tarif_lab_id, pendaftaran_id=x.pendaftaran_id).exists()
        
        x.total_harga = (x.tarif_lab.harga * x.kuantitas)
        summaryinvoicelab += x.total_harga
        # check diskon greater than or equal to
        check_diskon = PromotionDiskonHistory.objects.filter(layanan_diskon_id=x.tarif_lab.id, jenis_diskon="tindakan_lab", diskon__is_active=1, diskon__min_qty__lte=x.kuantitas).exists()
        if check_diskon:
            if x.diskon_pembelian == 0:
                get_data = PromotionDiskonHistory.objects.get(layanan_diskon_id=x.tarif_lab.id, jenis_diskon="tindakan_lab", diskon__is_active=1, diskon__min_qty__lte=x.kuantitas)
                x.diskon_layanan = get_data.diskon.diskon
                x.tipe_diskon = get_data.diskon.tipe_diskon
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (int(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicelab -= potongan
                else: 
                    x.total_harga = x.total_harga - int(x.diskon_layanan)
                    summaryinvoicelab -= int(x.diskon_layanan)

                if pendaftaran.status != "selesai":
                    InvoiceLab.objects.filter(tarif_lab_id=x.tarif_lab.id, pendaftaran_id=x.pendaftaran.id).update(diskon_pembelian=x.diskon_layanan, tipe_diskon=x.tipe_diskon)
            else:
                x.tipe_diskon = x.tipe_diskon
                x.diskon_layanan = x.diskon_pembelian
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (int(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicelab -= potongan
                else: 
                    x.total_harga = x.total_harga - int(x.diskon_layanan)
                    summaryinvoicelab -= int(x.diskon_layanan)
        else:
            if x.diskon_pembelian != 0:
                if x.diskon_pembelian == None:
                    x.diskon_pembelian = 0
                x.tipe_diskon = x.tipe_diskon
                x.diskon_layanan = x.diskon_pembelian
                if x.tipe_diskon == '%':
                    potongan = x.total_harga * (int(x.diskon_layanan) / 100)
                    x.total_harga = x.total_harga - potongan
                    summaryinvoicelab -= potongan
                else: 
                    x.total_harga = x.total_harga - int(x.diskon_layanan)
                    summaryinvoicelab -= int(x.diskon_layanan)
            else:
                x.diskon_layanan = 0
                x.tipe_diskon = '%'
        
        if document_exists:
            get_doc = Dokumenlab.objects.get(lab_id=x.tarif_lab_id, pendaftaran_id=x.pendaftaran_id)
            x.doc = get_doc.doc
        else:
            x.doc = None

    total_layanan = summaryinvoicelab
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    
    context = {
        'pendaftaran': pendaftaran,
        'invoicelab': invoicelab,
        'summaryinvoicelab': summaryinvoicelab,
        'carabayar': carabayar,
        'kelas': kelas,
        'total_layanan': total_layanan,
        'menu_items': menu_items,
        'lab': lab,
    }
    return render(request, 'pemeriksaan/isian/laboratorium.html', context)

@login_required
def postinvoicelab(request):
    data = request.POST
    current_datetime = timezone.now()
    formatted_date = current_datetime.strftime("%Y%m%d")
    pendaftaran = Pendaftaran.objects.get(id=data.get('id_pendaftaran'))
    lab_dimaksud = TarifLab.objects.get(id=data.get('lab'))
    check_qty = data.get('kuantitas')
    if check_qty == '':
        qty = 1
    else:
        qty = check_qty

    # JANG NGEPOST DATA INI AJA BROOO #
    invoicelab = InvoiceLab(
        kode=formatted_date,
        pendaftaran=pendaftaran,
        tarif_lab=lab_dimaksud,
        kuantitas=qty,
        progress='progress',
        diskon_pembelian=0,
        tipe_diskon='%',
        dokter=pendaftaran.dokter,
    )
    invoicelab.save()
    # invoicelab.save()
    messages.info(request, 'Layanan sudah dimasukkan')
    return redirect('/pemeriksaan/laboratorium/{0}'.format(pendaftaran.id))

@login_required
def hapusinvoicelab(request, id):
    invoicelab = InvoiceLab.objects.get(id=id)
    invoicelab.delete()
    messages.info(request, "Layanan Pasien {0} telah dihapus".format(invoicelab.pendaftaran.pasien.first_name))
    return redirect('/pemeriksaan/laboratorium/{0}/'.format(invoicelab.pendaftaran.id))

def convert_image_to_pdf(image_path, output_path):
    """Converts an image file to a PDF."""
    c = canvas.Canvas(output_path, pagesize=letter)
    c.drawImage(image_path, 0, 0, width=letter[0], height=letter[1])
    c.showPage()
    c.save()

@login_required
def dokumen_lab(request):
    if request.method == 'POST':
        nama_lab = request.POST.get('nama_lab')
        nama_pasien = request.POST.get('nama_pasien')
        tanggal_pemeriksaan = request.POST.get('tanggal_pemeriksaan')
        pendaftaran_id = request.POST.get('pendaftaran_id')
        lab_id = request.POST.get('lab_id')
        doc_file = request.FILES.get('doc', None)
        current_date = datetime.now().strftime('%d_%b_%Y')

        file_name = f"lab_{pendaftaran_id}_{lab_id}_{current_date}.pdf"

        if 'doc' in request.FILES:
            doc = request.FILES['doc']
            file_path = os.path.join(settings.MEDIA_ROOT, 'filelab', file_name)

            pdf_path = os.path.join(settings.MEDIA_ROOT, 'filelab', f"{file_name}")
            with open(file_path, 'wb+') as destination:
                for chunk in doc.chunks():
                    destination.write(chunk)

            convert_image_to_pdf(file_path, pdf_path)
        
        today = timezone.now()
        formatted_date = today.strftime("%Y%m%d")

        document_exists = Dokumenlab.objects.filter(lab_id=lab_id, pendaftaran_id=pendaftaran_id).first()
        
        if document_exists:
            docInsert = Dokumenlab.objects.get(lab_id=lab_id, pendaftaran_id=pendaftaran_id)
            docInsert.nama_lab = nama_lab
            docInsert.nama_pasien = ''
            docInsert.tanggal_pemeriksaan = tanggal_pemeriksaan
            docInsert.pendaftaran_id = pendaftaran_id
            docInsert.lab_id = lab_id
            docInsert.doc = file_name
            docInsert.created_at = formatted_date
            docInsert.save()
        else:
            doclab = Dokumenlab(
                nama_lab=nama_lab,
                nama_pasien='',
                tanggal_pemeriksaan=tanggal_pemeriksaan,
                pendaftaran_id=pendaftaran_id,
                lab_id=lab_id,
                doc=file_name,
                created_at=formatted_date,
            )
            doclab.save()
        
        # Redirect ke halaman yang sesuai setelah penyimpanan berhasil
        return redirect(f'laboratorium/{pendaftaran_id}')
        
    # Redirect ke halaman isian jika metode permintaan bukan POST
    return redirect('isian/laboratorium.html')

@login_required
def dokumen_lab_umum(request, id, lab_id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    pemeriksaan_lab = PemeriksaanLabUmum.objects.filter(is_active=1)

    for lab_instance in pemeriksaan_lab:
        related_lab_history = PemeriksaanLabUmumHistory.objects.filter(pemeriksaan_lab=lab_instance, lab_id=lab_id, pendaftaran_id=pendaftaran.id)
        
        lab_instance.hasil = related_lab_history.values_list('hasil', flat=True).first()
        lab_instance.note = related_lab_history.values_list('note', flat=True).first()

    context = {
        'lab_id': lab_id,
        'pendaftaran': pendaftaran,
        'pemeriksaan_lab': pemeriksaan_lab,
    }
    return render(request, 'pemeriksaan/isian/laboratorium-umum.html', context)

@login_required
def dokumen_lab_umum_history(request, id, lab_id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    pemeriksaan_lab = PemeriksaanLabUmum.objects.filter(is_active=1)

    for lab_instance in pemeriksaan_lab:
        related_lab_history = PemeriksaanLabUmumHistory.objects.filter(pemeriksaan_lab=lab_instance, lab_id=lab_id, pendaftaran_id=pendaftaran.id)
        
        lab_instance.hasil = related_lab_history.values_list('hasil', flat=True).first()
        lab_instance.note = related_lab_history.values_list('note', flat=True).first()

    tarif_lab = TarifLab.objects.get(id=lab_id)

    context = {
        'tariflab': tarif_lab,
        'pendaftaran': pendaftaran,
        'pemeriksaan_lab': pemeriksaan_lab,
    }
    return render(request, 'pemeriksaan/isian/laboratorium-umum-history.html', context)

@login_required
def post_lab_umum(request, id):
    data = request.POST
    lab_id = data.get('lab_id')
    pendaftaran_id = data.get('pendaftaran_id')
    pemeriksaan_lab_id = data.get('pemeriksaan_id')
    hasil_lab = data.get('hasil_lab')

    today = timezone.now()
    formatted_date = today.strftime("%Y-%m-%d %H:%M:%S")
    checkLab = PemeriksaanLabUmumHistory.objects.filter(pemeriksaan_lab_id=pemeriksaan_lab_id, pendaftaran_id=pendaftaran_id, lab_id=lab_id).first()
    if checkLab is not None:
        updateLab = PemeriksaanLabUmumHistory.objects.get(pemeriksaan_lab_id=pemeriksaan_lab_id, pendaftaran_id=pendaftaran_id, lab_id=lab_id)
        updateLab.hasil = hasil_lab
        updateLab.save()
    else:
        input_lab = PemeriksaanLabUmumHistory(
            pemeriksaan_lab_id=pemeriksaan_lab_id,
            pendaftaran_id=pendaftaran_id,
            lab_id=lab_id,
            hasil=hasil_lab,
            note='',
            created_at=formatted_date,
            updated_at=formatted_date
        )
        input_lab.save()

    json = {
        'lab_id' : lab_id,
        'pendaftaran_id' : pendaftaran_id,
        'pemeriksaan_id' : pemeriksaan_lab_id,
        'hasil_lab' : hasil_lab
    }
    return JsonResponse(json, safe=False)


@login_required
def dokumen_lab_triple_e(request, id, lab_id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    pemeriksaan_lab_triplee = PemeriksaanLabTripleE.objects.filter(is_active=1)

    for lab_instance in pemeriksaan_lab_triplee:
        related_lab_history = PemeriksaanLabTripleEHistory.objects.filter(pemeriksaan_lab=lab_instance, lab_id=lab_id, pendaftaran_id=pendaftaran.id)
        
        lab_instance.hasil = related_lab_history.values_list('hasil', flat=True).first()
        lab_instance.note = related_lab_history.values_list('note', flat=True).first()

    context = {
        'lab_id': lab_id,
        'pendaftaran': pendaftaran,
        'pemeriksaan_lab_triplee': pemeriksaan_lab_triplee,
    }
    return render(request, 'pemeriksaan/isian/laboratorium-triplee.html', context)

@login_required
def dokumen_lab_triple_e_history(request, id, lab_id):
    pendaftaran = Pendaftaran.objects.get(id=id)
    pemeriksaan_lab_triplee = PemeriksaanLabTripleE.objects.filter(is_active=1)

    for lab_instance in pemeriksaan_lab_triplee:
        related_lab_history = PemeriksaanLabTripleEHistory.objects.filter(pemeriksaan_lab=lab_instance, lab_id=lab_id, pendaftaran_id=pendaftaran.id)
        
        lab_instance.hasil = related_lab_history.values_list('hasil', flat=True).first()
        lab_instance.note = related_lab_history.values_list('note', flat=True).first()

    tarif_lab = TarifLab.objects.get(id=lab_id)

    context = {
        'tariflab': tarif_lab,
        'pendaftaran': pendaftaran,
        'pemeriksaan_lab_triplee': pemeriksaan_lab_triplee,
    }
    return render(request, 'pemeriksaan/isian/laboratorium-triplee-history.html', context)

@login_required
def post_lab_triplee(request, id):
    data = request.POST
    lab_id = data.get('lab_id')
    pendaftaran_id = data.get('pendaftaran_id')
    pemeriksaan_lab_id = data.get('pemeriksaan_id')
    hasil_lab = data.get('hasil_lab')

    today = timezone.now()
    formatted_date = today.strftime("%Y-%m-%d %H:%M:%S")
    checkLab = PemeriksaanLabTripleEHistory.objects.filter(pemeriksaan_lab_id=pemeriksaan_lab_id, pendaftaran_id=pendaftaran_id, lab_id=lab_id).first()
    if checkLab is not None:
        updateLab = PemeriksaanLabTripleEHistory.objects.get(pemeriksaan_lab_id=pemeriksaan_lab_id, pendaftaran_id=pendaftaran_id, lab_id=lab_id)
        updateLab.hasil = hasil_lab
        updateLab.save()
    else:
        input_lab = PemeriksaanLabTripleEHistory(
            pemeriksaan_lab_id=pemeriksaan_lab_id,
            pendaftaran_id=pendaftaran_id,
            lab_id=lab_id,
            hasil=hasil_lab,
            note='',
            created_at=formatted_date,
            updated_at=formatted_date
        )
        input_lab.save()

    json = {
        'lab_id' : lab_id,
        'pendaftaran_id' : pendaftaran_id,
        'pemeriksaan_id' : pemeriksaan_lab_id,
        'hasil_lab' : hasil_lab
    }
    return JsonResponse(json, safe=False)

# KEUANGAN
@login_required
def get_filter(request):
    faskes_info = InformasiDasarFaskes.objects.first()
    is_paket = faskes_info.is_paket
    laporan_keuangan = PendaftaranViews.objects.filter(status='selesai', cara_bayar=2)

    if request.POST.get('dokter_id'):
        dokter_id = request.POST.get('dokter_id')
        # Append conditions
        laporan_keuangan = laporan_keuangan.filter(dokter_id=dokter_id)
    if request.POST.get('pasien_id'):
        pasien_id = request.POST.get('pasien_id')
        laporan_keuangan = laporan_keuangan.filter(pasien_id=pasien_id)
    if request.POST.get('nama_dokter'):
        nama_dokter = request.POST.get('nama_dokter')
        laporan_keuangan = laporan_keuangan.filter(nama_dokter=nama_dokter)
    if request.POST.get('rm_no'):
        rm_no = request.POST.get('rm_no')
        laporan_keuangan = laporan_keuangan.filter(nomor_rekam_medis=rm_no)
    if request.POST.get('waktu_berobat'):
        waktu_berobat = request.POST.get('waktu_berobat')
        today = date.today()
        waktu_berobat_date = datetime.strptime(today.strftime('%Y-%m-%d'), '%Y-%m-%d').date()
        if waktu_berobat == "today":
                laporan_keuangan = laporan_keuangan.filter(created_at__date=waktu_berobat_date)
        if waktu_berobat == "week":
                laporan_keuangan = laporan_keuangan.filter(created_at__week=today.isocalendar()[1])
        if waktu_berobat == "month":
                laporan_keuangan = laporan_keuangan.filter(created_at__month=today.month)
        if waktu_berobat == "year":
                laporan_keuangan = laporan_keuangan.filter(created_at__year=today.year)

    if request.POST.get('start_date') or request.POST.get('finish_date'):
        start_date = request.POST.get('start_date')
        finish_date = request.POST.get('finish_date')
        start_date_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        finish_date_date = datetime.strptime(finish_date, '%Y-%m-%d').date()
        laporan_keuangan = laporan_keuangan.filter(created_at__range=[start_date_date, finish_date_date])

    result = []

    for x in laporan_keuangan:
        summaryinvoicebarang = 0
        invoicebarang = InvoiceBarang.objects.filter(is_dibayar=1, pendaftaran_id=x.id)

        if is_paket == 1:
            try:
                get_harga = HargaListHistory.objects.filter(pendaftaran_id=x.id).first()

                if get_harga and hasattr(get_harga.harga_list, 'price'):
                    price = get_harga.harga_list.price
                else:
                    price = 0

            except ObjectDoesNotExist:
                price = 0
            summaryinvoicebarang += price
        else:
            for xbarang in invoicebarang:
                summaryinvoicebarang += (xbarang.barang.harga_jual * xbarang.kuantitas)

        if x.is_new_pasien == True:
            fee_pendaftaran = faskes_info.fee_new_pasien
        else:
            fee_pendaftaran = faskes_info.fee_old_pasien 

        summaryinvoicelayanan = 0
        invoicelayanan = InvoiceLayanan.objects.filter(is_dibayar=1, pendaftaran_id=x.id)
        for xlayanan in invoicelayanan:
            summaryinvoicelayanan += (xlayanan.tarif_layanan.harga * xlayanan.kuantitas)

        summaryinvoicelab = 0
        invoicelab = InvoiceLab.objects.filter(is_dibayar=1, pendaftaran_id=x.id)
        for x in invoicelab:
            summaryinvoicelab += (x.tarif_lab.harga * x.kuantitas)  

        x.harga_obat = summaryinvoicebarang
        x.administrasi_pendaftaran = fee_pendaftaran
        x.total_layanan_harga = summaryinvoicelayanan
        x.total_lab_harga = summaryinvoicelab
        x.apd = 0
        x.total = summaryinvoicebarang + summaryinvoicelayanan + summaryinvoicelab + fee_pendaftaran

        result.append({
            'nomor_rekam_medis': x.nomor_rekam_medis,
            'nama_pasien': x.nama_pasien,
            'nama_dokter': x.nama_dokter,
            'harga_obat': x.harga_obat,
            'administrasi_pendaftaran': x.administrasi_pendaftaran,
            'total_layanan_harga': x.total_layanan_harga,
            'total_lab_harga': x.total_lab_harga,
            'apd': x.apd,
            'total': x.total,
        })

    return JsonResponse(result, safe=False)
    # return JsonResponse(list(laporan_keuangan.values()), safe=False)
    
    # combined_data = {
    #     'result': result,
    #     'laporan_keuangan': list(laporan_keuangan.values()),
    # }

    # return JsonResponse(combined_data, safe=False)


@login_required
def get_leaderboards(request):
    date = request.GET.get('date')

    duplicates = PendaftaranViews.objects.values('pasien_id', 'nama_pasien').annotate(
        count_kunjungan=Count('pasien_id'),
        count_layanan=Sum('harga_layanan_real')
    ).order_by('-count_layanan', '-count_kunjungan')

    if date == 'today':
        filter_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
        filter_end = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=999999)
        duplicates = duplicates.filter(created_at__range=(filter_start, filter_end))

    elif date == 'week':
        filter_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=timezone.localtime(timezone.now()).weekday())
        filter_end = filter_start + timezone.timedelta(days=6)
        duplicates = duplicates.filter(created_at__range=(filter_start, filter_end))

    elif date == 'currentmonth':
        filter_start = timezone.localtime(timezone.localtime(timezone.now())).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        _, last_day_of_month = calendar.monthrange(filter_start.year, filter_start.month)
        filter_end = timezone.localtime(timezone.now()).replace(day=last_day_of_month, hour=23, minute=59, second=59, microsecond=999999)
        duplicates = duplicates.filter(created_at__range=(filter_start, filter_end))
        
    elif date == 'lastmonth':
        filter_end = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=1)
        filter_start = filter_end.replace(day=1)
        duplicates = duplicates.filter(created_at__range=(filter_start, filter_end))

    elif date == 'range':
        filter_start = request.GET.get('start_date') + ' 00:00:00'
        filter_end = request.GET.get('end_date') + ' 00:00:00'
        duplicates = duplicates.filter(created_at__range=(filter_start, filter_end))

    else:
        filter_end = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=1)
        filter_start = filter_end.replace(day=1)
        duplicates = duplicates.filter(created_at__range=(filter_start, filter_end))
    
    export = request.GET.get('export')
    if export == 'excel':
        collect = duplicates[:15]
        pasien_ids = []
        for item in collect:
            pasien_ids.append(item['pasien_id'])

        order_cases = [When(pasien_id=id, then=Value(index)) for index, id in enumerate(pasien_ids)]
        # Construct the custom ordering
        ordering = Case(*order_cases, output_field=IntegerField())
        # Query and order according to the array positions
        result = export_top_leaderboards(pasien_ids, filter_start, filter_end, ordering)
        return result
        # return JsonResponse(list(get_pendaftaran), safe=False)

    return JsonResponse(list(duplicates)[:15], safe=False)

@login_required
def get_chart_pendapatan(request):
    user_id = request.user.id
    usergroups = request.user.groups.all().values()
    get_usergroup = list(usergroups)
    for x in get_usergroup:
        usergroup = x['name']

    # start_date = '2024-01-01'
    # finish_date = '2024-01-30'

    # start_date_date = datetime.strptime(start_date, '%Y-%m-%d').date()
    # finish_date_date = datetime.strptime(finish_date, '%Y-%m-%d').date()
    
    # pendaftaran_ids = Pendaftaran.objects.filter(created_at__range=[start_date_date, finish_date_date]).values_list('id', flat=True)
    date = request.GET.get('date')
    start_date = request.GET.get('start_date') + ' 00:00:00'
    end_date = request.GET.get('end_date') + ' 00:00:00'

    if date == 'today':
        today_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
        today_end = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=999999)
        pendaftaran_ids = PendaftaranViews.objects.filter(created_at__range=(today_start, today_end)).values_list('id', flat=True)

    elif date == 'week':
        week_start = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=timezone.localtime(timezone.now()).weekday())
        week_end = week_start + timezone.timedelta(days=6)
        pendaftaran_ids = PendaftaranViews.objects.filter(created_at__range=(week_start, week_end)).values_list('id', flat=True)

    elif date == 'currentmonth':
        month_start = timezone.localtime(timezone.localtime(timezone.now())).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        print(month_start)
        _, last_day_of_month = calendar.monthrange(month_start.year, month_start.month)
        month_end = timezone.localtime(timezone.now()).replace(day=last_day_of_month, hour=23, minute=59, second=59, microsecond=999999)
        print(month_end)
        pendaftaran_ids = PendaftaranViews.objects.filter(created_at__range=(month_start, month_end)).values_list('id', flat=True)

    elif date == 'lastmonth':
        last_month_end = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=1)
        last_month_start = last_month_end.replace(day=1)
        pendaftaran_ids = PendaftaranViews.objects.filter(created_at__range=(last_month_start, last_month_end)).values_list('id', flat=True)

    elif date == 'range':
        pendaftaran_ids = PendaftaranViews.objects.filter(created_at__range=(start_date, end_date)).values_list('id', flat=True)

    else:
        month_start = timezone.localtime(timezone.now()).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        _, last_day_of_month = calendar.monthrange(month_start.year, month_start.month)
        month_end = timezone.localtime(timezone.now()).replace(day=last_day_of_month, hour=23, minute=59, second=59, microsecond=999999)
        pendaftaran_ids = PendaftaranViews.objects.filter(created_at__range=(month_start, month_end)).values_list('id', flat=True)

    if usergroup == "SUPERADMIN":
        faskes_info = InformasiDasarFaskes.objects.first()
        is_paket = faskes_info.is_paket
        laporan_keuangan = PendaftaranViews.objects.filter(id__in=pendaftaran_ids, status='selesai', cara_bayar=2)
        
        totalPembayaran = 0
        for x in laporan_keuangan:
            summaryinvoicebarang = 0
            invoicebarang = InvoiceBarang.objects.filter(is_dibayar=1, pendaftaran_id=x.id)
            if is_paket == 1:
                try:
                    get_harga = HargaListHistory.objects.filter(pendaftaran_id=x.id).first()

                    if get_harga and hasattr(get_harga.harga_list, 'price'):
                        price = get_harga.harga_list.price
                    else:
                        price = 0

                except ObjectDoesNotExist:
                    price = 0
                summaryinvoicebarang += price
            else:
                for xbarang in invoicebarang:
                    xbarang.total_harga =  (xbarang.barang.harga_jual * xbarang.kuantitas)
                    summaryinvoicebarang += xbarang.total_harga
                    check_diskon = PromotionDiskonHistory.objects.filter(layanan_diskon_id=xbarang.barang.id, jenis_diskon="barang", diskon__is_active=1, diskon__min_qty__lte=xbarang.kuantitas).exists()
                    if check_diskon:
                        if xbarang.diskon_pembelian == 0:
                            get_data = PromotionDiskonHistory.objects.get(layanan_diskon_id=xbarang.barang.id, jenis_diskon="barang", diskon__is_active=1, diskon__min_qty__lte=xbarang.kuantitas)
                            xbarang.diskon_layanan = get_data.diskon.diskon
                            xbarang.tipe_diskon = get_data.diskon.tipe_diskon
                            if xbarang.tipe_diskon == '%':
                                potongan = xbarang.total_harga * (int(xbarang.diskon_layanan) / 100)
                                xbarang.total_harga = xbarang.total_harga - potongan
                                summaryinvoicebarang -= potongan
                            else: 
                                xbarang.total_harga = xbarang.total_harga - int(xbarang.diskon_layanan)
                                summaryinvoicebarang -= int(xbarang.diskon_layanan)

                        else:
                            xbarang.tipe_diskon = xbarang.tipe_diskon
                            xbarang.diskon_layanan = xbarang.diskon_pembelian
                            if xbarang.tipe_diskon == '%':
                                potongan = xbarang.total_harga * (int(xbarang.diskon_layanan) / 100)
                                xbarang.total_harga = xbarang.total_harga - potongan
                                summaryinvoicebarang -= potongan
                            else: 
                                xbarang.total_harga = xbarang.total_harga - int(xbarang.diskon_layanan)
                                summaryinvoicebarang -= int(xbarang.diskon_layanan)
                    else:
                        if xbarang.diskon_pembelian == None:
                            xbarang.diskon_pembelian = 0
                        if xbarang.diskon_pembelian != 0:
                            xbarang.tipe_diskon = xbarang.tipe_diskon
                            xbarang.diskon_layanan = xbarang.diskon_pembelian
                            if xbarang.tipe_diskon == '%':
                                potongan = xbarang.total_harga * (int(xbarang.diskon_layanan) / 100)
                                xbarang.total_harga = xbarang.total_harga - potongan
                                summaryinvoicebarang -= potongan
                            else: 
                                xbarang.total_harga = xbarang.total_harga - int(xbarang.diskon_layanan)
                                summaryinvoicebarang -= int(xbarang.diskon_layanan)
                        else:
                            xbarang.diskon_layanan = 0
                            xbarang.tipe_diskon = '%'

            if x.is_new_pasien == True:
                fee_pendaftaran = faskes_info.fee_new_pasien
            else:
                fee_pendaftaran = faskes_info.fee_old_pasien 

            summaryinvoicelayanan = 0
            invoicelayanan = InvoiceLayanan.objects.filter(is_dibayar=1, pendaftaran_id=x.id)
            for xlayanan in invoicelayanan:
                xlayanan.total_harga = (xlayanan.tarif_layanan.harga * xlayanan.kuantitas)
                summaryinvoicelayanan += xlayanan.total_harga
                # check diskon greater than or equal to
                check_diskon = PromotionDiskonHistory.objects.filter(layanan_diskon_id=xlayanan.tarif_layanan.id, jenis_diskon="tindakan", diskon__is_active=1, diskon__min_qty__lte=xlayanan.kuantitas).exists()
                if check_diskon:
                    if xlayanan.diskon_pembelian == 0:
                        get_data = PromotionDiskonHistory.objects.get(layanan_diskon_id=xlayanan.tarif_layanan.id, jenis_diskon="tindakan", diskon__is_active=1, diskon__min_qty__lte=xlayanan.kuantitas)
                        xlayanan.diskon_layanan = get_data.diskon.diskon
                        xlayanan.tipe_diskon = get_data.diskon.tipe_diskon
                        if xlayanan.tipe_diskon == '%':
                            potongan = xlayanan.total_harga * (float(xlayanan.diskon_layanan) / 100)
                            xlayanan.total_harga = xlayanan.total_harga - potongan
                            summaryinvoicelayanan -= potongan
                        else: 
                            xlayanan.total_harga = xlayanan.total_harga - float(xlayanan.diskon_layanan)
                            summaryinvoicelayanan -= float(xlayanan.diskon_layanan)

                    else:
                        xlayanan.tipe_diskon = xlayanan.tipe_diskon
                        xlayanan.diskon_layanan = xlayanan.diskon_pembelian
                        if xlayanan.tipe_diskon == '%':
                            potongan = xlayanan.total_harga * (float(xlayanan.diskon_layanan) / 100)
                            xlayanan.total_harga = xlayanan.total_harga - potongan
                            summaryinvoicelayanan -= potongan
                        else: 
                            xlayanan.total_harga = xlayanan.total_harga - float(xlayanan.diskon_layanan)
                            summaryinvoicelayanan -= float(xlayanan.diskon_layanan)
                else:
                    if xlayanan.diskon_pembelian == None:
                        xlayanan.diskon_pembelian = 0
                    if xlayanan.diskon_pembelian != 0:
                        xlayanan.tipe_diskon = xlayanan.tipe_diskon
                        xlayanan.diskon_layanan = xlayanan.diskon_pembelian
                        if xlayanan.tipe_diskon == '%':
                            potongan = xlayanan.total_harga * (float(xlayanan.diskon_layanan) / 100)
                            xlayanan.total_harga = xlayanan.total_harga - potongan
                            summaryinvoicelayanan -= potongan
                        else: 
                            xlayanan.total_harga = xlayanan.total_harga - float(xlayanan.diskon_layanan)
                            summaryinvoicelayanan -= float(xlayanan.diskon_layanan)
                    else:
                        xlayanan.diskon_layanan = 0
                        xlayanan.tipe_diskon = '%'

            summaryinvoicelab = 0
            invoicelab = InvoiceLab.objects.filter(is_dibayar=1, pendaftaran_id=x.id)
            for xlab in invoicelab:
                summaryinvoicelab += (xlab.tarif_lab.harga * xlab.kuantitas)       

            x.harga_obat = summaryinvoicebarang
            x.administrasi_pendaftaran = fee_pendaftaran
            x.total_layanan_harga = summaryinvoicelayanan
            x.total_lab_harga = summaryinvoicelab
            x.apd = 0
            x.total = summaryinvoicebarang + summaryinvoicelayanan + fee_pendaftaran + summaryinvoicelab
            totalPembayaran += int(x.total)
    
    else:
        totalPembayaran = 0
        invoicelayanan = InvoiceLayanan.objects.filter(is_dibayar=1, dokter_id=user_id, pendaftaran_id__in=pendaftaran_ids)
        invoicelayanan = invoicelayanan.annotate(
            total_harga_layanan=(F('tarif_layanan__harga') -  F('tarif_layanan__presentase_dokter_rp')) * ((F('tarif_layanan__presentase_dokter_persen')) / 100) * F('kuantitas')
        ).aggregate(Sum('total_harga_layanan'))

        total_harga_layanan = invoicelayanan['total_harga_layanan__sum'] or 0

        totalPembayaran = total_harga_layanan

    return JsonResponse(totalPembayaran, safe=False)
    
@login_required
def laporan_keuangan(request):
    faskes_info = InformasiDasarFaskes.objects.first()
    is_paket = faskes_info.is_paket
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
    laporan_keuangan = PendaftaranViews.objects.filter(status='selesai', cara_bayar=2)

    for x in laporan_keuangan:
        summaryinvoicebarang = 0
        invoicebarang = InvoiceBarang.objects.filter(is_dibayar=1, pendaftaran_id=x.id)
        if is_paket == 1:
            try:
                get_harga = HargaListHistory.objects.filter(pendaftaran_id=x.id).first()

                if get_harga and hasattr(get_harga.harga_list, 'price'):
                    price = get_harga.harga_list.price
                else:
                    price = 0

            except ObjectDoesNotExist:
                price = 0
            summaryinvoicebarang += price
        else:
            for xbarang in invoicebarang:
                summaryinvoicebarang += (xbarang.barang.harga_jual * xbarang.kuantitas)

        if x.is_new_pasien == True:
            fee_pendaftaran = faskes_info.fee_new_pasien
        else:
            fee_pendaftaran = faskes_info.fee_old_pasien 

        summaryinvoicelayanan = 0
        invoicelayanan = InvoiceLayanan.objects.filter(is_dibayar=1, pendaftaran_id=x.id)
        for xlayanan in invoicelayanan:
            summaryinvoicelayanan += (xlayanan.tarif_layanan.harga * xlayanan.kuantitas)

        summaryinvoicelab = 0
        invoicelab = InvoiceLab.objects.filter(is_dibayar=1, pendaftaran_id=x.id)
        for xlab in invoicelab:
            summaryinvoicelab += (xlab.tarif_lab.harga * xlab.kuantitas)       

        x.harga_obat = summaryinvoicebarang
        x.administrasi_pendaftaran = fee_pendaftaran
        x.total_layanan_harga = summaryinvoicelayanan
        x.total_lab_harga = summaryinvoicelab
        x.apd = 0
        x.total = summaryinvoicebarang + summaryinvoicelayanan + summaryinvoicelab + fee_pendaftaran
    
    # return JsonResponse()

    user_groups = request.user.groups.all()
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'menu_items': menu_items,
        'laporan_keuangan': laporan_keuangan,
        'dokter': dokter,
    }
    return render(request, 'pemeriksaan/laporan/laporan_keuangan.html', context)

row_num = 0
def increment_row_num():
    global row_num  # Declare 'row_num' as a global variable within the function
    row_num += 1    # Increment the global variable
    return row_num
    
@login_required
def import_data_pasien(request):
    file_name = 'alamat_pasien.xlsx'
    file_path = os.path.join('templates', 'import', 'excel', file_name)

    df = pd.read_excel(file_path, usecols=[1, 2, 3, 4], skiprows=3)

    data_list = df.values.tolist()

    pasien_list = []

    for item in data_list:
        nama_pasien = item[0]

        if not pd.isna(nama_pasien):
            kontak = item[2]
            if isinstance(item[2], str) and item[2].startswith("'"):
                kontak_no = kontak[1:]
            else:
                kontak_no = 0
            try:
                biodata = Biodata.objects.get(first_name=item[0])
                biodata.alamat = item[1]
                biodata.kontak = kontak_no
                biodata.pekerjaan = item[3]
                biodata.save()
            except Biodata.DoesNotExist:
                # Handle the case where the object is not found
                print("skipping")
            # pendaftaran = {
            #     'nama_pasien': item[0],
            #     'alamat': item[1],
            #     'telepon': item[2],
            #     'pekerjaan': item[3],
            # }
            # pasien_list.append(pendaftaran)

    return JsonResponse("berhasil, hore", safe=False)

@login_required
def export_excel_uang(request):
    # Create a new workbook and select the active sheet
    wb = Workbook()
    ws = wb.active

    # Define the title
    ws.merge_cells("A1:P1")
    title = "LAPORAN DATA PASIEN DAN PEMASUKAN KEUANGAN PER HARI"

    # Set the title in cell A1 with bold font
    title_cell = ws.cell(row=1, column=1, value=title)
    title_cell.alignment = Alignment(horizontal='center', vertical='center')
    title_cell.font = Font(bold=True)

    # Define the subtitle
    ws.merge_cells("A2:P2")
    info_dasar_faskes = InformasiDasarFaskes.objects.first()
    subtitle = info_dasar_faskes.nama

    # Set the subtitle in cell A1 with bold font
    subtitle_cell = ws.cell(row=2, column=1, value=subtitle)
    subtitle_cell.alignment = Alignment(horizontal='center', vertical='center')
    subtitle_cell.font = Font(bold=True)

    # Define the title
    ws.merge_cells("A3:P3")
    alamat = info_dasar_faskes.alamat

    # Set the alamat in cell A1 with bold font
    alamat_cell = ws.cell(row=3, column=1, value=alamat)
    alamat_cell.alignment = Alignment(horizontal='center', vertical='center')

    # Define the email
    ws.merge_cells("A4:P4")
    email = "email: -@aklik.id"

    # Set the email in cell A1 with bold font
    email_cell = ws.cell(row=4, column=1, value=email)
    email_cell.alignment = Alignment(horizontal='center', vertical='center')
    email_font = Font(bold=True, color="0000FF")  # "0000FF" is the code for blue
    email_cell.font = email_font

    # Define the column headers
    column_headers = [
        "No", "Tanggal", "Medrek", "Nama Pasien", "Umur", "JK", "Alamat",
        "No HP", "Diagnosa", "Layanan", "Kuantitas", "Layanan Lab", "Obat", "Harga Obat", "Adm. Pendaftaran", "Tindakan", "Harga Lab", "APD", "TOTAL",
    ]

    # Set the column headers in the worksheet
    for col_num, column_title in enumerate(column_headers, 1):
        cell = ws.cell(row=7, column=col_num, value=column_title)
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        
        col_letter = get_column_letter(col_num)
        max_width = max(len(str(column_title)), 15)  # Minimum width of 10 characters
        ws.column_dimensions[col_letter].width = max_width

        # Merge cells for "JML Pembayaran" and add sub-columns

    faskes_info = InformasiDasarFaskes.objects.first()
    is_paket = faskes_info.is_paket
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
    base_query = PendaftaranViews.objects.filter(status='selesai', cara_bayar=2)
    user_id = request.user.id
    usergroups = request.user.groups.all().values()
    get_usergroup = list(usergroups)
    for x in get_usergroup:
        usergroup = x['name']
    
    if usergroup == "DOKTER":
        base_query = base_query.filter(dokter_id=user_id)

    if request.GET.get('dokter_id') and request.GET.get('dokter_id') != 'null':
        dokter_id = request.GET.get('dokter_id')
        # Append conditions
        base_query = base_query.filter(dokter_id=dokter_id)
    if request.GET.get('pasien_id'):
        pasien_id = request.GET.get('pasien_id')
        base_query = base_query.filter(pasien_id=pasien_id)
    if request.GET.get('rm_no'):
        rm_no = request.GET.get('rm_no')
        base_query = base_query.filter(nomor_rekam_medis=rm_no)
    if request.GET.get('waktu_berobat'):
        waktu_berobat = request.GET.get('waktu_berobat')
        today = date.today()
        waktu_berobat_date = datetime.strptime(today.strftime('%Y-%m-%d'), '%Y-%m-%d').date()
        if waktu_berobat == "today":
                base_query = base_query.filter(created_at__date=waktu_berobat_date)
        if waktu_berobat == "week":
                base_query = base_query.filter(created_at__week=today.isocalendar()[1])
        if waktu_berobat == "month":
                base_query = base_query.filter(created_at__month=today.month)
        if waktu_berobat == "year":
                base_query = base_query.filter(created_at__year=today.year)

    if request.GET.get('start_date') or request.GET.get('finish_date'):
        start_date = request.GET.get('start_date')
        finish_date = request.GET.get('finish_date')
        # print(start_date)
        start_date_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        finish_date_date = datetime.strptime(finish_date, '%Y-%m-%d').date()

        base_query = base_query.filter(created_at__range=[start_date_date, finish_date_date])
        # base_query = base_query.order_by('-created_at').values('id')[:1]
        base_query = base_query.order_by('-created_at')

    for row_data in base_query:
        summaryinvoicebarang = 0
        invoicebarang = InvoiceBarang.objects.filter(is_dibayar=1, pendaftaran_id=row_data.id)
        if is_paket == 1:
            try:
                get_harga = HargaListHistory.objects.filter(pendaftaran_id=row_data.id).first()

                if get_harga and hasattr(get_harga.harga_list, 'price'):
                    price = get_harga.harga_list.price
                else:
                    price = 0

            except ObjectDoesNotExist:
                price = 0
            summaryinvoicebarang += price
        else:
            for xbarang in invoicebarang:
                summaryinvoicebarang += (xbarang.barang.harga_jual * xbarang.kuantitas)

        if row_data.is_new_pasien == True:
            fee_pendaftaran = faskes_info.fee_new_pasien
        else:
            fee_pendaftaran = faskes_info.fee_old_pasien 

        summaryinvoicelayanan = 0
        invoicelayanan = InvoiceLayanan.objects.filter(is_dibayar=1, pendaftaran_id=row_data.id)
        for xlayanan in invoicelayanan:
            summaryinvoicelayanan += (xlayanan.tarif_layanan.harga * xlayanan.kuantitas)

        summaryinvoicelab = 0
        invoicelab = InvoiceLab.objects.filter(is_dibayar=1, pendaftaran_id=row_data.id)
        for xlab in invoicelab:
            summaryinvoicelab += (xlab.tarif_lab.harga * xlab.kuantitas)

        row_data.harga_obat = summaryinvoicebarang
        row_data.administrasi_pendaftaran = fee_pendaftaran
        row_data.total_layanan_harga = summaryinvoicelayanan
        row_data.total_lab_harga = summaryinvoicelab
        row_data.apd = 0
        row_data.total = summaryinvoicebarang + summaryinvoicelayanan + summaryinvoicelab + fee_pendaftaran


        # for x in unique_invoicelayanan_list:
        get_layanan = InvoiceLayanan.objects.filter(pendaftaran_id=row_data.id)
        # return JsonResponse(x.id, safe=False)
        get_layanan = get_layanan.annotate(
            harga_layanan=F('tarif_layanan__harga'),
            qty=F('kuantitas')
        )

        get_layanan_lab = InvoiceLab.objects.filter(pendaftaran_id=row_data.id)
        # return JsonResponse(x.id, safe=False)
        get_layanan_lab = get_layanan_lab.values('pendaftaran_id').annotate(
            harga_lab=F('tarif_lab__harga'),
            nama_lab=F('tarif_lab__nama'),
            qty=F('kuantitas')
        )
        list_lab = list(get_layanan_lab)
        nama_lab = ', '.join(map(lambda x: str(x['nama_lab']), list_lab))
            
        getDiagnosa = InputIcd10.objects.filter(pendaftaran_id=row_data.id)
        getDiagnosa = getDiagnosa.annotate(
            diagnosa=F('icd10__diagnosa'),
            kode_diagnosa=F('icd10__kode'),
        )
        diagnosa_list = list(getDiagnosa)
        diagnosa = stringFromArray('diagnosa', diagnosa_list)
        joined_diagnosa = ', '.join(str(diag.kode_diagnosa) for diag in diagnosa_list)  

        invoicebarang = InvoiceBarang.objects.filter(pendaftaran_id=row_data.id)
        invoicebarang = invoicebarang.values('pendaftaran_id').annotate(
            nama_obat=F('barang__nama'),
            harga_barang=F('barang__harga_jual'),
        )
        # Contoh penggunaan langsung tanpa deklarasi fungsi
        list_obat = list(invoicebarang)
        nama_obat = ', '.join(map(lambda x: str(x['nama_obat']), list_obat))


        created_at_string = row_data.created_at.replace(tzinfo=None)
        tanggal= created_at_string.strftime('%y-%m-%d')

        check_id = set()
        # number = 0
        global number
        number = 0
        if len(get_layanan) > 0:
            for push_layanan in get_layanan:
                pendaftaran_id = push_layanan.pendaftaran_id
                
                if pendaftaran_id in check_id:
                    perlayanan = push_layanan.harga_layanan - push_layanan.tarif_layanan.presentase_dokter_rp
                    row = [
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        push_layanan.tarif_layanan.nama,
                        '',
                        '',
                        '',
                        '',
                        '',
                        perlayanan,
                        '',
                        push_layanan.tarif_layanan.presentase_dokter_rp,
                        '',
                    ]
                    ws.append(row)
                else:
                    check_id.add(push_layanan.pendaftaran_id)
                    perlayanan = push_layanan.harga_layanan - push_layanan.tarif_layanan.presentase_dokter_rp
                    number += 1
                    row = [
                        increment_row_num(),
                        tanggal,
                        row_data.nomor_rekam_medis,
                        row_data.nama_pasien,
                        checkUsia(row_data.tanggal_lahir),
                        row_data.jenis_kelamin,
                        row_data.alamat,
                        '',
                        joined_diagnosa,
                        push_layanan.tarif_layanan.nama,
                        push_layanan.qty,
                        nama_lab,
                        nama_obat,
                        row_data.harga_obat,
                        row_data.administrasi_pendaftaran,
                        perlayanan,
                        row_data.total_lab_harga,
                        push_layanan.tarif_layanan.presentase_dokter_rp,
                        row_data.total,
                    ]
                    ws.append(row)
        else:
            number += 1
            row = [
                increment_row_num(),
                tanggal,
                row_data.nomor_rekam_medis,
                row_data.nama_pasien,
                checkUsia(row_data.tanggal_lahir),
                row_data.jenis_kelamin,
                row_data.alamat,
                '',
                joined_diagnosa,
                '',
                '',
                nama_lab,
                nama_obat,
                row_data.harga_obat,
                row_data.administrasi_pendaftaran,
                '',
                row_data.total_lab_harga,
                '',
                row_data.total,
            ]
            ws.append(row)
    
    border = Border(left=Side(style='thin'), 
                    right=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thin')
                    )

    for row in ws.iter_rows(min_row=7, max_row=ws.max_row, min_col=1, max_col=ws.max_column):
        for cell in row:
            cell.border = border

    # Set response headers for Excel file download
    response = HttpResponse(content_type='application/ms-excel')
    tanggal_dibuat = datetime.now()
    response['Content-Disposition'] = f'attachment; filename="laporan-keuangan{tanggal_dibuat}.xlsx"'

    # Save the workbook to the response
    wb.save(response)

    return response
    
@login_required
def kontrol(request):
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()

    return render(request, 'pemeriksaan/kontrol_pasien.html', {'menu_items': menu_items})

@login_required
def get_kontrol(request):
    tanggal_sekarang = datetime.now().date()
    wkt_kntrl = datetime.combine(tanggal_sekarang, datetime.min.time())
    
    now = timezone.now()
    get_now = now - timedelta(days=1)
    two_days_later = now + timedelta(days=1)
    amonth_later = now + timedelta(days=30)
    get_pasien = PendaftaranViews.objects.filter(waktu_kontrol__range=(get_now, two_days_later)).values()

    return JsonResponse(list(get_pasien), safe=False)

@login_required
def check_kontrol(request):
    tanggal_sekarang = datetime.now().date()
    wkt_kntrl = datetime.combine(tanggal_sekarang, datetime.min.time())

    data_kontrol = PemeriksaanPendaftaranViews.objects.filter(status='selesai', waktu_kontrol__gte=wkt_kntrl).values()
    if len(data_kontrol) > 0:
        pasien_kontrol = True
    else:
        pasien_kontrol = False

    objects_kontrol = {
        'total': len(data_kontrol)
    }

    data_pembayaran = PendaftaranViews.objects.filter(Q(is_dp=1)).values()
    # return JsonResponse(list(data_pembayaran), safe=False)
    if len(data_pembayaran) > 0:
        pembayaran = True
    else:
        pembayaran = False

    objects_pembayaran = {
        'total': len(data_pembayaran)
    }

    return JsonResponse({'kontrol': {'pasien': pasien_kontrol, 'objects': objects_kontrol},
                         'pembayaran': {'pasien': pembayaran, 'objects': objects_pembayaran},
                         'pesan': {'pasien': False, 'objects': {'total': 0}}}, safe=False)

@login_required
def jasmed(request):
    user_groups = request.user.groups.all()
    data_jasmed = Biodata.objects.filter(is_staff='1').values()
    grup = Group.objects.all()

    for x in data_jasmed:
        user = User.objects.get(id=x['user_ptr_id'])
        groups = user.groups.all()
        group_names = [group.name for group in groups]
        x['group_name'] = ', '.join(group_names)

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'menu_items': menu_items,
        'data_jasmed': data_jasmed,
        'grup' : grup,
    }
    return render(request, 'pemeriksaan/jasmed/base.html', context)

@login_required
def tambah_jasmed(request):
    # user = Loket.objects.get(petugas__username=request.user.username)
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        nominal = request.POST.get('nominal')
        group = request.POST.get('group')
        created_at = timezone.now()
        # update_by = 'user'
        updated_at = timezone.now()

        tambahNakes = JasaMedis(
            user=Biodata.objects.get(id=user_id),
            nominal=nominal,
            created_at=created_at,
            # update_by=update_by,
            group=Group.objects.get(id=group),
            updated_at=updated_at,
        )
        tambahNakes.save()

        return redirect('/pemeriksaan/jasmed')

# @login_required
# def data_jasmed(request):
#     jasmed = JasaMedis.objects.all()
#     for x in jasmed:
#         user = User.objects.get(id=x['user_id'])
#         x['group_name'] = x.group.name
#         x['first_name'] = user.first_name

#     context = {
#         'id' : id,
#         'first_name' : first_name,
#         'group_name' : group_name,
#         'nominal' : nominal,
#     }

#     return JsonResponse(context, safe=False)

@login_required
def data_jasmed(request):
    jasmed = JasaMedis.objects.all()
    
    data = []
    for x in jasmed:
        user = User.objects.get(id=x.user_id)
        context = {
            'id': x.id,
            'user_id': user.id,
            'first_name': user.first_name,
            'group_name': x.group.name,
            'nominal': x.nominal,
        }
        data.append(context)

    return JsonResponse(data, safe=False)


@login_required
def get_data_nakes(request, id):
    nakes = JasaMedis.objects.get(id=id)
    user = User.objects.get(id=nakes.user_id)
    data = {
        'id': nakes.id,
        'nama': user.first_name,
        'nominal': nakes.nominal,
    }
    
    return JsonResponse(data)

@login_required
def edit_jasmed(request, id):
    nakes = JasaMedis.objects.get(id=id)
    nominal = request.POST.get('nominal_baru')
    nakes.nominal = (nominal)
    nakes.save()

    if nominal != "":
        return JsonResponse({'message':"ok"})
    else:
        return JsonResponse({'message': 'Data anda Kosong'})

@login_required
def get_history_jasmed(request):
    base_query = PendaftaranViews.objects.filter(status='selesai').values()
    user_id = request.POST.get('user_id')
    group_name = request.POST.get('group_name')
    month = request.POST.get('month')
    year = request.POST.get('year')
    field_kwargs = {'dokter_id': user_id}
    jasmed_user = 'dokter_jasmed'

    if group_name == "DOKTER":
        base_query = base_query.filter(dokter_id=user_id)
        field_kwargs = {'dokter_id': user_id}
        jasmed_user = 'dokter_jasmed'
        
    if group_name == "ADMIN":
        base_query = base_query.filter(petugas_id=user_id)
        field_kwargs = {'petugas_id': user_id}
        jasmed_user = 'admin_jasmed'

    if group_name == "PERAWAT":
        base_query = base_query.filter(user_perawat_id=user_id)
        field_kwargs = {'user_perawat_id': user_id}
        jasmed_user = 'perawat_jasmed'
        
    if group_name == "FARMASI":
        base_query = base_query.filter(user_farmasi_id=user_id)
        field_kwargs = {'user_farmasi_id': user_id}
        jasmed_user = 'farmasi_jasmed'

    if group_name == "LAB":
        base_query = base_query.filter(user_lab_id=user_id)
        field_kwargs = {'user_lab_id': user_id}
        jasmed_user = 'lab_jasmed'

    if request.POST.get('month'):
        month = request.POST.get('month')
        base_query = base_query.filter(created_at__month=month)
    if request.POST.get('year'):
        year = request.POST.get('year')
        base_query = base_query.filter(created_at__year=year)

    # Hitung total pasien
    total_pasien = base_query.count()
    # return JsonResponse(user_id, safe=False)

    # Hitung total nominal (contoh untuk dokter_jasmed, sesuaikan dengan field yang sesuai)
    pendaftaran_ids = Pendaftaran.objects.filter(status='selesai', **field_kwargs, created_at__month=month, created_at__year=year).values_list('id', flat=True)
    total_nominal = base_query.aggregate(total_nominal=Sum(jasmed_user))['total_nominal']
    
    invoicelayanan = InvoiceLayanan.objects.filter(is_dibayar=1, pendaftaran_id__in=pendaftaran_ids)
    invoicelayanan = invoicelayanan.annotate(
        total_harga_layanan=(F('tarif_layanan__harga') -  F('tarif_layanan__presentase_dokter_rp')) * ((F('tarif_layanan__presentase_dokter_persen')) / 100) * F('kuantitas')
    ).aggregate(Sum('total_harga_layanan'))
    total_harga_layanan = invoicelayanan['total_harga_layanan__sum'] or 0
    if group_name != "DOKTER":
        total_harga_layanan = 0
    # Persiapkan respons JSON
    response_data = {
        'data': list(base_query),  # Ubah queryset menjadi list
        'total_pasien': total_pasien,
        'total_nominal': total_nominal if total_nominal else 0,  # Jika total_nominal None, kembalikan 0
        'total_fee': total_harga_layanan,  # Jika total_nominal None, kembalikan 0
    }

    return JsonResponse(response_data, safe=False)

@login_required
def export_excel_jasmed(request):
    # Create a new workbook and select the active sheet
    wb = Workbook()
    ws = wb.active

    # Define the title
    ws.merge_cells("A1:G1")
    title = "LAPORAN PENGHASILAN DOKTER"

    # Set the title in cell A1 with bold font
    title_cell = ws.cell(row=1, column=1, value=title)
    title_cell.alignment = Alignment(horizontal='center', vertical='center')
    title_cell.font = Font(bold=True)

    # Define the subtitle
    ws.merge_cells("A2:G2")
    info_dasar_faskes = InformasiDasarFaskes.objects.first()
    subtitle = info_dasar_faskes.nama

    # Set the subtitle in cell A1 with bold font
    subtitle_cell = ws.cell(row=2, column=1, value=subtitle)
    subtitle_cell.alignment = Alignment(horizontal='center', vertical='center')
    subtitle_cell.font = Font(bold=True)

    # Define the title
    ws.merge_cells("A3:G3")
    alamat = info_dasar_faskes.alamat

    # Set the alamat in cell A1 with bold font
    alamat_cell = ws.cell(row=3, column=1, value=alamat)
    alamat_cell.alignment = Alignment(horizontal='center', vertical='center')

    # Define the email
    ws.merge_cells("A4:G4")
    email = "email: -"

    # Set the email in cell A1 with bold font
    email_cell = ws.cell(row=4, column=1, value=email)
    email_cell.alignment = Alignment(horizontal='center', vertical='center')
    email_font = Font(bold=True, color="0000FF")  # "0000FF" is the code for blue
    email_cell.font = email_font

    # Define the column headers
    column_headers = [
        "No", "Tanggal", "Nama Pasien", "Nama Dokter", "Perawatan", "Harga Perawatan", "Kuantitas", "Fee Dokter", "BHP", "PERSEN %"
    ]

    # Set the column headers in the worksheet
    for col_num, column_title in enumerate(column_headers, 1):
        cell = ws.cell(row=7, column=col_num, value=column_title)
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        
        col_letter = get_column_letter(col_num)
        max_width = max(len(str(column_title)), 15)  # Minimum width of 10 characters
        ws.column_dimensions[col_letter].width = max_width
    
    user_id = request.GET.get('user_id')
    group_name = request.GET.get('group_name')
    month = request.GET.get('month')
    year = request.GET.get('year')
    get_layanan = InvoiceLayanan.objects.filter(is_dibayar=True, pendaftaran_id__isnull=False, created_at__month=month, created_at__year=year)
    field_kwargs = {'dokter_id': user_id}

    if group_name == "DOKTER":
        get_layanan = get_layanan.filter(dokter_id=user_id)
        field_kwargs = {'dokter_id': user_id}
        
    if group_name == "ADMIN":
        get_layanan = get_layanan.filter(pendaftaran__petugas_id=user_id)
        field_kwargs = {'petugas_id': user_id}

    if group_name == "PERAWAT":
        get_layanan = get_layanan.filter(pendaftaran__user_perawat_id=user_id)
        field_kwargs = {'user_perawat_id': user_id}
        
    if group_name == "FARMASI":
        get_layanan = get_layanan.filter(pendaftaran__user_farmasi_id=user_id)
        field_kwargs = {'user_farmasi_id': user_id}

    if group_name == "LAB":
        get_layanan = get_layanan.filter(pendaftaran__user_lab_id=user_id)
        field_kwargs = {'user_lab_id': user_id}
    
    get_layanan = get_layanan.annotate(
        total_harga_layanan=(F('tarif_layanan__harga') -  F('tarif_layanan__presentase_dokter_rp')) * ((F('tarif_layanan__presentase_dokter_persen')) / 100) * F('kuantitas'))

    index = 0
    for item in get_layanan:
        index += 1
        tanggal = item.created_at
        row = [
            index,
            tanggal.strftime("%d/%m/%Y"),
            item.pendaftaran.pasien.first_name,
            item.pendaftaran.dokter.first_name,
            item.tarif_layanan.nama,
            item.tarif_layanan.harga,
            item.kuantitas,
            item.total_harga_layanan,
            item.tarif_layanan.presentase_dokter_rp,
            item.tarif_layanan.presentase_dokter_persen,
        ]
        ws.append(row)

    border = Border(left=Side(style='medium'), 
                    right=Side(style='medium'),
                    top=Side(style='medium'),
                    bottom=Side(style='medium'))

    for row in ws.iter_rows(min_row=7, max_row=ws.max_row, min_col=1, max_col=10): #MAX BORDER SAMPE MANA
        for cell in row:
            cell.border = border

    # Set response headers for Excel file download
    response = HttpResponse(content_type='application/ms-excel')
    current_date = datetime.now().strftime('%d_%b_%Y')

    filename = f"laporan_pendapatan_jasmed_{current_date}.xlsx"

    response['Content-Disposition'] = f'attachment; filename="{filename}"'

    # Save the workbook to the response
    wb.save(response)

    return response
    
@login_required
def diagnosa(request):
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()

    context = {
        'menu_items' : menu_items,
    }
    return render(request, 'pemeriksaan/diagnosa.html', context)

@login_required
def chart_diagnosa(request):
    filter_date = request.GET.get('filter_date')
    today = timezone.localtime(timezone.now())

    # Date filtering logic
    if filter_date == 'today':
        start_date = today.replace(hour=0, minute=0, second=0, microsecond=0)
        end_date = today.replace(hour=23, minute=59, second=59, microsecond=999999)

    elif filter_date == 'week':
        start_date = today.replace(hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=today.weekday())
        end_date = start_date + timezone.timedelta(days=6)

    elif filter_date == 'currentmonth':
        start_date = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        _, last_day_of_month = calendar.monthrange(start_date.year, start_date.month)
        end_date = today.replace(day=last_day_of_month, hour=23, minute=59, second=59, microsecond=999999)

    elif filter_date == 'lastmonth':
        end_date = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(days=1)
        start_date = end_date.replace(day=1)

    elif filter_date == 'range':
        start_date = timezone.datetime.strptime(request.GET.get('start_date') + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
        end_date = timezone.datetime.strptime(request.GET.get('end_date') + ' 23:59:59', '%Y-%m-%d %H:%M:%S')

    else:
        start_date = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        end_date = today + timezone.timedelta(days=1)

    # Fetch diagnoses data based on the date range
    pendaftaran = Pendaftaran.objects.filter(created_at__range=[start_date, end_date])

    # Filter diagnoses by the pendaftaran data
    pendaftaran_diagnosa_by_range = pendaftaran.values_list('id', flat=True)
    diagnosa_by_range = InputIcd10.objects.filter(pendaftaran_id__in=pendaftaran_diagnosa_by_range)

    total_diagnosa = diagnosa_by_range.values('icd10__kode').annotate(total=Count('icd10__kode')).order_by('-total')[:5]
    get_diagnosa_list = list(total_diagnosa)

    diagnosa = diagnosa_by_range.order_by('-created_at').values()
    diagnosa = diagnosa.annotate(
        kode_icd10=F('icd10__kode'),
        diagnosa=F('icd10__diagnosa')
    )

    # Prepare the context for the response
    context = {
        'get_diagnosa_list': get_diagnosa_list,
        'total': len(diagnosa),
        'table_diagnosa': list(diagnosa),
        'start_date': start_date.strftime('%Y/%m/%d'),
        'end_date': end_date.strftime('%Y/%m/%d')
    }

    return JsonResponse(context, safe=False)
    
@login_required
def daftarlayanan(request):
    user_groups = request.user.groups.all()

    # GET MENU BY GROUPS #RYDEV
    menu_items = MenuItem.objects.filter(auth_menu_access__group__in=user_groups).order_by('order').distinct()
    context = {
        'menu_items': menu_items,
    }
    return render(request, 'pemeriksaan/layanan/base.html', context)

@login_required
def data_layanan(request):
    layanan = TarifLayanan.objects.all().values()

    return JsonResponse(list(layanan), safe=False)

@login_required
def tambah_layanan(request):
    data = request.POST
    layanan = TarifLayanan.objects.all()
    nama = data.get('nama')
    harga = float(data.get('harga'))
    presentase_dokter_persen = data.get('presentase_dokter_persen')
    presentase_dokter_rp = data.get('presentase_dokter_rp')
    cara_bayar = CaraBayar.objects.get(id=2)  
    kelas = Kelas.objects.get(id=3)
    relasi = SubLayanan.objects.get(id=33)

    tambahLayanan = TarifLayanan(
        nama=nama,
        harga=harga,
        presentase_dokter_persen=presentase_dokter_persen,
        presentase_dokter_rp=presentase_dokter_rp,
        cara_bayar=cara_bayar,
        kelas=kelas,          
        relasi=relasi         
    )
    tambahLayanan.save()

    return redirect('/pemeriksaan/daftarlayanan')

@login_required
def hapus_layanan(request, id):
    layanan = TarifLayanan.objects.get(id=id)
    nama_layanan = layanan.nama
    layanan.delete()
    messages.info(request, f'Layanan "{nama_layanan}" telah dihapus')
    return redirect('/pemeriksaan/daftarlayanan')

@login_required
def get_data_layanan(request, id):
    layanan = TarifLayanan.objects.get(id=id)
    
    data = {
        'id': layanan.id,
        'nama': layanan.nama,
        'harga': layanan.harga,
        'presentase_dokter': layanan.presentase_dokter_persen, # Tambahkan presentase dokter ke dalam data
        'presentase_bhp': layanan.presentase_dokter_rp, # Tambahkan presentase dokter ke dalam data
    }
    
    return JsonResponse(data)

@login_required
def edit_layanan(request, id):
    layanan = TarifLayanan.objects.get(id=id)
    nama = request.POST.get('nama_baru')
    harga = request.POST.get('harga_baru')
    # created_at = timezone.now()
    # presentase_dokter_persen = request.POST.get('presentase_dokter_persen') # Sesuaikan dengan nama yang dikirimkan
    # presentase_dokter_rp = request.POST.get('presentase_dokter_rp') # Sesuaikan dengan nama yang dikirimkan
    presentase_fee = request.POST.get('presentase_fee') # Sesuaikan dengan nama yang dikirimkan
    presentase_bhp = request.POST.get('presentase_bhp') # Sesuaikan dengan nama yang dikirimkan
    created_at = request.POST.get('created_at')
    
    layanan.nama = nama
    layanan.harga = harga
    # layanan.presentase_dokter_persen = presentase_dokter_persen  # Update nilai presentase dokter
    # layanan.presentase_dokter_rp = presentase_dokter_rp  # Update nilai presentase dokter
    layanan.presentase_dokter_persen = presentase_fee  # Update nilai presentase dokter
    layanan.presentase_dokter_rp = presentase_bhp  # Update nilai presentase dokter
    layanan.created_at = created_at
    layanan.save()

    if nama and harga:  # Jangan perlu memeriksa jika nama dan harga tidak kosong
        return JsonResponse({'message': "ok"})
    else:
        return JsonResponse({'message': 'Data Anda Kosong'})

@login_required
def data_layanan_lab(request):
    layanan = TarifLab.objects.all().values()

    return JsonResponse(list(layanan), safe=False)

@login_required
def tambah_layanan_lab(request):
    data = request.POST
    layanan = TarifLab.objects.all()
    nama = data.get('nama')
    harga = float(data.get('harga'))
    presentase_dokter_persen = data.get('presentase_dokter_persen')
    presentase_dokter_rp = data.get('presentase_dokter_rp')
    cara_bayar = CaraBayar.objects.get(id=2)  
    kelas = Kelas.objects.get(id=3)
    # relasi = SubLayanan.objects.get(id=33)

    tambahlayananLab = TarifLab(
        nama=nama,
        harga=harga,
        presentase_dokter_persen=presentase_dokter_persen,
        presentase_dokter_rp=presentase_dokter_rp,
        cara_bayar=cara_bayar,
        kelas=kelas,          
        # relasi=relasi         
    )
    tambahlayananLab.save()

    return redirect('/pemeriksaan/daftarlayanan')

@login_required
def hapus_layanan_lab(request, id):
    layanan = TarifLab.objects.get(id=id)
    nama_layanan = layanan.nama
    layanan.delete()
    messages.info(request, f'Layanan "{nama_layanan}" telah dihapus')
    return redirect('/pemeriksaan/daftarlayanan')

@login_required
def get_data_layanan_lab(request, id):
    layanan = TarifLab.objects.get(id=id)
    
    data = {
        'id': layanan.id,
        'nama': layanan.nama,
        'harga': layanan.harga,
        'presentase_dokter_persen': layanan.presentase_dokter_persen, # Tambahkan presentase dokter ke dalam data
        'presentase_dokter_rp': layanan.presentase_dokter_rp, # Tambahkan presentase dokter ke dalam data
    }
    
    return JsonResponse(data)

@login_required
def edit_layanan_lab(request, id):
    layanan = TarifLab.objects.get(id=id)
    nama = request.POST.get('nama_baru')
    harga = request.POST.get('harga_baru')
    presentase_dokter_persen = request.POST.get('presentase_dokter_persen')
    presentase_dokter_rp = request.POST.get('presentase_dokter_rp')
    layanan.nama = nama
    layanan.harga = harga
    layanan.presentase_dokter_persen = presentase_dokter_persen
    layanan.presentase_dokter_rp = presentase_dokter_rp
    layanan.save()

    if nama != "" and harga != "":
        return JsonResponse({'message':"ok"})
    else:
        return JsonResponse({'message': 'Data anda Kosong'})
             
@login_required
def cek_nik(request):
    norm = request.GET.get('no_rm')
    datanik = request.GET.get('nik')
    pasien_by_norm = Biodata.objects.filter(nomor_rekam_medis__exact=norm)
    # print(pasien_by_norm[0].nama_penandatangan_pasien)
    if pasien_by_norm.exists():
        nama = pasien_by_norm[0].first_name
        norme = pasien_by_norm[0].nomor_rekam_medis
        return JsonResponse({'status': 400, 'nama': nama, 'nomor': norme, 'msg': f'Nomor Rekam Medis ini sudah terdaftar sebelumnya dengan nama {nama}'}, safe=False)  # Respon kembali ke JavaScript
        
    pasien_by_nik = Biodata.objects.filter(nomor_induk_kependudukan__exact=datanik)
    # print(pasien_by_nik[0].nama_penandatangan_pasien)
    if pasien_by_nik.exists():
        nama = pasien_by_nik[0].first_name
        nonik = pasien_by_nik[0].nomor_induk_kependudukan
        return JsonResponse({'status': 400, 'nama': nama, 'nomor': nonik, 'msg': f'Data NIK ini sudah terdaftar sebelumnya dengan nama {nama}'}, safe=False)  # Respon kembali ke JavaScript

    return JsonResponse({'status': 200}, safe=False)
        
@login_required
def cek_data_kepesertaan(request):
    data = request.POST
    no_nik = data.get('no_nik')
    noka_bpjs = data.get('noka_bpjs')
    current_date = timezone.now()
    formatted_date = current_date.strftime('%Y-%m-%d')
    if noka_bpjs is not None and noka_bpjs != '':
        route = 'Peserta/{0}/{1}/tglSEP/{2}'.format('nokartu', noka_bpjs, formatted_date)
        cek_noka = Vclaim(route=route)
        cek_noka.get()
        if cek_noka.data:
            data = cek_noka.data
            result = {}
            result['filter'] = 'nokartu'
            result['nokartu'] = data['peserta']['noKartu']
            result['nik'] = data['peserta']['nik']
            result['nama'] = data['peserta']['nama']
            result['tglLahir'] = data['peserta']['tglLahir']
            return JsonResponse({
                'result': result,
                'code': 200,
                'msg': 'Success!'
            }, safe=False)
        else:
            return JsonResponse({
                'result': {
                    'nomor':data.get('noka_bpjs')
                },
                'code': 404,
                'msg': 'Data Kepesertaan tidak ditemukan!'
            }, safe=False)
    if no_nik is not None and no_nik != '':
        route = 'Peserta/{0}/{1}/tglSEP/{2}'.format('nik', no_nik, formatted_date)
        cek_nik = Vclaim(route=route)
        cek_nik.get()
        if cek_nik.data:
            data = cek_nik.data
            result = {}
            result['filter'] = 'nik'
            result['nokartu'] = data['peserta']['noKartu']
            result['nik'] = data['peserta']['nik']
            result['nama'] = data['peserta']['nama']
            result['tglLahir'] = data['peserta']['tglLahir']
            return JsonResponse({
                'result': result,
                'code': 200,
                'msg': 'Success!'
            }, safe=False)
        else:
            return JsonResponse({
                'result': {
                    'nomor':data.get('no_nik'),
                },
                'code': 404,
                'msg': 'NIK tidak ditemukan!'
            }, safe=False)
            
def export_top_leaderboards(ids, start_date, end_date, ordering):
    wb = Workbook()
    ws = wb.active

    # Define the title
    ws.merge_cells("A1:P1")
    title = "LAPORAN KEUANGAN PASIEN - TOP LEADERBOARD"

    # Set the title in cell A1 with bold font
    title_cell = ws.cell(row=1, column=1, value=title)
    title_cell.alignment = Alignment(horizontal='center', vertical='center')
    title_cell.font = Font(bold=True)

    # Define the subtitle
    ws.merge_cells("A2:P2")
    info_dasar_faskes = InformasiDasarFaskes.objects.first()
    subtitle = info_dasar_faskes.nama

    # Set the subtitle in cell A1 with bold font
    subtitle_cell = ws.cell(row=2, column=1, value=subtitle)
    subtitle_cell.alignment = Alignment(horizontal='center', vertical='center')
    subtitle_cell.font = Font(bold=True)

    # Define the title
    ws.merge_cells("A3:P3")
    alamat = info_dasar_faskes.alamat

    # Set the alamat in cell A1 with bold font
    alamat_cell = ws.cell(row=3, column=1, value=alamat)
    alamat_cell.alignment = Alignment(horizontal='center', vertical='center')

    # Define the email
    ws.merge_cells("A4:P4")
    email = "email: -@aklik.id"

    # Set the email in cell A1 with bold font
    email_cell = ws.cell(row=4, column=1, value=email)
    email_cell.alignment = Alignment(horizontal='center', vertical='center')
    email_font = Font(bold=True, color="0000FF")  # "0000FF" is the code for blue
    email_cell.font = email_font

    # Define the column headers
    column_headers = [
        "No", "Tanggal", "Medrek", "Nama Pasien", "Umur", "JK", "Alamat",
        "No HP", "Diagnosa", "Layanan", "Kuantitas", "Layanan Lab", "Obat", "Harga Obat", "Adm. Pendaftaran", "Tindakan", "Harga Lab", "APD", "TOTAL",
    ]

    # Set the column headers in the worksheet
    for col_num, column_title in enumerate(column_headers, 1):
        cell = ws.cell(row=7, column=col_num, value=column_title)
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        
        col_letter = get_column_letter(col_num)
        max_width = max(len(str(column_title)), 15)  # Minimum width of 10 characters
        ws.column_dimensions[col_letter].width = max_width

        # Merge cells for "JML Pembayaran" and add sub-columns

    faskes_info = InformasiDasarFaskes.objects.first()
    is_paket = faskes_info.is_paket
    dokter = Biodata.objects.filter(groups__name='DOKTER').order_by('poli')
    base_query = PendaftaranViews.objects.filter(pasien_id__in=ids, created_at__range=(start_date, end_date)).order_by(ordering)
    
    row_number = 0
    for row_data in base_query:
        summaryinvoicebarang = 0
        invoicebarang = InvoiceBarang.objects.filter(is_dibayar=1, pendaftaran_id=row_data.id)
        if is_paket == 1:
            try:
                get_harga = HargaListHistory.objects.filter(pendaftaran_id=row_data.id).first()

                if get_harga and hasattr(get_harga.harga_list, 'price'):
                    price = get_harga.harga_list.price
                else:
                    price = 0
            except ObjectDoesNotExist:
                price = 0
            summaryinvoicebarang += price
        else:
            for xbarang in invoicebarang:
                summaryinvoicebarang += (xbarang.barang.harga_jual * xbarang.kuantitas)

        if row_data.is_new_pasien == True:
            fee_pendaftaran = faskes_info.fee_new_pasien
        else:
            fee_pendaftaran = faskes_info.fee_old_pasien 

        summaryinvoicelayanan = 0
        invoicelayanan = InvoiceLayanan.objects.filter(is_dibayar=1, pendaftaran_id=row_data.id)
        for xlayanan in invoicelayanan:
            summaryinvoicelayanan += (xlayanan.tarif_layanan.harga * xlayanan.kuantitas)

        summaryinvoicelab = 0
        invoicelab = InvoiceLab.objects.filter(is_dibayar=1, pendaftaran_id=row_data.id)
        for xlab in invoicelab:
            summaryinvoicelab += (xlab.tarif_lab.harga * xlab.kuantitas)

        row_data.harga_obat = summaryinvoicebarang
        row_data.administrasi_pendaftaran = fee_pendaftaran
        row_data.total_layanan_harga = summaryinvoicelayanan
        row_data.total_lab_harga = summaryinvoicelab
        row_data.apd = 0
        row_data.total = summaryinvoicebarang + summaryinvoicelayanan + summaryinvoicelab + fee_pendaftaran


        # for x in unique_invoicelayanan_list:
        get_layanan = InvoiceLayanan.objects.filter(pendaftaran_id=row_data.id)
        # return JsonResponse(x.id, safe=False)
        get_layanan = get_layanan.annotate(
            harga_layanan=F('tarif_layanan__harga'),
            qty=F('kuantitas')
        )

        get_layanan_lab = InvoiceLab.objects.filter(pendaftaran_id=row_data.id)
        # return JsonResponse(x.id, safe=False)
        get_layanan_lab = get_layanan_lab.values('pendaftaran_id').annotate(
            harga_lab=F('tarif_lab__harga'),
            nama_lab=F('tarif_lab__nama'),
            qty=F('kuantitas')
        )
        list_lab = list(get_layanan_lab)
        nama_lab = ', '.join(map(lambda x: str(x['nama_lab']), list_lab))
            
        getDiagnosa = InputIcd10.objects.filter(pendaftaran_id=row_data.id)
        getDiagnosa = getDiagnosa.annotate(
            diagnosa=F('icd10__diagnosa'),
            kode_diagnosa=F('icd10__kode'),
        )
        diagnosa_list = list(getDiagnosa)
        diagnosa = stringFromArray('diagnosa', diagnosa_list)
        joined_diagnosa = ', '.join(str(diag.kode_diagnosa) for diag in diagnosa_list)  

        invoicebarang = InvoiceBarang.objects.filter(pendaftaran_id=row_data.id)
        invoicebarang = invoicebarang.values('pendaftaran_id').annotate(
            nama_obat=F('barang__nama'),
            harga_barang=F('barang__harga_jual'),
        )
        # Contoh penggunaan langsung tanpa deklarasi fungsi
        list_obat = list(invoicebarang)
        nama_obat = ', '.join(map(lambda x: str(x['nama_obat']), list_obat))


        created_at_string = row_data.created_at.replace(tzinfo=None)
        tanggal= created_at_string.strftime('%y-%m-%d')

        check_id = set()
        # number = 0
        if len(get_layanan) > 0:
            for push_layanan in get_layanan:
                pendaftaran_id = push_layanan.pendaftaran_id
                
                if pendaftaran_id in check_id:
                    perlayanan = push_layanan.harga_layanan - push_layanan.tarif_layanan.presentase_dokter_rp
                    row = [
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        push_layanan.tarif_layanan.nama,
                        '',
                        '',
                        '',
                        '',
                        '',
                        perlayanan,
                        '',
                        push_layanan.tarif_layanan.presentase_dokter_rp,
                        '',
                    ]
                    ws.append(row)
                else:
                    check_id.add(push_layanan.pendaftaran_id)
                    perlayanan = push_layanan.harga_layanan - push_layanan.tarif_layanan.presentase_dokter_rp
                    row_number += 1
                    row = [
                        row_number,
                        tanggal,
                        row_data.nomor_rekam_medis,
                        row_data.nama_pasien,
                        checkUsia(row_data.tanggal_lahir),
                        row_data.jenis_kelamin,
                        row_data.alamat,
                        '',
                        joined_diagnosa,
                        push_layanan.tarif_layanan.nama,
                        push_layanan.qty,
                        nama_lab,
                        nama_obat,
                        row_data.harga_obat,
                        row_data.administrasi_pendaftaran,
                        perlayanan,
                        row_data.total_lab_harga,
                        push_layanan.tarif_layanan.presentase_dokter_rp,
                        row_data.total,
                    ]
                    ws.append(row)
        else:
            row_number += 1
            row = [
                row_number,
                tanggal,
                row_data.nomor_rekam_medis,
                row_data.nama_pasien,
                checkUsia(row_data.tanggal_lahir),
                row_data.jenis_kelamin,
                row_data.alamat,
                '',
                joined_diagnosa,
                '',
                '',
                nama_lab,
                nama_obat,
                row_data.harga_obat,
                row_data.administrasi_pendaftaran,
                '',
                row_data.total_lab_harga,
                '',
                row_data.total,
            ]
            ws.append(row)
    
    border = Border(left=Side(style='thin'), 
                    right=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thin')
                    )

    for row in ws.iter_rows(min_row=7, max_row=ws.max_row, min_col=1, max_col=ws.max_column):
        for cell in row:
            cell.border = border

    # Set response headers for Excel file download
    response = HttpResponse(content_type='application/ms-excel')
    tanggal_dibuat = datetime.now()
    response['Content-Disposition'] = f'attachment; filename="laporan-keuangan{tanggal_dibuat}.xlsx"'

    # Save the workbook to the response
    wb.save(response)

    return response
    
@login_required
def import_obat(request):
    file_name = 'obat.xlsx'
    file_path = os.path.join('templates', 'import', 'excel', file_name)

    df = pd.read_excel(file_path, usecols=[3, 4], skiprows=4)

    data_list = df.values.tolist()

    barang_list = []

    n = 0
    for item in data_list:
        nama_obat = item[0]
        harga_obat = item[1]

        if not pd.isna(nama_obat):
            n += 1
            barang = Barang(
                kode=f"A{n}",
                nama=nama_obat,
                harga_jual=harga_obat,
                satuan=1,
                stok=100,
                expired_at='2024-01-01 00:00:00',
                created_at='2024-01-01 00:00:00',
                cara_jual_id=1, 
                jenis_barang_id=1, 
                kategori_barang_id=1, 
                lokasi_id=1
            )
            barang_list.append(barang)

    # Bulk insert all Barang objects into the database
    Barang.objects.bulk_create(barang_list)

    return JsonResponse('Berhasil', safe=False)

@login_required
def import_layanan(request):
    file_name = 'tindakan.xlsx'
    file_path = os.path.join('templates', 'import', 'excel', file_name)

    df = pd.read_excel(file_path, usecols=[2, 3], skiprows=2)

    data_list = df.values.tolist()

    barang_list = []

    n = 0
    for item in data_list:
        nama_layanan = item[0]
        harga_layanan = item[1]

        if not pd.isna(nama_layanan):
            n += 1
            barang = TarifLayanan(
                nama = nama_layanan,
                harga = harga_layanan,
                catatan = '',
                created_at = '2024-06-04 00:00:00',
                cara_bayar_id = 2,
                kelas_id = 5,
                relasi_id = 33,
                presentase_dokter_persen = 30,
                presentase_dokter_rp = 0,
            )
            barang_list.append(barang)

    # Bulk insert all Barang objects into the database
    TarifLayanan.objects.bulk_create(barang_list)

    return JsonResponse('Berhasil', safe=False)

# @login_required
# def import_lab(request):
#     file_name = 'tarif-Lab.xlsx'
#     file_path = os.path.join('templates', 'import', 'excel', file_name)

#     df = pd.read_excel(file_path, usecols=[1, 2, 3], skiprows=2)

#     data_list = df.values.tolist()

#     lab_list = []

#     n = 0
#     for item in data_list:
#         nama_lab = item[0]
#         harga_lab = item[1]
#         fee_dokter = item[2]

#         if not pd.isna(nama_lab):
#             n += 1
#             lab = TarifLab(
#                 nama = nama_lab,
#                 harga = harga_lab,
#                 catatan = '',
#                 created_at = '2024-03-01 00:00:00',
#                 cara_bayar_id = 2,
#                 kelas_id = 5,
#                 relasi_id = 33,
#                 presentase_dokter_persen = fee_dokter,
#                 presentase_dokter_rp = 0,
#             )
#             lab_list.append(lab)

#     # Bulk insert all Barang objects into the database
#     TarifLab.objects.bulk_create(lab_list)

#     return JsonResponse('Berhasil', safe=False)

@login_required
def change_gender(request):
    file_name = 'template-migrasi-data-pasien-pkbi-garut.xlsx'
    file_path = os.path.join('templates', 'import', 'excel', file_name)
    
    df = pd.read_excel(file_path, usecols=range(0, 22), skiprows=6)  # Adjusted to read columns 1 to 21
    if not df.empty:
        data_list = df.values.tolist()  # Convert DataFrame to a list of lists
        for item in data_list:  # Iterate through each item in the data list
            row = {
                'nomor_induk_kependudukan': item[0] if not pd.isna(item[0]) else '',
                'nomor_kartu_bpjs': item[1] if not pd.isna(item[1]) else '',
                'first_name': item[2] if not pd.isna(item[2]) else '',
                'tanggal_lahir': item[3].strftime('%Y-%m-%d') if not pd.isna(item[3]) and isinstance(item[3], datetime) else '1999-09-09',
                'pekerjaan': item[4] if not pd.isna(item[4]) else '',
                'jenis_kelamin': item[5] if not pd.isna(item[5]) else '',
                'alamat': item[6] if not pd.isna(item[6]) else '',
                'kontak': item[7] if not pd.isna(item[7]) else '',
                'tgl_kunjungan': item[8].strftime('%Y-%m-%d') if not pd.isna(item[8]) and isinstance(item[8], datetime) else '',
                'keluhan': item[9] if not pd.isna(item[9]) else '',
                'tensi': item[10] if not pd.isna(item[10]) else '',
                'berat_badan': item[11] if not pd.isna(item[11]) else '',
                'tinggi_badan': item[12] if not pd.isna(item[12]) else '',
                'status_pasien': item[13] if not pd.isna(item[13]) else '',
                'kunjungan_poli': item[14] if not pd.isna(item[14]) else '',
                'layanan': item[15] if not pd.isna(item[15]) else '',
                'dokter': item[16] if not pd.isna(item[16]) else '',
                'jenis_tindakan': item[17] if not pd.isna(item[17]) else '',
                'icd10_primer': item[18] if not pd.isna(item[18]) else '',
                'diagnosa_primer': item[19] if not pd.isna(item[19]) else '',
                'icd10_sekunder': item[20] if not pd.isna(item[20]) else '',
                'diagnosa_sekunder': item[21] if not pd.isna(item[21]) else '',
            }
            
            if not isinstance(row['jenis_kelamin'], int):
                # check_alpa = re.sub(r'[^a-zA-Z0-9]', '', row['jenis_kelamin'])
                try:
                    jenis_kelamin = 'male' if row['jenis_kelamin'] == 'Male' else 'female'
                except IndexError:
                    jenis_kelamin = 'male'
            else:
                jenis_kelamin = 'male'

            pasien = Biodata.objects.filter(first_name__exact=row['first_name'], tanggal_lahir=row['tanggal_lahir']).first()
            pasien.jenis_kelamin = jenis_kelamin
            pasien.save()
            print(f'Berhasil : {row["first_name"]}')
            
    print('Data imported successfully.')
    
@login_required
def biodata_pasien(request, id):
    biodata = Biodata.objects.get(user_ptr_id=id)
    data = {
        'norm': biodata.nomor_rekam_medis,
        'first_name': biodata.first_name,
        'nomor_induk_kependudukan': biodata.nomor_induk_kependudukan,
        'alamat': biodata.alamat,
        'kontak': biodata.kontak,
        'pekerjaan': biodata.pekerjaan,
        'email': biodata.email,
        'tanggal_lahir': biodata.tanggal_lahir,
        'tempat_lahir': biodata.tempat_lahir,
    }
    return JsonResponse(data)

@login_required
def update_biodata(request, id):
    biodata = Biodata.objects.get(user_ptr_id=id,nomor_rekam_medis=request.POST.get('norm'))
    biodata.nomor_rekam_medis = request.POST.get('norm')
    biodata.first_name = request.POST.get('first_name')
    biodata.nomor_induk_kependudukan = request.POST.get('nomor_induk_kependudukan')
    biodata.alamat = request.POST.get('alamat')
    biodata.kontak = request.POST.get('kontak')
    biodata.pekerjaan = request.POST.get('pekerjaan')
    biodata.email = request.POST.get('email')
    biodata.tanggal_lahir = request.POST.get('tanggal_lahir')
    biodata.tempat_lahir = request.POST.get('tempat_lahir')
    biodata.save()

    return JsonResponse({'status': 'success', 'message': 'Biodata updated successfully'})
    
class DaftarPasienListView(ServerSideDatatableView):
    queryset = PemeriksaanPendaftaranViews.objects.filter(status__in=['arrived', 'progress', 'selesai'])
    columns = ['id', 'nomor_rekam_medis', 'nama_pasien', 'alamat', 'tanggal_lahir', 'created_at']