<!DOCTYPE html>
<html lang="vi">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quản lý và In nhãn DMHH</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.0/dist/JsBarcode.all.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="key.js"></script>
    <style>
       

       body {
            background-color: #f8f9fa;
            font-family: Arial, sans-serif;
        }
        .card {
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .table-container {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .btn-primary {
            background-color: #0d6efd;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
        }
        #printArea {
            display: none;
        }

        @media print {
            @page {
                size: 100mm 32.5mm;
                margin: 0;
            }

            body {
                margin: 0;
                padding: 0;
                width: 100mm;
            }

            #printArea {
                display: flex;
                flex-wrap: wrap;
            }

            .print-label {
                width: 50mm;
                height: 32.5mm;
                page-break-after: always;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                box-sizing: border-box;
                padding: 2mm;
            }

            .label-title {
                font-size: 13px;
                font-weight: bold;
                text-align: center;
            }

            .label-barcode {
                text-align: center;
                height: 15mm;
            }

            .label-barcode svg {
                max-width: 100%;
                height: 100%;
            }

            .label-price {
                font-size: 16px;
                font-weight: bold;
                text-align: center;
            }

            .container,
            #loading,
            #error,
            #dataTable_wrapper {
                display: none !important;
            }
        }
    </style>
</head>

<body class="">
    <div id="dataTable_wrapper" class="mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <h1 class="text-3xl font-bold text-center text-gray-900 mb-8">Quản lý và In nhãn DMHH</h1>

        <!-- Filter Section -->
        <div class="mb-8 space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Category Filter -->
                <div class="bg-white p-6 rounded-lg shadow">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">Lọc theo phân loại</h3>
                    <div id="categoryTags" class="flex flex-wrap gap-2"></div>
                </div>

                <!-- Unit Filter -->
                <div class="bg-white p-6 rounded-lg shadow">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">Lọc theo đơn vị tính</h3>
                    <div id="unitTags" class="flex flex-wrap gap-2"></div>
                </div>
            </div>

            <!-- Active Filters -->
            <div class="bg-white p-6 rounded-lg shadow">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Bộ lọc đang áp dụng</h3>
                <div id="activeFilters" class="flex flex-wrap gap-2"></div>
            </div>
        </div>

        <!-- Loading State -->
        <div id="loading" class="text-center py-8">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-gray-200 border-t-blue-600">
            </div>
            <p class="mt-2 text-gray-600">Đang tải dữ liệu...</p>
        </div>

        <!-- Error Message -->
        <div id="error" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative"
            role="alert">
        </div>

        <!-- Print Button -->
        <button id="printSelectedBtn"
            class="hidden mb-4 bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">
            In các mục đã chọn
        </button>

        <!-- Data Table -->
        <div class="overflow-x-auto">
            <table id="dataTable" class="w-full table-auto hidden">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" id="selectAll" class="rounded border-gray-300">
                        </th>
                        <th>STT</th>
                        <th>MÃ HÀNG</th>
                        <th>TÊN HÀNG</th>
                        <th>HÌNH ẢNH</th>
                        <th>ĐƠN VỊ TÍNH</th>
                        <th>PHÂN LOẠI</th>
                        <th>QUY CÁCH</th>
                        <th>GHI CHÚ</th>
                        <th>ĐƠN GIÁ NHẬP</th>
                        <th>ĐƠN GIÁ XUẤT</th>
                        <th>MÃ VẠCH</th>
                    </tr>
                </thead>
                <tbody id="tableBody"></tbody>
            </table>
        </div>
    </div>

    <div id="printArea"></div>

    <script>
        const APP_ID  = 'e483be4d-1b20-4805-8bcf-c01013ee853b'
         const   ACCESS_KEY  = 'V2-PelHU-a4w3r-2mlpo-wI0XW-nZvbo-Y5sLF-XoEn4-wf3Ym'
            const   REGION  = 'www'
        const API_URL = `https://${REGION}.appsheet.com/api/v2/apps/${APP_ID}/tables`;

        let activeFilters = {
            categories: new Set(),
            units: new Set()
        };

        function apiRequest(tableName, action, data) {
            const apiUrl = `${API_URL}/${tableName}/Action`;
            return $.ajax({
                url: apiUrl,
                method: 'POST',
                headers: {
                    'ApplicationAccessKey': ACCESS_KEY,
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify({
                    Action: action,
                    Properties: {
                        Locale: 'vi-VN',
                        Timezone: 'Asia/Ho_Chi_Minh'
                    },
                    ...data
                })
            });
        }

        function initializeFilters(data) {
            const categories = new Set();
            const units = new Set();

            data.forEach(item => {
                if (item['PHÂN LOẠI']) categories.add(item['PHÂN LOẠI']);
                if (item['ĐƠN VỊ TÍNH']) units.add(item['ĐƠN VỊ TÍNH']);
            });

            renderFilterTags('categoryTags', Array.from(categories), 'category');
            renderFilterTags('unitTags', Array.from(units), 'unit');
        }

        function renderFilterTags(containerId, items, type) {
            const container = document.getElementById(containerId);
            container.innerHTML = '';

            items.forEach(item => {
                const tag = document.createElement('button');
                const isActive = type === 'category' ?
                    activeFilters.categories.has(item) :
                    activeFilters.units.has(item);

                tag.className = `px-3 py-1 rounded-full text-sm font-medium transition-colors duration-200 ${isActive ?
                        'bg-blue-500 text-white hover:bg-blue-600' :
                        'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`;
                tag.textContent = item;

                tag.onclick = () => toggleFilter(item, type);
                container.appendChild(tag);
            });

            updateActiveFilters();
        }

        function toggleFilter(value, type) {
            const filterSet = type === 'category' ? activeFilters.categories : activeFilters.units;

            if (filterSet.has(value)) {
                filterSet.delete(value);
            } else {
                filterSet.add(value);
            }

            applyFilters();
            updateActiveFilters();
        }

        function updateActiveFilters() {
            const container = document.getElementById('activeFilters');
            container.innerHTML = '';

            if (activeFilters.categories.size === 0 && activeFilters.units.size === 0) {
                container.innerHTML = '<span class="text-gray-500">Chưa có bộ lọc nào được áp dụng</span>';
                return;
            }

            [...activeFilters.categories].forEach(category => {
                addActiveFilterTag(container, category, 'category');
            });

            [...activeFilters.units].forEach(unit => {
                addActiveFilterTag(container, unit, 'unit');
            });
        }

        function addActiveFilterTag(container, value, type) {
            const tag = document.createElement('div');
            tag.className = 'inline-flex items-center bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm';
            tag.innerHTML = `
                ${value}
                <button class="ml-2 text-blue-600 hover:text-blue-800 focus:outline-none" onclick="toggleFilter('${value}', '${type}')">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            `;
            container.appendChild(tag);
        }

        function applyFilters() {
            const table = $('#dataTable').DataTable();

            $.fn.dataTable.ext.search.push(function (settings, data) {
                const category = data[6]; // Index of PHÂN LOẠI column
                const unit = data[5];     // Index of ĐƠN VỊ TÍNH column

                const categoryMatch = activeFilters.categories.size === 0 ||
                    activeFilters.categories.has(category);
                const unitMatch = activeFilters.units.size === 0 ||
                    activeFilters.units.has(unit);

                return categoryMatch && unitMatch;
            });

            table.draw();

            // Remove the custom filter after drawing
            $.fn.dataTable.ext.search.pop();
        }

        function loadData() {
            showLoading();
            apiRequest('DMHH', 'Find', { Rows: [], Properties: { Selector: 'Filter(DMHH, true)' } })
                .then(data => {
                    processData(data);
                    hideLoading();
                })
                .catch(error => {
                    console.error('Lỗi khi tải dữ liệu:', error);
                    showError('Có lỗi xảy ra khi tải dữ liệu. Vui lòng thử lại sau.');
                    hideLoading();
                });
        }

        function processData(data) {
            const tableBody = document.getElementById('tableBody');
            tableBody.innerHTML = '';

            const filteredData = data.filter(item => item['MÃ HÀNG']);

            filteredData.sort((a, b) => {
                const aStt = parseInt(a._RowNumber) || 0;
                const bStt = parseInt(b._RowNumber) || 0;
                return aStt - bStt;
            });

            filteredData.forEach((item, index) => {
                const row = tableBody.insertRow();

                // Checkbox cell
                const cellCheckbox = row.insertCell();
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'row-checkbox rounded border-gray-300';
                cellCheckbox.appendChild(checkbox);

                // Data cells
                row.insertCell().textContent = item._RowNumber || (index + 1);
                row.insertCell().textContent = item['MÃ HÀNG'];
                row.insertCell().textContent = item['TÊN HÀNG'];

                // Image cell
                const cellHinhAnh = row.insertCell();
                if (item['HÌNH ẢNH']) {
                    const img = document.createElement('img');
                    img.src = item['HÌNH ẢNH'];
                    img.className = 'w-12 h-12 object-cover rounded';
                    cellHinhAnh.appendChild(img);
                }

                row.insertCell().textContent = item['ĐƠN VỊ TÍNH'];
                row.insertCell().textContent = item['PHÂN LOẠI'];
                row.insertCell().textContent = item['Quy cách'];
                row.insertCell().textContent = item['Ghi chú'];
                row.insertCell().textContent = formatPrice(item['ĐƠN GIÁ NHẬP']);
                row.insertCell().textContent = formatPrice(item['ĐƠN GIÁ XUẤT']);

                // Barcode cell
                const cellBarcode = row.insertCell();
                const barcodeCanvas = document.createElement('canvas');
                cellBarcode.appendChild(barcodeCanvas);
                JsBarcode(barcodeCanvas, item['MÃ HÀNG'], {
                    format: "CODE128",
                    width: 1,
                    height: 30,
                    displayValue: true
                });
            });

            // Initialize DataTable with enhanced configuration
            const dataTable = $('#dataTable').DataTable({
                language: {
                    url: 'https://cdn.datatables.net/plug-ins/1.11.5/i18n/vi.json'
                },
                columnDefs: [
                    { orderable: false, targets: [0, 4] },
                    { type: 'num', targets: 1 }
                ],
                order: [[1, 'asc']],
                pageLength: 10,
                lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, "Tất cả"]],
                responsive: true,
                dom: '<"flex flex-col md:flex-row justify-between items-center mb-4"<"flex-1"l><"flex-1"f>>rtip',
                initComplete: function () {
                    // Initialize filters after DataTable is created
                    initializeFilters(filteredData);
                }
            });

            document.getElementById('dataTable').style.display = 'table';
            document.getElementById('printSelectedBtn').style.display = 'inline-block';
        }

        function printSelectedLabels() {
            const printArea = document.getElementById('printArea');
            printArea.innerHTML = '';

            const selectedItems = [];
            document.querySelectorAll('.row-checkbox:checked').forEach(checkbox => {
                const row = checkbox.closest('tr');
                const IDSP = row.cells[2].textContent;
                const tenSanPham = row.cells[3].textContent;
                const donGia = row.cells[10].textContent;
                selectedItems.push({ IDSP, tenSanPham, donGia });
            });

            selectedItems.forEach((item, index) => {
                const printLabel = document.createElement('div');
                printLabel.className = 'print-label';
                printLabel.innerHTML = `
                    <div class="label-title">${item.tenSanPham}</div>
                    <div class="label-barcode">
                        <svg id="barcode_${index}"></svg>
                    </div>
                    <div class="label-price">${item.donGia}</div>
                `;

                printArea.appendChild(printLabel);

                JsBarcode(`#barcode_${index}`, item.IDSP, {
                    format: "CODE128",
                    width: 2,
                    height: 40,
                    displayValue: true,
                    fontSize: 8,
                    marginTop: 5,
                    marginBottom: 5
                });
            });

            setTimeout(() => {
                window.print();
            }, 1000);
        }

        function formatPrice(price) {
            let numericPrice = parseFloat(price);
            if (isNaN(numericPrice)) {
                return "Giá không hợp lệ";
            }
            numericPrice = numericPrice.toFixed(0);
            return numericPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " VNĐ";
        }

        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('error').style.display = 'none';
            document.getElementById('dataTable').style.display = 'none';
            document.getElementById('printSelectedBtn').style.display = 'none';
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }

        function showError(message) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }

        // Initialize everything when the page loads
        window.onload = () => {
            loadData();

            // Print button event listener
            document.getElementById('printSelectedBtn').addEventListener('click', () => {
                const selectedCount = document.querySelectorAll('.row-checkbox:checked').length;

                if (selectedCount === 0) {
                    alert('Vui lòng chọn ít nhất một nhãn để in.');
                    return;
                }

                if (selectedCount > 25) {
                    const confirmPrint = confirm(
                        `Bạn đã chọn ${selectedCount} nhãn. Việc in số lượng lớn có thể mất nhiều thời gian. Bạn có muốn tiếp tục không?`
                    );
                    if (!confirmPrint) return;
                }

                printSelectedLabels();
            });

            // Select all checkbox event listener
            document.getElementById('selectAll').addEventListener('change', function () {
                const isChecked = this.checked;
                document.querySelectorAll('.row-checkbox').forEach(checkbox => {
                    checkbox.checked = isChecked;
                });
            });
        };
    </script>
</body>

</html>