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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>In Tem Nhãn Hàng Hóa</title>
    <link rel="shortcut icon" href="1.png" type="image/x-icon">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.2/axios.min.js"></script>
    <!-- Thêm thư viện JsBarcode để tạo mã vạch -->
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    <style>
        /* Chế độ xem trước trên màn hình */
        @media screen {
            #printContent {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
                gap: 1rem;
                padding: 1rem;
                margin-left: 20rem;
                padding-top: 4rem;
                /* Thêm padding phía trên để tránh che nút in */
            }

            .preview-label {
                /* Đổi tên class cho xem trước */
                background: white;
                border-radius: 0.5rem;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
                padding: 1.5rem;
                transition: all 0.2s;
            }
        }

        /* Chế độ in */
        @media print {
            @page {
                size: 100mm 32.5mm;
                margin: 0;
            }

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


            .no-print {
                display: none !important;
            }

            #printContent {
                display: grid;
                grid-template-columns: repeat(2, 50mm);
                width: 100mm;
                margin: 0 !important;
            }

            .print-label {
                width: 50mm;
                height: 32.5mm;
                padding: 4mm;
                box-sizing: border-box;
                page-break-inside: avoid;
            }

            .label-content {
                height: 100%;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
            }

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

            .label-barcode {
                text-align: center;
            }

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

        #loadingOverlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .custom-scrollbar::-webkit-scrollbar {
            width: 4px;
        }

        .custom-scrollbar::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 10px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #666;
        }



        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
    </style>
</head>

