
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

# Create your views here.
from datetime import timedelta

from django.shortcuts import render
from django.utils import timezone

from otentifikasi.models import MenuItem
from penjualan.models import InvBarang, InvoiceBarang, Barang, HargaList, HargaListHistory
from pemeriksaan.models import Pendaftaran

# 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
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
import time
import json
from pembayaran.models import CekPembayaran
from faskes.models import InformasiDasarFaskes
# Create your views here.

@login_required
def laporan_obat(request):

    # 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()

    # keseluruhan
    daftar_pasien = Pendaftaran.objects.filter(status='selesai')
    now = timezone.now()

    # bulan ini
    objects_this_month = Pendaftaran.objects.filter(created_at__month=now.month, created_at__year=now.year, status='selesai')

    # Untuk bulan sebelumnya
    first_day_of_month = now - timedelta(days=now.day - 1)
    last_month_end = first_day_of_month - timedelta(days=1)
    objects_last_month = Pendaftaran.objects.filter(created_at__month=last_month_end.month,created_at__year=last_month_end.year)
    
    # stok_obat_terjual = []
    # paket = []
    # totalPaket = []
    bulan_ini = []
    bulan_lalu = []

    # for i in daftar_pasien:
    #     invLay = InvoiceLayanan.objects.filter(pendaftaran=i, progress='progress')
    #     for a in invLay:
    #         # print(a.tarif_layanan_id)
    #         tarif = TarifLayanan.objects.filter(id=a.tarif_layanan_id)
    #         for i in tarif:
    #             total.append(i.harga)
    # print(sum(total))
        # # print(invoicebarangs)
        # for s in invoicebarangs:
        #     stok_obat_terjual.append(s.kuantitas)
        # count = len(invoicebarangs)
    
        # if count <= 1:
        #     # paket.append("-")
        #     totalPaket.append(0)
        # elif count > 3:
        #     # paket.append("Paket 2")
        #     totalPaket.append(100000)

        # else:
        #     # paket.append("Paket 1")
        #     totalPaket.append(50000)

    
    faskes_info = InformasiDasarFaskes.objects.first()
    is_paket = faskes_info.is_paket
    # pengecekan bulan kemarin
    for a in objects_last_month:
        invoicebarang = InvoiceBarang.objects.filter(pendaftaran=a.id, is_dibayar=1)
        count = len(invoicebarang)
    
        if is_paket == 1 or is_paket != False:
            if count <= 1:
                bulan_lalu.append(0)
            elif count > 3:
                bulan_lalu.append(100000)
            else:
                bulan_lalu.append(50000)
        else:
            for x in invoicebarang:
                bulan_lalu.append(x.barang.harga_jual * x.kuantitas)

    # pengecekan bulan ini
    for b in objects_this_month:
        invoicebarang = InvoiceBarang.objects.filter(pendaftaran=b.id, is_dibayar=1)
        count = len(invoicebarang)
    
        if is_paket == 1 or is_paket != False:
            if count <= 1:
                bulan_ini.append(0)
            elif count > 3:
                bulan_ini.append(100000)
            else:
                bulan_ini.append(50000)
        else:
            for x in invoicebarang:
                bulan_ini.append(x.barang.harga_jual * x.kuantitas)
    

    
    # filter by bulan ini
    invs = InvBarang.objects.filter(progress='progress')
    barangs=[]
    for inv in invs:
        barang = Barang.objects.filter(id=inv.barang_id)
        barangs.extend(barang)

    total_kuantitas = sum(inv.kuantitas for inv in invs)
        
    # filter by bulan sebelumnnya
    invs = zip(invs, barangs)
    # perubahan = sum(bulan_ini) - sum(bulan_lalu)
    # persentase_perubahan = (perubahan / sum(bulan_lalu)) * 100
    context = {
           "menu_items": menu_items,
           "pendapatan" : sum(bulan_lalu),
           "bulan_ini" : sum(bulan_ini),
           "persentase_perubahan": 0, # persentase di pendapatan bulan ini
           "last_month_end":last_month_end,
           "kuantitas":total_kuantitas,
           "invs": invs,
           }
    
    return render(request, 'penjualan/laporan-penjualan-obat.html', context)
    
@login_required
def change_package(request, id_pendaftaran):
    id_paket_custom = request.POST.get('id');
    if not HargaListHistory.objects.filter(pendaftaran_id=id_pendaftaran).exists():
        harga_list_history = HargaListHistory(
                                        pendaftaran_id=id_pendaftaran,
                                        harga_list=HargaList.objects.get(id=id_paket_custom)
                                        )
        harga_list_history.save()
    else:
        harga_list_history = HargaListHistory.objects.get(pendaftaran_id=id_pendaftaran)
        harga_list_history.harga_list=HargaList.objects.get(id=id_paket_custom)
        harga_list_history.save()
        
    return JsonResponse({'msg': 'Updated Succesfully', 'price': harga_list_history.harga_list.price}, safe=False)
    
@login_required
def add_ref_obat(request):
    if request.method == 'POST':
        nama = request.POST.get('nama_paket')
        harga = request.POST.get('harga')

        harga_list = HargaList(
            title=nama,  # assuming 'title' corresponds to 'nama_paket'
            price=harga  # assuming 'price' corresponds to 'harga'
        )

        # Save the instance to the database
        harga_list.save()
        
        return JsonResponse({'message': "ok"})
    else:
        return JsonResponse({'error': "Invalid request"}, status=400)
        
@login_required
def get_ref_obat(request, packid):
    data = HargaList.objects.get(id=packid)
    json = {
        'id':data.id,
        'title':data.title,
        'price':data.price,
        'created_at':data.created_at,
    }
    return JsonResponse(json, safe=False)
    
@login_required
def edit_ref_obat(request, packid):
    data_update = HargaList.objects.get(id=packid)
    data_update.title = request.POST.get('nama_paket')
    data_update.price = request.POST.get('harga')
    data_update.save()
    
    return JsonResponse({'status': 'Berhasil'}, safe=False)
    
@login_required
def rm_ref_obat(request, packid):
    data_delete = HargaList.objects.get(id=packid)
    data_delete.delete()
    
    return JsonResponse({'status': 'Berhasil'}, safe=False)
