from django.shortcuts import render
from .models import Category, Product
from django.http import FileResponse, Http404
from django.conf import settings
import os
from django.contrib.admin.views.decorators import staff_member_required
import openpyxl
from django.http import HttpResponse
from openpyxl import Workbook
from django.utils.translation import gettext_lazy as _

# Create your views here.
def category_list(request):
    categories = Category.objects.all()
    return render(request, 'category.html', {'categories': categories})

def download_template(modeladmin, request, queryset):
    print("Aksi download template dipanggil")
    wb = Workbook()
    ws = wb.active
    ws.title = "Template"
    
    # Menambahkan header ke template Excel
    headers = ['Name', 'Description']  # Gantilah dengan nama field model yang relevan
    ws.append(headers)
    
    # Menyediakan response untuk mengunduh file Excel
    response = HttpResponse(content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response['Content-Disposition'] = 'attachment; filename=product_template.xlsx'
    
    # Menyimpan file Excel ke response
    wb.save(response)
    return response

download_template.short_description = "Unduh Template Excel"  # Nama aksi yang ditampilkan di admin

def product_excel_template(request):
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = "Template Produk"

    # Header dengan gaya
    headers = [
        "product_number", "supplier", "name", "qty", 
        "unit", "price", "description", "category"
    ]
    for col_num, header in enumerate(headers, 1):
        cell = sheet.cell(row=1, column=col_num, value=header)
        cell.font = openpyxl.styles.Font(bold=True)
        cell.fill = openpyxl.styles.PatternFill(
            start_color="DDDDDD", 
            end_color="DDDDDD", 
            fill_type="solid"
        )

    # Contoh validasi/dropdown untuk field tertentu
    # Misalnya untuk unit
    units_validation = openpyxl.worksheet.datavalidation.DataValidation(
        type="list", 
        formula1='"Pcs,Kg,Meter,Box"'
    )
    sheet.add_data_validation(units_validation)
    units_validation.add(f'E2:E{sheet.max_row}')

    # Set lebar kolom
    for col in sheet.columns:
        max_length = 0
        column = col[0].column_letter
        for cell in col:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(cell.value)
            except:
                pass
        adjusted_width = (max_length + 2)
        sheet.column_dimensions[column].width = adjusted_width

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    response['Content-Disposition'] = 'attachment; filename="Product_Template.xlsx"'
    workbook.save(response)
    return response

@staff_member_required
def download_template_product(request):
    try:
        app_template_path = os.path.join(settings.BASE_DIR, 'categories', 'static', 'templates', 'product_import.xlsx')
        
        if os.path.exists(app_template_path):
            template_path = app_template_path
        else:
            raise Http404("Template file tidak ditemukan")
            
        return FileResponse(
            open(template_path, 'rb'),
            as_attachment=True,
            filename='product_import.xlsx'
        )
    except Exception as e:
        raise Http404(f"Error saat mengunduh template: {str(e)}")
    
@staff_member_required
def download_template_employee(request):
    try:
        app_template_path = os.path.join(settings.BASE_DIR, 'management', 'static', 'templates', 'employee_import.xlsx')
        
        if os.path.exists(app_template_path):
            template_path = app_template_path
        else:
            raise Http404("Template file tidak ditemukan")
            
        return FileResponse(
            open(template_path, 'rb'),
            as_attachment=True,
            filename='employee_import.xlsx'
        )
    except Exception as e:
        raise Http404(f"Error saat mengunduh template: {str(e)}")
    
@staff_member_required
def download_template_supplier(request):
    try:
        app_template_path = os.path.join(settings.BASE_DIR, 'management', 'static', 'templates', 'supplier_import.xlsx')
        
        if os.path.exists(app_template_path):
            template_path = app_template_path
        else:
            raise Http404("Template file tidak ditemukan")
            
        return FileResponse(
            open(template_path, 'rb'),
            as_attachment=True,
            filename='supplier_import.xlsx'
        )
    except Exception as e:
        raise Http404(f"Error saat mengunduh template: {str(e)}")

@staff_member_required
def download_template_customer(request):
    try:
        app_template_path = os.path.join(settings.BASE_DIR, 'management', 'static', 'templates', 'customer_import.xlsx')
        
        if os.path.exists(app_template_path):
            template_path = app_template_path
        else:
            raise Http404("Template file tidak ditemukan")
            
        return FileResponse(
            open(template_path, 'rb'),
            as_attachment=True,
            filename='customer_import.xlsx'
        )
    except Exception as e:
        raise Http404(f"Error saat mengunduh template: {str(e)}")
#def product_list(request):
#    products = Product.objects.select_related('category').all()  # Menggunakan select_related untuk efisiensi
#    return render(request, 'product.html', {'products': products})