<body class="bg-gray-100">
    <div id="loadingOverlay" class="hidden">
        <div class="spinner"></div>
        <div class="text-white mt-4">Đang xử lý...</div>
    </div>

    <div class="no-print fixed top-0 left-0 w-80 h-full bg-white shadow-lg flex flex-col">
        <div class="p-2">
            <h2 class="text-xl font-bold">In Tem Nhãn Hàng Hóa</h2>
        </div>

        <div class="p-2 border-b">
            <div class="relative mb-4">
                <input type="text" id="searchInput" placeholder="Tìm kiếm hàng hóa..."
                    class="w-full p-2 pl-8 border rounded bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                <svg class="w-4 h-4 absolute left-2 top-3 text-gray-400" fill="none" stroke="currentColor"
                    viewBox="0 0 24 24">
                    <path d="M21 21l-6-6m2-6a7 7 0 11-14 0 7 7 0 0114 0z" stroke-linecap="round" stroke-linejoin="round"
                        stroke-width="2" />
                </svg>
            </div>

            <div class="mb-4">
                <div id="tagFilters" class="flex flex-wrap gap-2">
                </div>
            </div>

            <div class="flex gap-2">
                <button onclick="selectAllProducts()"
                    class="flex-1 p-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors">
                    <span>Chọn tất cả</span>
                </button>
                <button onclick="unselectAllProducts()"
                    class="flex-1 p-2 bg-gray-500 text-white rounded hover:bg-gray-600 transition-colors">
                    <span>Bỏ chọn tất cả</span>
                </button>
            </div>
        </div>

        <div class="flex-1 overflow-auto p-2 bg-gray-50">
            <div id="productList" class="space-y-2">
            </div>
        </div>

        <div class="p-2 border-t bg-white">
            <div id="selectedCount" class="text-center font-medium text-gray-700">
                Đã chọn: 0
            </div>
        </div>
    </div>

    <!-- Thay đổi phần nút in -->
    <div class="no-print fixed top-4 right-4 flex gap-2" style="z-index: 1000;">
        <button onclick="window.print()"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg shadow hover:bg-blue-600 transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                    d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"
                    stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />
            </svg>
            <span>In Tem Đã Chọn</span>
        </button>
    </div>

    <div id="printContent" class="print-content ml-80">
    </div>
    <script src="key.js"></script>
    <script>
        let allData = {
            products: []
        };

        let selectedTags = new Set();
     
        const apiService = {
            createAxiosInstance() {
                return axios.create({
                    baseURL: `${API_CONFIG.BASE_URL}/${API_CONFIG.APP_ID}/tables`,
                    headers: {
                        'ApplicationAccessKey': API_CONFIG.ACCESS_KEY,
                        'Content-Type': 'application/json'
                    }
                });
            },

            async request(tableName, action, data = {}, select = {}) {
                const api = this.createAxiosInstance();
                const response = await api.post(`/${tableName}/Action`, {
                    Action: action,
                    Properties: select,
                    ...data
                });
                return response.data;
            }
        };

        function showLoading() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        }

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

        let allProducts = [];
        let selectedProducts = new Set();

        function updateSelectedCount() {
            const count = selectedProducts.size;
            document.getElementById('selectedCount').innerHTML = `
                <div class="flex items-center justify-center gap-2">
                    <span class="text-gray-600">Đã chọn:</span>
                    <span class="font-bold text-blue-500">${count}</span>
                    <span class="text-gray-600">sản phẩm</span>
                </div>
            `;
        }

        function selectAllProducts() {
            allProducts.forEach(product => {
                selectedProducts.add(product.Masp);
                const checkbox = document.querySelector(`input[data-id="${product.Masp}"]`);
                if (checkbox) checkbox.checked = true;
            });
            updateSelectedCount();
            renderSelectedProducts();
        }

        function unselectAllProducts() {
            selectedProducts.clear();
            document.querySelectorAll('#productList input[type="checkbox"]')
                .forEach(checkbox => checkbox.checked = false);
            updateSelectedCount();
            renderSelectedProducts();
        }

        function toggleProduct(id, checked) {
            if (checked) {
                selectedProducts.add(id);
            } else {
                selectedProducts.delete(id);
            }
            updateSelectedCount();
            renderSelectedProducts();
        }

        async function renderProductLabel(product) {
            return `
        <div class="max-w-[10cm] mx-auto bg-white p-4 mb-4 page-break">
            <div class="text-center mb-3">
                <h2 class="text-lg font-bold">${product["Tensp"]}</h2>
            </div>

            <div class="text-center mb-3">
                <svg id="barcode-${product.Masp}"></svg>
                <div class="text-xs mt-1">${product.Masp}</div>
            </div>

            <div class="text-center mt-2">
                <p class="text-xl font-bold">${Number(product.Giaban).toLocaleString('vi-VN')} VNĐ</p>
            </div>
        </div>
    `;
        }
        async function renderSelectedProducts() {
            if (selectedProducts.size === 0) {
                document.getElementById('printContent').innerHTML = `
        <div class="p-8 text-center text-gray-500">
            <p class="text-lg font-medium">Chưa có sản phẩm nào được chọn</p>
        </div>`;
                return;
            }

            const selectedProductsList = allData.products.filter(p => selectedProducts.has(p.Masp));
            const printContent = document.getElementById('printContent');
            printContent.innerHTML = '';

            selectedProductsList.forEach((product, index) => {
                const labelDiv = document.createElement('div');
                labelDiv.className = 'print-label';

                const price = product["Giaban"] ? parseFloat(product["Giaban"]) : 1;
                const formattedPrice = price === 1 ? "1 VNĐ" : price.toLocaleString('vi-VN') + ' VNĐ';

                labelDiv.innerHTML = `
            <div class="label-content">
                <div class="label-title">${product["Tensp"]}</div>
                <div class="label-barcode">
                    <svg id="barcode-${index}"></svg>
                </div>
                <div class="label-price">${formattedPrice} / ${product["Dvtinh"]}</div>
            </div>
        `;

                printContent.appendChild(labelDiv);

                JsBarcode(`#barcode-${index}`, product.Masp, {
                    format: "CODE128",
                    width: 1.3,
                    height: 40,
                    displayValue: true,
                    fontSize: 8,
                    marginTop: 5,
                    marginBottom: 5
                });
            });
        }
        function renderProductList(productList) {
            const listHTML = productList
                .map(product => `
        <div class="bg-white rounded-lg shadow-sm hover:shadow-md transition-all duration-200 border border-gray-100">
            <label class="flex items-center gap-4 p-1 cursor-pointer">
                <div class="flex-shrink-0">
                    <input type="checkbox" 
                           class="w-5 h-5 text-blue-600 rounded border-gray-300 focus:ring-blue-500 cursor-pointer"
                           data-id="${product.Masp}"
                           ${selectedProducts.has(product.Masp) ? 'checked' : ''}
                           onchange="toggleProduct('${product.Masp}', this.checked)">
                </div>
                <div class="flex-1">
                    <div class="flex items-center justify-between">
                        <span class="font-semibold text-gray-800">${product["Tensp"]}</span>
                        <span class="px-2.5 py-1 text-xs font-medium rounded-full bg-blue-50 text-blue-700">
                            ${product["Nhomsp"]}
                        </span>
                    </div>
                   
                    <div class="mt-2 text-sm font-medium text-gray-900">
                        ${Number(product["Giaban"]).toLocaleString('vi-VN')} VNĐ 
                    </div>
                </div>
            </label>
        </div>
    `)
                .join('');

            document.getElementById('productList').innerHTML = listHTML || `
        <div class="flex flex-col items-center justify-center py-12 text-gray-500">
            <svg class="w-16 h-16 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p class="text-lg font-medium">Không tìm thấy sản phẩm nào</p>
        </div>
    `;
        }

        function renderTagFilters(tags) {
            const tagsWithCount = tags.map(tag => {
                const count = allData.products.filter(p => p["Nhomsp"] === tag).length;
                return { tag, count };
            });

            const headerHTML = `
        <div class="flex items-center justify-between mb-2">
            <h3 class="text-xs font-medium text-gray-700">Loại hàng hóa</h3>
            ${selectedTags.size > 0 ? `
                <button 
                    onclick="clearAllTags()"
                    class="text-xs text-blue-600 hover:text-blue-800"
                >
                    Bỏ chọn
                </button>
            ` : ''}
        </div>
    `;

            const tagsHTML = tagsWithCount.map(({ tag, count }) => `
        <button 
            class="px-2 py-1 rounded text-xs font-medium
                flex items-center gap-1.5 transition-colors 
                ${selectedTags.has(tag)
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }"
            onclick="toggleTag('${tag}')"
        >
            <span class="truncate max-w-[100px]">${tag}</span>
            <span class="shrink-0 inline-flex items-center px-1.5 
                rounded text-xs
                ${selectedTags.has(tag)
                    ? 'bg-blue-400 text-white'
                    : 'bg-white text-gray-600'
                }">${count}</span>
        </button>
    `).join('');

            document.getElementById('tagFilters').innerHTML = `
        ${headerHTML}
        <div class="flex flex-wrap gap-1.5 max-h-24 overflow-y-auto pr-1 -mr-1">
            ${tagsHTML}
        </div>
    `;
        }

        function clearAllTags() {
            selectedTags.clear();
            renderTagFilters([...new Set(allData.products.map(p => p["Nhomsp"]))]);
            filterAndRenderProductList();
        }

        function toggleTag(tag) {
            if (selectedTags.has(tag)) {
                selectedTags.delete(tag);
            } else {
                selectedTags.add(tag);
            }
            renderTagFilters([...new Set(allData.products.map(p => p["Nhomsp"]))]);
            filterAndRenderProductList();
        }

        function filterAndRenderProductList() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();

            const filteredProducts = allData.products.filter(product => {
                const matchesSearch =
                    product["Tensp"].toLowerCase().includes(searchTerm) ||
                    product["Mô tả"]?.toLowerCase().includes(searchTerm) ||
                    product.Masp.toLowerCase().includes(searchTerm);

                const matchesTags = selectedTags.size === 0 || selectedTags.has(product["Nhomsp"]);

                return matchesSearch && matchesTags;
            });

            renderProductList(filteredProducts);
        }

        function setupSearch() {
            const searchInput = document.getElementById('searchInput');
            searchInput.addEventListener('input', filterAndRenderProductList);
        }

        async function initializeApp() {
            try {
                showLoading();
                const products = await apiService.request('DMHH', 'Find', {}, {
                    Selector: 'Filter(DMHH, true)'
                });

                if (!products || products.length === 0) {
                    alert('Không có hàng hóa nào');
                    return;
                }

                // Store all data
                allData = {
                    products: products.sort((a, b) => a["Tensp"].localeCompare(b["Tensp"]))
                };

                // Get unique tags
                const uniqueTags = [...new Set(allData.products.map(p => p["Nhomsp"]))];
                renderTagFilters(uniqueTags);

                // Initialize display
                allProducts = allData.products;
                renderProductList(allProducts);
                setupSearch();
            } catch (error) {
                console.error('Error initializing app:', error);
                alert('Có lỗi xảy ra khi tải dữ liệu');
            } finally {
                hideLoading();
            }
        }

        // Initialize when document is ready
        document.addEventListener('DOMContentLoaded', initializeApp);
    </script>
</body>

</html>