{% extends "_base.html" %}

{% block title %}Excel 批次查詢工具{% endblock %}

{% block head_extra %}
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft JhengHei', Arial, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 8px 8px 0 0;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }

        .header p {
            opacity: 0.9;
            font-size: 14px;
        }

        .content {
            padding: 30px;
        }

        .step-section {
            margin-bottom: 25px;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background: #fafafa;
        }

        .step-section.disabled {
            opacity: 0.5;
            pointer-events: none;
        }

        .step-title {
            font-size: 16px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .step-number {
            background: #667eea;
            color: white;
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }

        .upload-area {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        input[type="file"] {
            padding: 10px;
            border: 2px dashed #ccc;
            border-radius: 6px;
            cursor: pointer;
        }

        input[type="file"]:hover {
            border-color: #667eea;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.2s;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a6fd6;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
        }

        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        select {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            min-width: 200px;
            background: white;
        }

        select:focus {
            outline: none;
            border-color: #667eea;
        }

        .info-box {
            background: #e3e8ff;
            color: #667eea;
            padding: 10px 15px;
            border-radius: 6px;
            font-size: 13px;
            margin-top: 10px;
        }

        .info-box.warning {
            background: #fff3cd;
            color: #856404;
        }

        .checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
            max-height: 200px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            background: white;
        }

        .checkbox-item {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 5px 10px;
            background: #f8f9fa;
            border-radius: 4px;
            font-size: 13px;
        }

        .checkbox-item:hover {
            background: #e3e8ff;
        }

        .checkbox-item input[type="checkbox"] {
            cursor: pointer;
        }

        .select-all-bar {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }

        .select-all-bar button {
            padding: 5px 10px;
            font-size: 12px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
        }

        .select-all-bar button:hover {
            background: #f0f0f0;
        }

        .result-section {
            margin-top: 30px;
            display: none;
        }

        .result-section.active {
            display: block;
        }

        .result-header {
            background: #667eea;
            color: white;
            padding: 15px 20px;
            border-radius: 6px 6px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .result-stats {
            display: flex;
            gap: 20px;
            font-size: 14px;
        }

        .table-container {
            overflow-x: auto;
            max-height: 500px;
            border: 1px solid #e0e0e0;
            border-top: none;
            border-radius: 0 0 6px 6px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }

        thead {
            position: sticky;
            top: 0;
            background: #f8f9fa;
            z-index: 10;
        }

        th {
            padding: 12px 10px;
            text-align: left;
            border-bottom: 2px solid #dee2e6;
            font-weight: 600;
            color: #495057;
            white-space: nowrap;
        }

        td {
            padding: 10px;
            border-bottom: 1px solid #f0f0f0;
            color: #333;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #667eea;
        }

        .loading-spinner {
            display: inline-block;
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 10px;
        }

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

        .error {
            background: #fee;
            color: #c33;
            padding: 15px;
            border-radius: 6px;
            margin-top: 10px;
        }

        .preview-table {
            margin-top: 15px;
            font-size: 12px;
        }

        .preview-table th {
            background: #e9ecef;
            padding: 8px;
        }

        .preview-table td {
            padding: 8px;
            max-width: 150px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .row {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }

        .col {
            flex: 1;
            min-width: 300px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }

        /* Type badges */
        .type-badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: 500;
            margin-left: 5px;
        }
        .type-badge.text { background: #e3e8ff; color: #667eea; }
        .type-badge.number { background: #d4edda; color: #155724; }
        .type-badge.date { background: #fff3cd; color: #856404; }
        .type-badge.datetime { background: #ffeeba; color: #856404; }
        .type-badge.id { background: #cce5ff; color: #004085; }
        .type-badge.unknown { background: #f8f9fa; color: #6c757d; }

        /* Advanced options panel */
        .advanced-panel {
            margin-top: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            overflow: hidden;
        }
        .advanced-panel-header {
            background: #f8f9fa;
            padding: 12px 15px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 500;
        }
        .advanced-panel-header:hover {
            background: #e9ecef;
        }
        .advanced-panel-toggle {
            transition: transform 0.2s;
        }
        .advanced-panel.collapsed .advanced-panel-toggle {
            transform: rotate(-90deg);
        }
        .advanced-panel.collapsed .advanced-panel-body {
            display: none;
        }
        .advanced-panel-body {
            padding: 15px;
            background: white;
            border-top: 1px solid #e0e0e0;
        }

        /* Date inputs */
        input[type="date"] {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
        input[type="date"]:focus {
            outline: none;
            border-color: #667eea;
        }

        /* Performance warning */
        .performance-warning {
            background: #fff3cd;
            border: 1px solid #ffc107;
            color: #856404;
            padding: 10px 15px;
            border-radius: 6px;
            margin-top: 10px;
            font-size: 13px;
        }

        /* Type mismatch warning */
        .type-mismatch-warning {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
            padding: 8px 12px;
            border-radius: 4px;
            margin-top: 8px;
            font-size: 12px;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container">
        <div class="header">
            <h1>Excel 批次查詢工具</h1>
            <p>上傳 Excel 檔案，批次查詢資料庫並匯出結果</p>
        </div>

        <div class="content">
            <!-- Step 1: Upload Excel -->
            <div class="step-section" id="step1">
                <div class="step-title">
                    <span class="step-number">1</span>
                    上傳 Excel 檔案
                </div>
                <div class="upload-area">
                    <input type="file" id="excelFile" accept=".xlsx,.xls">
                    <button class="btn btn-primary" onclick="uploadExcel()">上傳</button>
                </div>
                <div id="uploadInfo"></div>
                <div id="previewTable"></div>
            </div>

            <!-- Step 2: Select Excel Column -->
            <div class="step-section disabled" id="step2">
                <div class="step-title">
                    <span class="step-number">2</span>
                    選擇 Excel 欄位（作為查詢值）
                </div>
                <div class="row">
                    <div class="col">
                        <label>選擇欄位：</label>
                        <select id="excelColumn" onchange="loadColumnValues()">
                            <option value="">-- 請選擇 --</option>
                        </select>
                    </div>
                </div>
                <div id="columnInfo"></div>
            </div>

            <!-- Step 3: Select Target Table -->
            <div class="step-section disabled" id="step3">
                <div class="step-title">
                    <span class="step-number">3</span>
                    選擇目標資料表
                </div>
                <div class="row">
                    <div class="col">
                        <label>資料表：</label>
                        <select id="targetTable" onchange="loadTableColumns()">
                            <option value="">-- 請選擇 --</option>
                        </select>
                    </div>
                </div>
                <div id="tableInfo"></div>
            </div>

            <!-- Step 4: Select Columns -->
            <div class="step-section disabled" id="step4">
                <div class="step-title">
                    <span class="step-number">4</span>
                    選擇查詢欄位與回傳欄位
                </div>
                <div class="row">
                    <div class="col">
                        <label>查詢欄位：</label>
                        <select id="searchColumn" onchange="checkTypeMismatch()">
                            <option value="">-- 請選擇 --</option>
                        </select>
                        <div id="typeMismatchWarning"></div>
                    </div>
                </div>

                <!-- Advanced Options Panel -->
                <div class="advanced-panel" id="advancedPanel">
                    <div class="advanced-panel-header" onclick="toggleAdvancedPanel()">
                        <span>進階查詢條件</span>
                        <span class="advanced-panel-toggle">&#9660;</span>
                    </div>
                    <div class="advanced-panel-body">
                        <!-- Query Type Selection -->
                        <div class="row" style="margin-bottom: 15px;">
                            <div class="col">
                                <label>查詢類型：</label>
                                <select id="queryType" onchange="onQueryTypeChange()">
                                    <option value="in">完全符合 (WHERE IN)</option>
                                    <option value="like_contains">包含 (LIKE %...%)</option>
                                    <option value="like_prefix">開頭符合 (LIKE ...%)</option>
                                    <option value="like_suffix">結尾符合 (LIKE %...)</option>
                                </select>
                            </div>
                        </div>

                        <!-- Date Range Filter -->
                        <div id="dateRangeSection" style="display: none;">
                            <label>日期範圍篩選：</label>
                            <div class="row" style="gap: 10px; align-items: center;">
                                <div>
                                    <label style="font-size: 12px; margin-bottom: 4px;">時間欄位</label>
                                    <select id="dateColumn" style="min-width: 150px;">
                                        <option value="">-- 不限時間 --</option>
                                    </select>
                                </div>
                                <div>
                                    <label style="font-size: 12px; margin-bottom: 4px;">起始日期</label>
                                    <input type="date" id="dateFrom">
                                </div>
                                <div>
                                    <label style="font-size: 12px; margin-bottom: 4px;">結束日期</label>
                                    <input type="date" id="dateTo">
                                </div>
                                <div>
                                    <button class="btn" style="padding: 8px 12px; margin-top: 18px;" onclick="setDefaultDateRange()">最近 90 天</button>
                                </div>
                            </div>
                            <div id="dateRangeError" class="error" style="display: none; margin-top: 10px;"></div>
                        </div>

                        <!-- Performance Warning -->
                        <div id="performanceWarning" class="performance-warning" style="display: none;"></div>
                    </div>
                </div>

                <div style="margin-top: 15px;">
                    <label>回傳欄位（可多選）：</label>
                    <div class="select-all-bar">
                        <button onclick="selectAllColumns()">全選</button>
                        <button onclick="deselectAllColumns()">取消全選</button>
                    </div>
                    <div class="checkbox-group" id="returnColumns"></div>
                </div>
            </div>

            <!-- Step 5: Execute -->
            <div class="step-section disabled" id="step5">
                <div class="step-title">
                    <span class="step-number">5</span>
                    執行查詢
                </div>
                <div style="display: flex; gap: 15px;">
                    <button class="btn btn-primary" onclick="executeQuery()">查詢預覽</button>
                    <button class="btn btn-success" onclick="exportCSV()">匯出 CSV</button>
                </div>
                <div id="executeInfo"></div>
            </div>

            <!-- Result Section -->
            <div class="result-section" id="resultSection">
                <div class="result-header">
                    <h3>查詢結果</h3>
                    <div class="result-stats" id="resultStats"></div>
                </div>
                <div class="table-container">
                    <div id="resultTable"></div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    {% set excel_query_js = frontend_asset('excel-query.js') %}
    {% if excel_query_js %}
    <script type="module" src="{{ excel_query_js }}"></script>
    {% else %}
    <script>
        // State
        let excelColumns = [];
        let excelColumnTypes = {};  // { columnName: { detected_type, type_label } }
        let searchValues = [];
        let tableColumns = [];      // Array of column names (for backward compat)
        let tableColumnsMeta = [];  // Array of { name, data_type, is_date, is_number }
        let tableMetadata = null;   // Full table metadata including time_field, row_count
        let queryResult = null;

        // Step 1: Upload Excel
        async function uploadExcel() {
            const fileInput = document.getElementById('excelFile');
            const file = fileInput.files[0];

            if (!file) {
                alert('請選擇檔案');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            document.getElementById('uploadInfo').innerHTML = '<div class="loading"><div class="loading-spinner"></div><br>上傳中...</div>';

            try {
                // Note: File upload uses native fetch since MesApi doesn't support FormData
                const response = await fetch('/api/excel-query/upload', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();

                if (data.error) {
                    document.getElementById('uploadInfo').innerHTML = `<div class="error">${data.error}</div>`;
                    return;
                }

                excelColumns = data.columns;
                document.getElementById('uploadInfo').innerHTML = `
                    <div class="info-box">
                        檔案上傳成功！共 ${data.total_rows} 行，${data.columns.length} 欄
                    </div>
                `;

                renderPreviewTable(data.columns, data.preview);

                const select = document.getElementById('excelColumn');
                select.innerHTML = '<option value="">-- 請選擇 --</option>';
                excelColumns.forEach(col => {
                    select.innerHTML += `<option value="${col}">${col}</option>`;
                });

                document.getElementById('step2').classList.remove('disabled');
                loadTables();

            } catch (error) {
                document.getElementById('uploadInfo').innerHTML = `<div class="error">上傳失敗: ${error.message}</div>`;
            }
        }

        function renderPreviewTable(columns, data) {
            if (!data || data.length === 0) return;

            let html = '<table class="preview-table"><thead><tr>';
            columns.forEach(col => {
                html += `<th>${col}</th>`;
            });
            html += '</tr></thead><tbody>';

            data.forEach(row => {
                html += '<tr>';
                columns.forEach(col => {
                    const val = row[col] !== null && row[col] !== undefined ? row[col] : '';
                    html += `<td title="${val}">${val}</td>`;
                });
                html += '</tr>';
            });
            html += '</tbody></table>';

            document.getElementById('previewTable').innerHTML = html;
        }

        // Step 2: Load column values
        async function loadColumnValues() {
            const column = document.getElementById('excelColumn').value;
            if (!column) {
                searchValues = [];
                document.getElementById('columnInfo').innerHTML = '';
                return;
            }

            document.getElementById('columnInfo').innerHTML = '<div class="loading"><div class="loading-spinner"></div><br>讀取中...</div>';

            try {
                // Get column values
                const data = await MesApi.post('/api/excel-query/column-values', { column_name: column });

                if (data.error) {
                    document.getElementById('columnInfo').innerHTML = `<div class="error">${data.error}</div>`;
                    return;
                }

                searchValues = data.values;

                // Get column type detection
                try {
                    const typeData = await MesApi.post('/api/excel-query/column-type', { column_name: column });
                    if (!typeData.error) {
                        excelColumnTypes[column] = typeData;
                    }
                } catch (e) {
                    console.warn('Could not detect column type:', e);
                }

                // Build info display
                const typeInfo = excelColumnTypes[column];
                const typeBadge = typeInfo ? `<span class="type-badge ${typeInfo.detected_type}">${typeInfo.type_label}</span>` : '';
                const warningClass = data.count > 1000 ? ' warning' : '';

                document.getElementById('columnInfo').innerHTML = `
                    <div class="info-box${warningClass}">
                        共 ${data.count} 個不重複值 ${typeBadge}
                        ${data.count > 1000 ? '（將分批查詢，每批 1000 筆）' : ''}
                    </div>
                `;

                document.getElementById('step3').classList.remove('disabled');

            } catch (error) {
                document.getElementById('columnInfo').innerHTML = `<div class="error">讀取失敗: ${error.message}</div>`;
            }
        }

        // Load available tables
        async function loadTables() {
            try {
                const data = await MesApi.get('/api/excel-query/tables', { silent: true });

                const select = document.getElementById('targetTable');
                select.innerHTML = '<option value="">-- 請選擇 --</option>';

                data.tables.forEach(table => {
                    select.innerHTML += `<option value="${table.name}">${table.display_name} (${table.name})</option>`;
                });
            } catch (error) {
                console.error('Failed to load tables:', error);
            }
        }

        // Step 3: Load table columns (using new table-metadata endpoint)
        async function loadTableColumns() {
            const tableName = document.getElementById('targetTable').value;
            if (!tableName) {
                tableColumns = [];
                tableColumnsMeta = [];
                tableMetadata = null;
                document.getElementById('tableInfo').innerHTML = '';
                document.getElementById('dateRangeSection').style.display = 'none';
                document.getElementById('performanceWarning').style.display = 'none';
                return;
            }

            document.getElementById('tableInfo').innerHTML = '<div class="loading"><div class="loading-spinner"></div><br>讀取欄位...</div>';

            try {
                const data = await MesApi.post('/api/excel-query/table-metadata', { table_name: tableName });

                if (data.error) {
                    document.getElementById('tableInfo').innerHTML = `<div class="error">${data.error}</div>`;
                    return;
                }

                tableColumnsMeta = data.columns || [];
                tableColumns = tableColumnsMeta.map(c => c.name);
                tableMetadata = data;

                // Show table info
                let infoHtml = `共 ${tableColumns.length} 個欄位`;
                if (data.row_count) {
                    infoHtml += ` | 約 ${data.row_count.toLocaleString()} 筆`;
                }
                if (data.time_field) {
                    infoHtml += ` | 時間欄位: ${data.time_field}`;
                }
                document.getElementById('tableInfo').innerHTML = `<div class="info-box">${infoHtml}</div>`;

                // Populate search column dropdown with type badges
                const searchSelect = document.getElementById('searchColumn');
                searchSelect.innerHTML = '<option value="">-- 請選擇 --</option>';
                tableColumnsMeta.forEach(col => {
                    const typeBadge = getTypeBadgeHtml(col.data_type);
                    searchSelect.innerHTML += `<option value="${col.name}" data-type="${col.data_type}">${col.name} ${typeBadge}</option>`;
                });

                // Populate return columns with type badges
                const container = document.getElementById('returnColumns');
                container.innerHTML = '';
                tableColumnsMeta.forEach(col => {
                    const typeBadge = getTypeBadgeHtml(col.data_type);
                    container.innerHTML += `
                        <label class="checkbox-item">
                            <input type="checkbox" value="${col.name}" checked>
                            ${col.name} ${typeBadge}
                        </label>
                    `;
                });

                // Setup date range section
                setupDateRangeSection(data);

                // Show performance warning if applicable
                if (data.performance_warning) {
                    document.getElementById('performanceWarning').textContent = data.performance_warning;
                    document.getElementById('performanceWarning').style.display = 'block';
                } else {
                    document.getElementById('performanceWarning').style.display = 'none';
                }

                document.getElementById('step4').classList.remove('disabled');
                document.getElementById('step5').classList.remove('disabled');

            } catch (error) {
                document.getElementById('tableInfo').innerHTML = `<div class="error">讀取失敗: ${error.message}</div>`;
            }
        }

        // Helper: Get type badge HTML
        function getTypeBadgeHtml(dataType) {
            if (!dataType || dataType === 'UNKNOWN') return '';

            const typeMap = {
                'VARCHAR2': { class: 'text', label: '文字' },
                'CHAR': { class: 'text', label: '文字' },
                'NVARCHAR2': { class: 'text', label: '文字' },
                'CLOB': { class: 'text', label: '文字' },
                'NUMBER': { class: 'number', label: '數值' },
                'FLOAT': { class: 'number', label: '數值' },
                'INTEGER': { class: 'number', label: '數值' },
                'DATE': { class: 'date', label: '日期' },
                'TIMESTAMP': { class: 'datetime', label: '日期時間' },
            };

            // Find matching type
            for (const [key, val] of Object.entries(typeMap)) {
                if (dataType.toUpperCase().includes(key)) {
                    return `<span class="type-badge ${val.class}">${val.label}</span>`;
                }
            }
            return `<span class="type-badge unknown">${dataType}</span>`;
        }

        // Setup date range section based on table metadata
        function setupDateRangeSection(metadata) {
            const section = document.getElementById('dateRangeSection');
            const dateColumnSelect = document.getElementById('dateColumn');

            // Find date/timestamp columns
            const dateColumns = tableColumnsMeta.filter(c => c.is_date);

            if (dateColumns.length === 0 && !metadata.time_field) {
                section.style.display = 'none';
                return;
            }

            section.style.display = 'block';
            dateColumnSelect.innerHTML = '<option value="">-- 不限時間 --</option>';

            // Add configured time_field first if available
            if (metadata.time_field) {
                dateColumnSelect.innerHTML += `<option value="${metadata.time_field}" selected>${metadata.time_field} (預設)</option>`;
            }

            // Add other date columns
            dateColumns.forEach(col => {
                if (col.name !== metadata.time_field) {
                    dateColumnSelect.innerHTML += `<option value="${col.name}">${col.name}</option>`;
                }
            });
        }

        // Set default date range (last 90 days)
        function setDefaultDateRange() {
            const today = new Date();
            const past = new Date();
            past.setDate(today.getDate() - 90);

            document.getElementById('dateFrom').value = past.toISOString().split('T')[0];
            document.getElementById('dateTo').value = today.toISOString().split('T')[0];
        }

        // Toggle advanced panel
        function toggleAdvancedPanel() {
            const panel = document.getElementById('advancedPanel');
            panel.classList.toggle('collapsed');
        }

        // Handle query type change
        function onQueryTypeChange() {
            const queryType = document.getElementById('queryType').value;
            const warningDiv = document.getElementById('performanceWarning');

            // Show warning for LIKE contains on large tables
            if (queryType === 'like_contains' && tableMetadata && tableMetadata.row_count > 10000000) {
                warningDiv.textContent = '此資料表超過 1000 萬筆，包含查詢可能較慢，建議配合日期範圍縮小查詢範圍';
                warningDiv.style.display = 'block';
            } else if (tableMetadata && tableMetadata.performance_warning && queryType === 'like_contains') {
                warningDiv.textContent = tableMetadata.performance_warning;
                warningDiv.style.display = 'block';
            } else {
                warningDiv.style.display = 'none';
            }
        }

        // Check for type mismatch between Excel column and Oracle column
        function checkTypeMismatch() {
            const warningDiv = document.getElementById('typeMismatchWarning');
            const searchCol = document.getElementById('searchColumn').value;
            const excelCol = document.getElementById('excelColumn').value;

            if (!searchCol || !excelCol) {
                warningDiv.innerHTML = '';
                return;
            }

            // Get types
            const oracleMeta = tableColumnsMeta.find(c => c.name === searchCol);
            const excelType = excelColumnTypes[excelCol];

            if (!oracleMeta || !excelType) {
                warningDiv.innerHTML = '';
                return;
            }

            // Check for potential mismatches
            let warning = '';
            if (oracleMeta.is_number && excelType.detected_type === 'text') {
                warning = '欄位類型可能不相符：Excel 欄位為文字，Oracle 欄位為數值';
            } else if (oracleMeta.is_date && excelType.detected_type !== 'date' && excelType.detected_type !== 'datetime') {
                warning = '欄位類型可能不相符：Oracle 欄位為日期類型';
            }

            if (warning) {
                warningDiv.innerHTML = `<div class="type-mismatch-warning">${warning}</div>`;
            } else {
                warningDiv.innerHTML = '';
            }
        }

        function selectAllColumns() {
            document.querySelectorAll('#returnColumns input[type="checkbox"]').forEach(cb => cb.checked = true);
        }

        function deselectAllColumns() {
            document.querySelectorAll('#returnColumns input[type="checkbox"]').forEach(cb => cb.checked = false);
        }

        function getSelectedReturnColumns() {
            const checkboxes = document.querySelectorAll('#returnColumns input[type="checkbox"]:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        }

        function getQueryParams() {
            const params = {
                table_name: document.getElementById('targetTable').value,
                search_column: document.getElementById('searchColumn').value,
                return_columns: getSelectedReturnColumns(),
                search_values: searchValues,
                query_type: document.getElementById('queryType').value
            };

            // Add date range if specified
            const dateColumn = document.getElementById('dateColumn').value;
            const dateFrom = document.getElementById('dateFrom').value;
            const dateTo = document.getElementById('dateTo').value;

            if (dateColumn) {
                params.date_column = dateColumn;
                if (dateFrom) params.date_from = dateFrom;
                if (dateTo) params.date_to = dateTo;
            }

            return params;
        }

        function validateQuery() {
            const params = getQueryParams();

            if (!params.table_name) {
                alert('請選擇資料表');
                return false;
            }
            if (!params.search_column) {
                alert('請選擇查詢欄位');
                return false;
            }
            if (params.return_columns.length === 0) {
                alert('請至少選擇一個回傳欄位');
                return false;
            }
            if (params.search_values.length === 0) {
                alert('無查詢值，請先選擇 Excel 欄位');
                return false;
            }

            // Validate LIKE keyword limit
            if (params.query_type.startsWith('like_') && params.search_values.length > 100) {
                alert('LIKE 查詢最多支援 100 個關鍵字，目前有 ' + params.search_values.length + ' 個');
                return false;
            }

            // Validate date range
            if (params.date_from && params.date_to) {
                const from = new Date(params.date_from);
                const to = new Date(params.date_to);
                if (from > to) {
                    alert('起始日期不可晚於結束日期');
                    document.getElementById('dateRangeError').textContent = '起始日期不可晚於結束日期';
                    document.getElementById('dateRangeError').style.display = 'block';
                    return false;
                }
                const daysDiff = (to - from) / (1000 * 60 * 60 * 24);
                if (daysDiff > 365) {
                    alert('日期範圍不可超過 365 天');
                    document.getElementById('dateRangeError').textContent = '日期範圍不可超過 365 天';
                    document.getElementById('dateRangeError').style.display = 'block';
                    return false;
                }
                document.getElementById('dateRangeError').style.display = 'none';
            }

            return true;
        }

        // Step 5: Execute query
        async function executeQuery() {
            if (!validateQuery()) return;

            const params = getQueryParams();
            const isAdvanced = params.query_type !== 'in' || params.date_column;
            const batchCount = params.query_type === 'in' ? Math.ceil(params.search_values.length / 1000) : 1;

            // Build loading message
            let loadingMsg = `查詢中... (${params.search_values.length} 筆`;
            if (params.query_type !== 'in') {
                const typeLabels = {
                    'like_contains': '包含查詢',
                    'like_prefix': '前綴查詢',
                    'like_suffix': '後綴查詢'
                };
                loadingMsg += `，${typeLabels[params.query_type] || params.query_type}`;
            } else if (batchCount > 1) {
                loadingMsg += `，${batchCount} 批次`;
            }
            if (params.date_from || params.date_to) {
                loadingMsg += `，日期篩選`;
            }
            loadingMsg += ')';

            document.getElementById('executeInfo').innerHTML = `
                <div class="loading">
                    <div class="loading-spinner"></div><br>
                    ${loadingMsg}
                </div>
            `;
            document.getElementById('resultSection').classList.remove('active');

            try {
                // Use advanced endpoint if using advanced features
                const endpoint = isAdvanced ? '/api/excel-query/execute-advanced' : '/api/excel-query/execute';
                const data = await MesApi.post(endpoint, params);

                if (data.error) {
                    document.getElementById('executeInfo').innerHTML = `<div class="error">${data.error}</div>`;
                    return;
                }

                queryResult = data;

                // Build result message
                let resultMsg = `查詢完成！搜尋 ${data.search_count} 筆，找到 ${data.row_count} 筆結果`;
                if (data.query_type && data.query_type !== 'in') {
                    resultMsg += ` (${data.query_type})`;
                }

                document.getElementById('executeInfo').innerHTML = `
                    <div class="info-box">${resultMsg}</div>
                `;

                renderResult(data);

            } catch (error) {
                document.getElementById('executeInfo').innerHTML = `<div class="error">查詢失敗: ${error.message}</div>`;
            }
        }

        function renderResult(data) {
            const section = document.getElementById('resultSection');
            const statsDiv = document.getElementById('resultStats');
            const tableDiv = document.getElementById('resultTable');

            statsDiv.innerHTML = `
                <span>搜尋值: ${data.search_count}</span>
                <span>結果: ${data.row_count} 筆</span>
                ${data.batch_count > 1 ? `<span>批次: ${data.batch_count}</span>` : ''}
            `;

            if (data.data.length === 0) {
                tableDiv.innerHTML = '<div style="padding: 40px; text-align: center; color: #999;">查無資料</div>';
            } else {
                let html = '<table><thead><tr>';
                data.columns.forEach(col => {
                    html += `<th>${col}</th>`;
                });
                html += '</tr></thead><tbody>';

                const previewData = data.data.slice(0, 1000);
                previewData.forEach(row => {
                    html += '<tr>';
                    data.columns.forEach(col => {
                        const val = row[col] !== null && row[col] !== undefined ? row[col] : '<i style="color:#999">NULL</i>';
                        html += `<td>${val}</td>`;
                    });
                    html += '</tr>';
                });
                html += '</tbody></table>';

                if (data.data.length > 1000) {
                    html += `<div style="padding: 15px; text-align: center; color: #666; background: #f8f9fa;">
                        顯示前 1000 筆，完整資料請匯出 CSV
                    </div>`;
                }

                tableDiv.innerHTML = html;
            }

            section.classList.add('active');
            section.scrollIntoView({ behavior: 'smooth' });
        }

        // Export CSV
        async function exportCSV() {
            if (!validateQuery()) return;

            const params = getQueryParams();
            const batchCount = Math.ceil(params.search_values.length / 1000);

            document.getElementById('executeInfo').innerHTML = `
                <div class="loading">
                    <div class="loading-spinner"></div><br>
                    匯出中... (${params.search_values.length} 筆，${batchCount} 批次)
                </div>
            `;

            try {
                // Note: CSV export uses native fetch for blob response
                const response = await fetch('/api/excel-query/export-csv', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(params)
                });

                if (!response.ok) {
                    const data = await response.json();
                    document.getElementById('executeInfo').innerHTML = `<div class="error">${data.error || '匯出失敗'}</div>`;
                    return;
                }

                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'query_result.csv';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);

                document.getElementById('executeInfo').innerHTML = `
                    <div class="info-box">CSV 匯出完成！</div>
                `;

            } catch (error) {
                document.getElementById('executeInfo').innerHTML = `<div class="error">匯出失敗: ${error.message}</div>`;
            }
        }
    </script>
    {% endif %}
{% endblock %}
