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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tra cứu Mã số thuế</title>
    <link rel="shortcut icon" href="logo.png" type="image/x-icon">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2563EB',
                        secondary: '#1E40AF',
                        accent: '#60A5FA'
                    }
                }
            }
        }
    </script>
</head>

<body class="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
    <div class=" mx-auto px-4 py-8">
        <div class="flex flex-col items-left ">
            <!-- Logo và Tiêu đề -->
            <div class="flex flex-row items-left gap-4">
                <img src="logo.png" width="100" alt="Logo" class="h-20 w-auto">
                <div class="text-left">
                    <h1 class="text-3xl font-bold text-gray-800">Tra cứu Mã số thuế</h1>
                    <p class="text-gray-600 mt-2">Công cụ tra cứu thông tin doanh nghiệp qua mã số thuế</p>
                </div>
            </div>
        </div>

        <div class="flex gap-8">
            <!-- Left side: Input Forms -->
            <div class="w-1/4 space-y-8">
                <!-- Import Excel Card -->
                <div
                    class="bg-white rounded-xl shadow-lg p-8 transform transition duration-300 hover:shadow-xl sticky top-8">
                    <div class="flex items-center mb-6">
                        <div class="rounded-full bg-blue-100 p-3 mr-4">
                            <svg class="w-6 h-6 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                        </div>
                        <h3 class="text-xl font-semibold text-gray-800">Import từ Excel</h3>
                    </div>
                    <div class="space-y-4">
                        <div class="relative">
                            <input type="file" id="fileInput" accept=".xlsx,.xls" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2.5 file:px-4
                                file:rounded-full file:border-0 file:text-sm file:font-semibold
                                file:bg-primary file:text-white hover:file:bg-secondary
                                transition duration-300 cursor-pointer">
                        </div>
                        <button onclick="processExcel()" class="w-full bg-primary text-white py-3 px-6 rounded-full hover:bg-secondary
                            transition duration-300 flex items-center justify-center space-x-2">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                            </svg>
                            <span>Import Excel</span>
                        </button>
                        <a href="tracuumst.xlsx" class="block text-center bg-blue-50 text-primary py-3 px-6 rounded-full
                            hover:bg-blue-100 transition duration-300">
                            Tải file mẫu
                        </a>
                    </div>
                </div>

                <!-- Direct Input Card -->
                <div
                    class="bg-white rounded-xl shadow-lg p-8 transform transition duration-300 hover:shadow-xl sticky top-96">
                    <div class="flex items-center mb-6">
                        <div class="rounded-full bg-green-100 p-3 mr-4">
                            <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                        </div>
                        <h3 class="text-xl font-semibold text-gray-800">Nhập MST trực tiếp</h3>
                    </div>
                    <div class="space-y-4">
                        <textarea id="mstInput" class="w-full h-40 px-4 py-3 text-gray-700 border rounded-xl focus:outline-none 
                            focus:ring-2 focus:ring-primary resize-none"
                            placeholder="Nhập các MST, mỗi MST một dòng"></textarea>
                        <button onclick="processMST()" class="w-full bg-green-600 text-white py-3 px-6 rounded-full hover:bg-green-700
                            transition duration-300 flex items-center justify-center space-x-2">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                            </svg>
                            <span>Tra cứu MST</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Right side: Results Table -->
            <div class="w-3/4">
                <!-- Progress bar -->
                <div id="progressContainer" class="hidden mb-4 bg-white rounded-xl shadow-lg p-4">
                    <div class="flex justify-between mb-2">
                        <span class="text-sm font-medium text-gray-700" id="progressText">0%</span>
                        <span class="text-sm font-medium text-gray-700" id="progressCount">0/0</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div id="progressBar" class="bg-primary h-2 rounded-full transition-all duration-300"
                            style="width: 0%"></div>
                    </div>
                </div>

                <!-- Loading indicator -->
                <div id="loading" class="hidden mb-4">
                    <div class="flex justify-center items-center p-4 bg-white rounded-xl shadow-lg">
                        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
                        <span class="ml-2 text-gray-600">Đang xử lý...</span>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                    <div class="max-h-screen overflow-auto">
                        <table id="resultTable" class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50 sticky top-0 z-10">
                                <tr>
                                    <th scope="col"
                                        class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        MST
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Tên công ty
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Tên quốc tế
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Tên viết tắt
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Địa chỉ
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Trạng thái
                                    </th>
                                    <!-- Các cột khác tương tự -->
                                </tr>
                            </thead>
                            <tbody id="resultBody" class="bg-white divide-y divide-gray-200"></tbody>
                            <tfoot class="bg-gray-50 sticky bottom-0 z-10">
                                <tr>
                                    <td colspan="6" class="px-6 py-4">
                                        <div class="flex justify-between items-center">
                                            <span class="text-sm text-gray-500">Tổng số kết quả: <span
                                                    id="totalResults">0</span></span>
                                            <div class="flex space-x-4">
                                                <button onclick="exportToExcel()" class="bg-primary text-white py-2 px-4 rounded-full hover:bg-secondary
                                                    transition duration-300 flex items-center space-x-2">
                                                    <svg class="w-5 h-5" fill="none" stroke="currentColor"
                                                        viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                            stroke-width="2"
                                                            d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                                    </svg>
                                                    <span>Xuất Excel</span>
                                                </button>
                                                <button onclick="clearResults()" class="bg-red-500 text-white py-2 px-4 rounded-full hover:bg-red-600
                                                    transition duration-300 flex items-center space-x-2">
                                                    <svg class="w-5 h-5" fill="none" stroke="currentColor"
                                                        viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                            stroke-width="2"
                                                            d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                    </svg>
                                                    <span>Xóa kết quả</span>
                                                </button>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>
