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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>In Nhiều Phiếu Nhập Xuất Kho</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>
    <script src="key.js"></script>
    <style>
        @media print {
            @page {
                size: A4 portrait;
                margin: 0.5cm;
            }

            body {
                margin: 0;
                padding: 0;
            }

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

            .page-break {
                page-break-after: always;
            }

            .print-content {
                margin: 0 !important;
                padding: 0 !important;
                width: 100% !important;
                max-width: 100% !important;
            }

            #printContent {
                margin-left: 0 !important;
            }

            /* Reset margin for print template */
            #printContent>div {
                margin: 0 auto !important;
                max-width: none !important;
                box-shadow: none !important;
            }
        }

        /* Loading overlay styles */
        #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;
        }

        @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">
        <!-- Header -->
        <div class="p-4 ">
            <h2 class="text-xl font-bold">In Phiếu Nhập Xuất Kho</h2>
        </div>

        <!-- Search and Filters -->
        <div class="p-4 border-b">
            <div class="relative mb-4">
                <input type="text" id="searchInput" placeholder="Tìm kiếm phiếu..."
                    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>

            <!-- Tag Filters with counts -->
            <div class="mb-4">
                <h3 class="text-sm font-medium text-gray-700 mb-2">Loại phiếu</h3>
                <div id="tagFilters" class="flex flex-wrap gap-2">
                    <!-- Tags will be populated here -->
                </div>
            </div>

            <!-- Action buttons -->
            <div class="flex gap-2">
                <button onclick="selectAllPhieu()"
                    class="flex-1 px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors">
                    <span>Chọn tất cả</span>
                </button>
                <button onclick="unselectAllPhieu()"
                    class="flex-1 px-3 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 transition-colors">
                    <span>Bỏ chọn tất cả</span>
                </button>
            </div>
        </div>

        <!-- Phiếu List -->
        <div class="flex-1 overflow-auto p-4 bg-gray-50">
            <div id="phieuList" class="space-y-2">
                <!-- Phiếu list will be populated here -->
            </div>
        </div>

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

    <!-- Action Buttons -->
    <div class="no-print fixed top-4 right-4 flex gap-2">
        <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 Phiếu Đã Chọn</span>
        </button>
    </div>

    <!-- Print Content -->
    <!-- Print Content -->
    <div id="printContent" class="print-content">
        <!-- Phiếu templates will be populated here -->
    </div>
    <script>
        let allData = {
            phieu: [],
            details: [],
            warehouses: [],
            products: []
        };

        let selectedTags = new Set(); // Lưu các tag đang được chọn
        const API_CONFIG = {
            APP_ID: 'e483be4d-1b20-4805-8bcf-c01013ee853b',
            ACCESS_KEY: 'V2-PelHU-a4w3r-2mlpo-wI0XW-nZvbo-Y5sLF-XoEn4-wf3Ym',
            BASE_URL: 'https://www.appsheet.com/api/v2/apps'
        };

        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 allPhieu = [];
        let selectedPhieu = new Set();

        function updateSelectedCount() {
            const count = selectedPhieu.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">phiếu</span>
        </div>
    `;
        }
        function selectAllPhieu() {
            allPhieu.forEach(phieu => {
                selectedPhieu.add(phieu.IDPHIEUNXT);
                const checkbox = document.querySelector(`input[data-id="${phieu.IDPHIEUNXT}"]`);
                if (checkbox) checkbox.checked = true;
            });
            updateSelectedCount();
            renderSelectedPhieu();
        }

        function unselectAllPhieu() {
            selectedPhieu.clear();
            document.querySelectorAll('#phieuList input[type="checkbox"]')
                .forEach(checkbox => checkbox.checked = false);
            updateSelectedCount();
            renderSelectedPhieu();
        }

        function togglePhieu(id, checked) {
            if (checked) {
                selectedPhieu.add(id);
            } else {
                selectedPhieu.delete(id);
            }
            updateSelectedCount();
            renderSelectedPhieu();
        }

        async function renderPhieuTemplate(phieu, details, warehouses, products) {
            const isNhap = phieu['LOẠI PHIẾU'].toLowerCase().includes('nhập');
            const khoXuat = warehouses.find(w => w['MÃ KHO'] === phieu['ĐƠN VỊ XUẤT']);
            const khoNhan = warehouses.find(w => w['MÃ KHO'] === phieu['ĐƠN VỊ NHẬN']);

            let totalAmount = 0;
            const detailsHTML = details
                .filter(d => d.IDPHIEUNXT === phieu.IDPHIEUNXT)
                .map((detail, index) => {
                    const product = products.find(p => p['MÃ HÀNG'] === detail['MÃ HÀNG']);
                    const quantity = parseFloat(detail['SỐ LƯỢNG']);
                    const price = isNhap ? parseFloat(detail['ĐƠN GIÁ NHẬP']) : parseFloat(detail['ĐƠN GIÁ XUẤT']);
                    const amount = quantity * price;
                    totalAmount += amount;

                    return `
                <tr>
                    <td class="border p-2 text-center">${index + 1}</td>
                    <td class="border p-2">${product ? product['TÊN HÀNG'] : detail['MÃ HÀNG']}</td>
                    <td class="border p-2 text-center">${quantity.toLocaleString('vi-VN')}</td>
                    <td class="border p-2 text-center">${detail['ĐƠN VỊ TÍNH']}</td>
                    <td class="border p-2 text-right">${price.toLocaleString('vi-VN')}</td>
                    <td class="border p-2 text-right">${amount.toLocaleString('vi-VN')}</td>
                    <td class="border p-2">${detail['GHI CHÚ'] || ''}</td>
                </tr>
            `;
                }).join('');

            return `
        <div class="max-w-[21cm] mx-auto bg-white p-8 shadow-lg mb-8 page-break">
            <!-- Header -->
            <div class="grid grid-cols-12 gap-4 mb-8">
                <div class="col-span-2 flex items-start gap-4">
                    <img src="1.png" alt="Company Logo" class="w-20 h-auto object-contain">
                </div>
                <div class="col-span-8 center">
                    <div class="flex flex-col text-center justify-center">
                        <h2 class="font-bold text-xl">TÊN CÔNG TY</h2>
                        <p class="text-sm">MST: MÃ SỐ THUẾ</p>
                        <p class="text-sm">Địa chỉ: ĐỊA CHỈ CÔNG TY</p>
                        <p class="text-sm">Hotline: 0326132124</p>
                        <p class="text-sm">Email: ninhphuoc@phuocnv.io.vn</p>
                    </div>
                </div>
                <div class="col-span-2 text-right">
                    <p class="text-sm mb-2">Mẫu số: 01-HĐGT</p>
                    <p class="text-sm mb-2">Ký hiệu: PO/22E</p>
                    <p>Số: ${phieu['SỐ CHỨNG TỪ']}</p>
                </div>
            </div>

            <!-- Title -->
            <div class="text-center mb-4">
                <h1 class="text-xl font-bold">PHIẾU ${phieu['LOẠI PHIẾU'].toUpperCase()}</h1>
                <p class="text-sm">${new Date(phieu['THỜI GIAN']).toLocaleString('vi-VN')}</p>
            </div>

            <!-- Info -->
            <div class="grid grid-cols-2 gap-4 mb-4 text-sm">
                <div>
                    <p><span class="inline-block w-32">Số chứng từ:</span> ${phieu['SỐ CHỨNG TỪ']}</p>
                    <p><span class="inline-block w-32">Đơn vị xuất:</span> ${khoXuat ? khoXuat['TÊN KHO'] : phieu['ĐƠN VỊ XUẤT']}</p>
                    <p><span class="inline-block w-32">Đơn vị nhận:</span> ${khoNhan ? khoNhan['TÊN KHO'] : phieu['ĐƠN VỊ NHẬN']}</p>
                </div>
                <div>
                    <p><span class="inline-block w-32">Thời gian:</span> ${new Date(phieu['THỜI GIAN']).toLocaleString('vi-VN')}</p>
                    <p><span class="inline-block w-32">Người tạo:</span> ${phieu['NGƯỜI TẠO']}</p>
                    <p><span class="inline-block w-32">Bộ phận:</span> Phòng kho vận</p>
                </div>
            </div>

            <!-- Notes -->
            <div class="mb-4 text-sm">
                <p><span class="inline-block w-32">Diễn giải:</span> ${phieu['DIỄN GIẢI'] || ''}</p>
                <p><span class="inline-block w-32">Ghi chú:</span> ${phieu['GHI CHÚ'] || ''}</p>
            </div>

            <!-- Table -->
            <table class="w-full border border-gray-200 text-sm mb-4">
                <thead>
                    <tr class="bg-gray-50">
                        <th class="border p-1">STT</th>
                        <th class="border p-1">Tên Hàng</th>
                        <th class="border p-1">Số Lượng</th>
                        <th class="border p-1">ĐVT</th>
                        <th class="border p-1">Đơn Giá</th>
                        <th class="border p-1">Thành Tiền</th>
                        <th class="border p-1">Ghi Chú</th>
                    </tr>
                </thead>
                <tbody>
                    ${detailsHTML}
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5" class="border p-1 text-right font-bold">Tổng cộng:</td>
                        <td class="border p-1 text-right font-bold">${totalAmount.toLocaleString('vi-VN')}</td>
                        <td class="border p-1"></td>
                    </tr>
                </tfoot>
            </table>

            <!-- Signatures -->
            <div class="grid grid-cols-3 gap-4 text-center text-sm mt-8">
                <div>
                    <p class="font-bold">Người lập phiếu</p>
                    <p class="text-xs">(Ký, họ tên)</p>
                    <div class="h-20"></div>
                    <p>${phieu['NGƯỜI TẠO']}</p>
                </div>
                <div>
                    <p class="font-bold">Người nhận hàng</p>
                    <p class="text-xs">(Ký, họ tên)</p>
                    <div class="h-20"></div>
                    <p>Người nhận hàng</p>
                </div>
                <div>
                    <p class="font-bold">Thủ kho</p>
                    <p class="text-xs">(Ký, họ tên)</p>
                    <div class="h-20"></div>
                    <p>Thủ kho</p>
                </div>
            </div>
        </div>
    `;
        }

        async function renderSelectedPhieu() {
            if (selectedPhieu.size === 0) {
                document.getElementById('printContent').innerHTML =
                    '<div class="p-8 text-center text-gray-500">Chưa có phiếu nào được chọn</div>';
                return;
            }

            const selectedPhieuList = allData.phieu.filter(p => selectedPhieu.has(p.IDPHIEUNXT));
            const content = await Promise.all(
                selectedPhieuList.map(phieu =>
                    renderPhieuTemplate(
                        phieu,
                        allData.details,
                        allData.warehouses,
                        allData.products
                    )
                )
            );

            document.getElementById('printContent').innerHTML = content.join('');
        }
        function renderPhieuList(phieuList) {
            const listHTML = phieuList
                .map(phieu => `
            <div class="bg-white rounded-lg shadow-sm hover:shadow transition-shadow">
                <label class="flex items-center gap-3 p-3 cursor-pointer">
                    <input type="checkbox" 
                           class="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                           data-id="${phieu.IDPHIEUNXT}"
                           ${selectedPhieu.has(phieu.IDPHIEUNXT) ? 'checked' : ''}
                           onchange="togglePhieu('${phieu.IDPHIEUNXT}', this.checked)">
                    <div class="flex-1">
                        <div class="flex items-center gap-2">
                            <span class="font-medium">${phieu['SỐ CHỨNG TỪ']}</span>
                            <span class="px-2 py-0.5 text-xs rounded-full ${phieu['LOẠI PHIẾU'].toLowerCase().includes('nhập')
                        ? 'bg-green-100 text-green-800'
                        : 'bg-blue-100 text-blue-800'
                    }">${phieu['LOẠI PHIẾU']}</span>
                        </div>
                        <div class="text-sm text-gray-500 mt-1">
                            ${new Date(phieu['THỜI GIAN']).toLocaleString('vi-VN')}
                        </div>
                    </div>
                </label>
            </div>
        `)
                .join('');

            document.getElementById('phieuList').innerHTML = listHTML || `
        <div class="text-center text-gray-500 py-8">
            Không tìm thấy phiếu nào
        </div>
    `;
        }

        function setupSearch() {
            const searchInput = document.getElementById('searchInput');
            searchInput.addEventListener('input', (e) => {
                const searchTerm = e.target.value.toLowerCase();
                const filteredPhieu = allPhieu.filter(phieu =>
                    phieu['SỐ CHỨNG TỪ'].toLowerCase().includes(searchTerm) ||
                    phieu['LOẠI PHIẾU'].toLowerCase().includes(searchTerm) ||
                    new Date(phieu['THỜI GIAN']).toLocaleDateString('vi-VN').includes(searchTerm)
                );
                renderPhieuList(filteredPhieu);
            });
        }

        async function initializeApp() {
            try {
                showLoading();
                // Fetch all data concurrently
                const [phieuList, details, warehouses, products] = await Promise.all([
                    apiService.request('PHIEUNXT', 'Find', {}, {
                        Selector: 'Filter(PHIEUNXT, true)'
                    }),
                    apiService.request('PHIEUNXTDE', 'Find', {}, {
                        Selector: 'Filter(PHIEUNXTDE, true)'
                    }),
                    apiService.request('KHO', 'Find', {}, {
                        Selector: 'Filter(KHO, true)'
                    }),
                    apiService.request('DMHH', 'Find', {}, {
                        Selector: 'Filter(DMHH, true)'
                    })
                ]);

                if (!phieuList || phieuList.length === 0) {
                    alert('Không có phiếu nào');
                    return;
                }

                // Store all data
                allData = {
                    phieu: phieuList.sort((a, b) => new Date(b['THỜI GIAN']) - new Date(a['THỜI GIAN'])),
                    details: details,
                    warehouses: warehouses,
                    products: products
                };

                // Get unique tags
                const uniqueTags = [...new Set(allData.phieu.map(p => p['LOẠI PHIẾU']))];
                renderTagFilters(uniqueTags);

                // Initialize display
                allPhieu = allData.phieu;
                renderPhieuList(allPhieu);
                setupSearch();
            } catch (error) {
                console.error('Error initializing app:', error);
                alert('Có lỗi xảy ra khi tải dữ liệu');
            } finally {
                hideLoading();
            }
        }
        function renderTagFilters(tags) {
            const tagsWithCount = tags.map(tag => {
                const count = allData.phieu.filter(p => p['LOẠI PHIẾU'] === tag).length;
                return { tag, count };
            });

            const tagsHTML = tagsWithCount.map(({ tag, count }) => `
        <button 
            class="px-3 py-1.5 rounded-lg text-sm flex items-center gap-2 transition-colors ${selectedTags.has(tag)
                    ? 'bg-blue-500 text-white'
                    : 'bg-white text-gray-700 hover:bg-gray-100 border'
                }"
            onclick="toggleTag('${tag}')"
        >
            <span>${tag}</span>
            <span class="px-1.5 py-0.5 rounded-full text-xs ${selectedTags.has(tag)
                    ? 'bg-blue-400'
                    : 'bg-gray-100'
                }">${count}</span>
        </button>
    `).join('');

            document.getElementById('tagFilters').innerHTML = tagsHTML;
        }
        function toggleTag(tag) {
            if (selectedTags.has(tag)) {
                selectedTags.delete(tag);
            } else {
                selectedTags.add(tag);
            }

            // Re-render tags and filter list
            renderTagFilters([...new Set(allData.phieu.map(p => p['LOẠI PHIẾU']))]);
            filterAndRenderPhieuList();
        }
        function filterAndRenderPhieuList() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();

            const filteredPhieu = allData.phieu.filter(phieu => {
                const matchesSearch =
                    phieu['SỐ CHỨNG TỪ'].toLowerCase().includes(searchTerm) ||
                    phieu['LOẠI PHIẾU'].toLowerCase().includes(searchTerm) ||
                    new Date(phieu['THỜI GIAN']).toLocaleDateString('vi-VN').includes(searchTerm);

                const matchesTags = selectedTags.size === 0 || selectedTags.has(phieu['LOẠI PHIẾU']);

                return matchesSearch && matchesTags;
            });

            renderPhieuList(filteredPhieu);
        }

        function setupSearch() {
            const searchInput = document.getElementById('searchInput');
            searchInput.addEventListener('input', filterAndRenderPhieuList);
        }
        // Initialize when document is ready
        document.addEventListener('DOMContentLoaded', initializeApp);
    </script>
</body>

</html>