<script>
    // Cấu hình toast message
    const toastConfig = {
        duration: 3000,
        gravity: "top",
        position: "right",
        stopOnFocus: true,
        className: "rounded-lg shadow-lg",
        style: {
            padding: '1rem',
            fontSize: '0.875rem'
        }
    };

    // Hiển thị toast message
    function showToast(message, type = 'success') {
        const backgroundColor = type === 'success' ? '#059669' : '#DC2626';
        Toastify({
            ...toastConfig,
            text: message,
            backgroundColor,
        }).showToast();
    }
    function updateTotalResults() {
        const totalResults = document.getElementById('resultBody').children.length;
        document.getElementById('totalResults').textContent = totalResults;
    }
    // Cập nhật thanh tiến trình
    function updateProgress(current, total) {
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const progressText = document.getElementById('progressText');
        const progressCount = document.getElementById('progressCount');

        if (!progressContainer || !progressBar || !progressText || !progressCount) {
            console.warn('Progress elements not found');
            return;
        }

        progressContainer.classList.remove('hidden');
        const percentage = Math.round((current / total) * 100);
        progressBar.style.width = `${percentage}%`;
        progressText.textContent = `${percentage}%`;
        progressCount.textContent = `${current}/${total}`;

        if (current === total) {
            setTimeout(() => {
                progressContainer.classList.add('hidden');
                progressBar.style.width = '0%';
            }, 1500);
        }
    }
    // Kiểm tra MST hợp lệ
    function isValidMST(mst) {
        return /^\d{10}(\-\d{3})?$/.test(mst.trim());
    }

    // Tạo row HTML cho kết quả
    function createResultRow(data, mst, error = null) {
        const tr = document.createElement('tr');
        tr.className = 'hover:bg-gray-50 transition-colors duration-200';

        if (error) {
            tr.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${mst}</td>
            <td colspan="5" class="px-6 py-4 text-sm text-red-500">
                <div class="flex items-center">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    ${error}
                </div>
            </td>
        `;
        } else {
            tr.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${data.id || ''}</td>
            <td class="px-6 py-4 text-sm text-gray-900">${data.name || ''}</td>
            <td class="px-6 py-4 text-sm text-gray-900">${data.internationalName || ''}</td>
            <td class="px-6 py-4 text-sm text-gray-900">${data.shortName || ''}</td>
            <td class="px-6 py-4 text-sm text-gray-900">${data.address || ''}</td>
            <td class="px-6 py-4 text-sm ${data.status ? 'text-green-600' : 'text-gray-600'}">
                <div class="flex items-center">
                    <span class="w-2 h-2 rounded-full ${data.status ? 'bg-green-500' : 'bg-gray-500'} mr-2"></span>
                    ${data.desc || ''}
                </div>
            </td>
        `;
        }
        return tr;
    }

    // Tìm kiếm MST
    async function searchMST(mst) {
        try {
            if (!isValidMST(mst)) {
                return createResultRow(null, mst, 'Mã số thuế không hợp lệ');
            }

            const response = await axios.get(`https://api.vietqr.io/v2/business/${mst}`, {
                timeout: 10000
            });

            if (response.data.code === '00') {
                return createResultRow(response.data.data, mst);
            } else {
                return createResultRow(null, mst, 'Không tìm thấy thông tin');
            }
        } catch (error) {
            const errorMessage = error.response?.data?.message || 'Lỗi khi tra cứu';
            return createResultRow(null, mst, errorMessage);
        }
    }

    // Xử lý MST nhập trực tiếp
    async function processMST() {
        const mstInput = document.getElementById('mstInput');
        const loading = document.getElementById('loading');
        const resultBody = document.getElementById('resultBody');

        const mstList = mstInput.value
            .split('\n')
            .map(mst => mst.trim())
            .filter(mst => mst);

        if (!mstList.length) {
            showToast('Vui lòng nhập ít nhất một MST', 'error');
            return;
        }

        loading?.classList.remove('hidden');
        resultBody.innerHTML = '';
        let processed = 0;

        try {
            const batchSize = 5;
            for (let i = 0; i < mstList.length; i += batchSize) {
                const batch = mstList.slice(i, i + batchSize);
                const results = await Promise.all(batch.map(mst => searchMST(mst)));
                results.forEach(tr => resultBody.appendChild(tr));
                processed += batch.length;
                updateProgress(processed, mstList.length);
                updateTotalResults();
                if (i + batchSize < mstList.length) {
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
            }
            showToast(`Đã tra cứu ${processed} MST thành công!`);
        } catch (error) {
            console.error('Error processing MST:', error);
            showToast('Có lỗi xảy ra khi tra cứu', 'error');
        } finally {
            loading?.classList.add('hidden');
        }
    }

    // Xử lý file Excel
    async function processExcel() {
        const fileInput = document.getElementById('fileInput');
        const loading = document.getElementById('loading');
        const resultBody = document.getElementById('resultBody');

        if (!fileInput.files.length) {
            showToast('Vui lòng chọn file Excel', 'error');
            return;
        }

        loading?.classList.remove('hidden');
        resultBody.innerHTML = '';

        try {
            const file = fileInput.files[0];
            const reader = new FileReader();

            reader.onload = async function (e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                    const jsonData = XLSX.utils.sheet_to_json(firstSheet);

                    if (!jsonData.length) {
                        throw new Error('File Excel không có dữ liệu');
                    }

                    let processed = 0;
                    const batchSize = 5;

                    for (let i = 0; i < jsonData.length; i += batchSize) {
                        const batch = jsonData.slice(i, i + batchSize);
                        const mstList = batch.map(row => row.MST || Object.values(row)[0]);
                        const results = await Promise.all(mstList.map(mst => searchMST(mst)));
                        results.forEach(tr => resultBody.appendChild(tr));
                        processed += batch.length;
                        updateProgress(processed, jsonData.length);

                        if (i + batchSize < jsonData.length) {
                            await new Promise(resolve => setTimeout(resolve, 1000));
                        }
                    }
                    showToast(`Đã xử lý ${processed} dòng từ file Excel!`);
                } catch (error) {
                    console.error('Error processing Excel:', error);
                    showToast('Có lỗi khi xử lý file Excel', 'error');
                } finally {
                    loading?.classList.add('hidden');
                }
            };

            reader.readAsArrayBuffer(file);
        } catch (error) {
            console.error('Error reading file:', error);
            showToast('Có lỗi khi đọc file', 'error');
            loading?.classList.add('hidden');
        }
    }

    // Xuất kết quả ra Excel
    function exportToExcel() {
        try {
            const resultBody = document.getElementById('resultBody');
            if (!resultBody.children.length) {
                showToast('Không có dữ liệu để xuất', 'error');
                return;
            }

            const table = document.getElementById('resultTable');
            const ws = XLSX.utils.table_to_sheet(table);

            // Định dạng cột MST
            const range = XLSX.utils.decode_range(ws['!ref']);
            for (let R = range.s.r + 1; R <= range.e.r; ++R) {
                const cellAddress = XLSX.utils.encode_cell({ r: R, c: 0 });
                if (ws[cellAddress]) {
                    ws[cellAddress].t = 's';
                    ws[cellAddress].v = String(ws[cellAddress].v);
                    if (ws[cellAddress].v.startsWith('0')) {
                        ws[cellAddress].z = '@';
                    }
                }
            }

            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "Kết quả tra cứu");

            const date = new Date();
            const fileName = `ket_qua_tra_cuu_mst_${date.toISOString().split('T')[0].replace(/-/g, '_')}_${date.getHours()}_${date.getMinutes()}.xlsx`;

            XLSX.writeFile(wb, fileName);
            showToast('Đã xuất Excel thành công!');
        } catch (error) {
            console.error('Error exporting to Excel:', error);
            showToast('Có lỗi khi xuất Excel', 'error');
        }
    }

    // Xóa kết quả
    function clearResults() {
        try {
            document.getElementById('resultBody').innerHTML = '';
            document.getElementById('mstInput').value = '';
            document.getElementById('fileInput').value = '';
            document.getElementById('progressContainer').classList.add('hidden');
            document.getElementById('progressBar').style.width = '0%';
            showToast('Đã xóa kết quả thành công');
        } catch (error) {
            console.error('Error clearing results:', error);
            showToast('Có lỗi khi xóa kết quả', 'error');
        }
    }

    // Xử lý phím tắt
    document.addEventListener('keydown', function (event) {
        if (event.ctrlKey && event.key === 'Enter') {
            const activeElement = document.activeElement;
            if (activeElement.id === 'mstInput') {
                processMST();
            }
        }
    });

    // Auto focus vào ô nhập MST
    window.addEventListener('load', function () {
        document.getElementById('mstInput').focus();
    });

    // Thêm sự kiện paste cho textarea
    document.getElementById('mstInput').addEventListener('paste', (e) => {
        setTimeout(() => {
            const text = e.target.value;
            e.target.value = text.split(/[\s,]+/).join('\n');
        }, 0);
    });
</script>
</body>

</html>