<?php
// 功能：订单管理文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。

if (!defined('ADMIN_LOADED')) {
    header('HTTP/1.1 403 Forbidden');
    exit('Access Denied');
}

global $conn;

$action = $_GET['action'] ?? '';
$order_id = $_GET['id'] ?? '';
$page = isset($current_page) ? intval($current_page) : 1;
$posts_per_page = isset($posts_per_page) ? intval($posts_per_page) : 30;
$search_query = isset($search) ? trim($search) : (isset($_GET['search']) ? trim($_GET['search']) : '');

if ($action === 'delete' && $order_id) {
    $stmt = $conn->prepare("DELETE FROM `order` WHERE id = ?");
    $stmt->bind_param('i', $order_id);
    $stmt->execute();
    $ok = $stmt->affected_rows > 0;
    $stmt->close();
    if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
        echo $ok ? 'success' : 'error';
    }
    exit;
}

if ($action === 'clear_all') {
    $result = $conn->query("DELETE FROM `order`");
    if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
        echo $result ? 'success' : 'error';
    }
    exit;
}

$filter = isset($_GET['filter']) ? trim($_GET['filter']) : '';
$time_range = isset($_GET['time_range']) ? trim($_GET['time_range']) : '';

$filter_condition = '';
if (!empty($filter)) {
    switch ($filter) {
        case 'today':
            $filter_condition = " AND DATE(o.created_at) = CURDATE()";
            break;
        case 'this_month':
            $filter_condition = " AND YEAR(o.created_at) = YEAR(CURDATE()) AND MONTH(o.created_at) = MONTH(CURDATE())";
            break;
        case 'wechat':
            $filter_condition = " AND o.pay_type = '微信'";
            break;
        case 'alipay':
            $filter_condition = " AND o.pay_type = '支付宝'";
            break;
        case 'shipped':
            $filter_condition = " AND o.shipping_status = 1";
            break;
        case 'unshipped':
            $filter_condition = " AND o.shipping_status = 0";
            break;
        case 'points':
            $filter_condition = " AND o.type = '积分类'";
            break;
        case 'resource':
            $filter_condition = " AND o.type = '资源类'";
            break;
        case 'tool':
            $filter_condition = " AND o.type = '工具类'";
            break;
        case 'goods':
            $filter_condition = " AND o.type = '商品类'";
            break;
    }
}

$time_condition = '';
if (!empty($time_range)) {
    switch ($time_range) {
        case 'today':
            $time_condition = " AND DATE(o.created_at) = CURDATE()";
            break;
        case 'yesterday':
            $time_condition = " AND DATE(o.created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
            break;
        case 'this_month':
            $time_condition = " AND YEAR(o.created_at) = YEAR(CURDATE()) AND MONTH(o.created_at) = MONTH(CURDATE())";
            break;
        case 'three_months':
            $time_condition = " AND o.created_at >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)";
            break;
        case 'this_year':
            $time_condition = " AND YEAR(o.created_at) = YEAR(CURDATE())";
            break;
    }
}

$total_amount_query = "SELECT SUM(amount) as total_amount FROM `order` o WHERE 1=1" . $filter_condition . $time_condition;
if (!empty($search_query)) {
    $total_amount_query .= " AND (o.order_no LIKE '%" . $conn->real_escape_string($search_query) . "%' OR o.user_id IN (SELECT id FROM users WHERE username LIKE '%" . $conn->real_escape_string($search_query) . "%'))";
}
$total_amount_result = $conn->query($total_amount_query);
$total_amount_row = $total_amount_result->fetch_assoc();
$total_amount = $total_amount_row['total_amount'] ?? 0;

$page = max(1, $page);
$posts_per_page = max(1, min(1000, $posts_per_page));
$offset = ($page - 1) * $posts_per_page;

$search_condition = '';
if (!empty($search_query)) {
    $search_condition = " WHERE (o.order_no LIKE '" . $conn->real_escape_string($search_query) . "%' OR u.username LIKE '" . $conn->real_escape_string($search_query) . "%')";
}

$where_condition = $search_condition;
if (empty($where_condition)) {
    $where_condition = " WHERE 1=1";
} else {
    $where_condition = str_replace("WHERE", "WHERE (", $where_condition) . ")";
}
$where_condition .= $filter_condition . $time_condition;

$total_orders_result = $conn->query("SELECT COUNT(*) as total FROM `order` o LEFT JOIN users u ON o.user_id = u.id" . $where_condition);
$total_orders_row = $total_orders_result->fetch_assoc();
$total_orders = $total_orders_row['total'] ?? 0;
$total_pages = ceil($total_orders / $posts_per_page);

$orders_result = $conn->query("SELECT o.*, u.username FROM `order` o LEFT JOIN users u ON o.user_id = u.id" . $where_condition . " ORDER BY o.created_at DESC LIMIT $offset, $posts_per_page");
$orders = [];
while ($row = $orders_result->fetch_assoc()) {
    $orders[] = $row;
}
$payTypeStyleMap = function_exists('getPayConfig56PayTypeStyleMap') ? getPayConfig56PayTypeStyleMap() : array();
?>

<script src="../assets/js/toast.js"></script>
<script>
    window.isDemoOrderAccount = <?php echo function_exists('isDemoAdmin') && isDemoAdmin() ? 'true' : 'false'; ?>;
    window.payTypeStyleMap = <?php echo json_encode($payTypeStyleMap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

    function getPayTagHtml(payType) {
        payType = payType || '';
        const m = window.payTypeStyleMap || {};
        const s = m[payType] || null;
        if (!payType) return '-';
        if (!s) return `<span class="pay-type-tag pay-type-tag-default">${escapeHtml(payType)}</span>`;
        const bg = s.bg || '';
        const color = s.color || '';
        const border = s.border || '';
        const style = `background-color:${bg};color:${color};border:1px solid ${border};`;
        return `<span class="pay-type-tag" style="${style}">${escapeHtml(payType)}</span>`;
    }

    function handleOrderAjaxResponse(rawText, successMessage, onSuccess) {
        let response = null;
        const text = (rawText || '').trim();

        try {
            response = JSON.parse(text);
        } catch (e) {}

        if (response && response.success === false) {
            showToast(response.message || response.error || '演示账号无权限操作', 'error', 2000);
            return false;
        }

        if (response && response.success === true) {
            showToast(response.message || successMessage, 'success', 2000);
            if (typeof onSuccess === 'function') onSuccess();
            return true;
        }

        if (text === 'success') {
            showToast(successMessage, 'success', 2000);
            if (typeof onSuccess === 'function') onSuccess();
            return true;
        }

        showToast(text || '操作失败', 'error', 2000);
        return false;
    }

    function deleteOrder(id, searchQuery) {
        if (window.isDemoOrderAccount) {
            showToast('演示账号无权限操作', 'error', 2000);
            return;
        }
        const xhr = new XMLHttpRequest();
        xhr.open('GET', '/admin/admin.php?tab=order&action=delete&id=' + id + '&ajax=1', true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                handleOrderAjaxResponse(xhr.responseText, '订单删除成功', function() {
                    if (typeof HeaderPagination !== 'undefined') HeaderPagination.load();
                    else window.location.reload();
                });
            }
        };
        xhr.send();
    }

    function updateShippingStatus(id, status) {
        // 更新当前下拉框的class
        const selectElements = document.querySelectorAll('.admin-table.order-manage select.shipping-status-select[onchange*="updateShippingStatus(' + id + '"');
        selectElements.forEach(select => {
            select.className = select.className.replace(/status-\d/g, '');
            select.classList.add('status-' + status);
        });

        if (window.isDemoOrderAccount) {
            if (window._ordersCache && window._ordersCache[id]) {
                const originalStatus = window._ordersCache[id].shipping_status;
                selectElements.forEach(select => {
                    select.value = originalStatus;
                    select.className = select.className.replace(/status-\d/g, '');
                    select.classList.add('status-' + originalStatus);
                });
            }
            if (typeof showToast === 'function') showToast('演示账号无权限操作', 'error', 1500);
            return;
        }

        const params = new URLSearchParams();
        params.set('action', 'update_order_shipping');
        params.set('id', String(id));
        params.set('shipping_status', String(status));
        fetch('/admin/ajaxx.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: params.toString()
        }).then(r => r.json()).then(d => {
            if (d && d.success) {
                if (typeof showToast === 'function') showToast('更新成功', 'info', 1200);
                if (window._ordersCache && window._ordersCache[id]) {
                    window._ordersCache[id].shipping_status = status;
                }
                return;
            }
            // 如果更新失败，恢复原来的状态和样式
            if (window._ordersCache && window._ordersCache[id]) {
                const originalStatus = window._ordersCache[id].shipping_status;
                selectElements.forEach(select => {
                    select.value = originalStatus;
                    select.className = select.className.replace(/status-\d/g, '');
                    select.classList.add('status-' + originalStatus);
                });
            }
            if (typeof showToast === 'function') showToast((d && d.message) ? d.message : '更新失败', 'error', 1500);
        }).catch(() => {
            // 如果请求失败，恢复原来的状态和样式
            if (window._ordersCache && window._ordersCache[id]) {
                const originalStatus = window._ordersCache[id].shipping_status;
                selectElements.forEach(select => {
                    select.value = originalStatus;
                    select.className = select.className.replace(/status-\d/g, '');
                    select.classList.add('status-' + originalStatus);
                });
            }
            if (typeof showToast === 'function') showToast('更新失败', 'error', 1500);
        });
    }

    function clearAllOrders() {
        if (window.isDemoOrderAccount) {
            showToast('演示账号无权限操作', 'error', 2000);
            return;
        }
        const confirmMessage = '此操作将清空所有订单数据且无法恢复';
        if (typeof window.confirmDialog === 'function') {
            window.confirmDialog(confirmMessage, function() {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', '/admin/admin.php?tab=order&action=clear_all&ajax=1', true);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        handleOrderAjaxResponse(xhr.responseText, '全部订单已清空', function() {
                            if (typeof HeaderPagination !== 'undefined') HeaderPagination.load();
                            else window.location.reload();
                        });
                    }
                };
                xhr.send();
            });
        } else {
            if (confirm(confirmMessage)) {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', '/admin/admin.php?tab=order&action=clear_all&ajax=1', true);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        handleOrderAjaxResponse(xhr.responseText, '全部订单已清空', function() {
                            if (typeof HeaderPagination !== 'undefined') HeaderPagination.load();
                            else window.location.reload();
                        });
                    }
                };
                xhr.send();
            }
        }
    }

    function toggleTimeMenu() {
        const header = document.getElementById('time-header');
        const menu = document.getElementById('time-dropdown-menu');
        if (!header || !menu) return;

        closeAllMenus();

        const isOpen = menu.style.display === 'block';
        if (isOpen) {
            menu.style.display = 'none';
            return;
        }

        if (menu.parentElement !== document.body) {
            document.body.appendChild(menu);
        }

        const rect = header.getBoundingClientRect();
        menu.style.position = 'fixed';
        menu.style.top = rect.bottom + 'px';
        menu.style.left = rect.left + 'px';
        menu.style.zIndex = '2147483647';
        menu.style.setProperty('display', 'block', 'important');
    }

    function toggleTypeMenu() {
        const header = document.getElementById('type-header');
        const menu = document.getElementById('type-dropdown-menu');
        if (!header || !menu) return;

        closeAllMenus();

        const isOpen = menu.style.display === 'block';
        if (isOpen) {
            menu.style.display = 'none';
            return;
        }

        if (menu.parentElement !== document.body) {
            document.body.appendChild(menu);
        }

        const rect = header.getBoundingClientRect();
        menu.style.position = 'fixed';
        menu.style.top = rect.bottom + 'px';
        menu.style.left = rect.left + 'px';
        menu.style.zIndex = '2147483647';
        menu.style.setProperty('display', 'block', 'important');
    }

    function togglePayMenu() {
        const header = document.getElementById('pay-header');
        const menu = document.getElementById('pay-dropdown-menu');
        if (!header || !menu) return;

        closeAllMenus();

        const isOpen = menu.style.display === 'block';
        if (isOpen) {
            menu.style.display = 'none';
            return;
        }

        if (menu.parentElement !== document.body) {
            document.body.appendChild(menu);
        }

        const rect = header.getBoundingClientRect();
        menu.style.position = 'fixed';
        menu.style.top = rect.bottom + 'px';
        menu.style.left = rect.left + 'px';
        menu.style.zIndex = '2147483647';
        menu.style.setProperty('display', 'block', 'important');
    }

    function toggleStatusMenu() {
        const header = document.getElementById('status-header');
        const menu = document.getElementById('status-dropdown-menu');
        if (!header || !menu) return;

        closeAllMenus();

        const isOpen = menu.style.display === 'block';
        if (isOpen) {
            menu.style.display = 'none';
            return;
        }

        if (menu.parentElement !== document.body) {
            document.body.appendChild(menu);
        }

        const rect = header.getBoundingClientRect();
        menu.style.position = 'fixed';
        menu.style.top = rect.bottom + 'px';
        menu.style.left = rect.left + 'px';
        menu.style.zIndex = '2147483647';
        menu.style.setProperty('display', 'block', 'important');
    }

    function closeAllMenus() {
        const menus = ['time-dropdown-menu', 'type-dropdown-menu', 'pay-dropdown-menu', 'status-dropdown-menu'];
        menus.forEach(menuId => {
            const menu = document.getElementById(menuId);
            if (menu) {
                menu.style.removeProperty('display');
                menu.style.display = 'none';
            }
        });
    }

    function filterTime(timeRange) {
        const menu = document.getElementById('time-dropdown-menu');
        if (menu) menu.style.display = 'none';
        
        const current = new URLSearchParams(window.location.search);
        current.delete('page');
        current.delete('posts_per_page');
        for (const key of Array.from(current.keys())) {
            if (key.match(/^p\d+_s\d+$/)) current.delete(key);
        }
        if (timeRange) current.set('time_range', timeRange);
        else current.delete('time_range');

        const pageSize = (typeof HeaderPagination !== 'undefined' && HeaderPagination.state && HeaderPagination.state.pageSize) ? HeaderPagination.state.pageSize : 30;
        let newUrl = '?tab=order&p1_s' + pageSize;
        for (const [key, value] of current.entries()) {
            if (key !== 'tab') newUrl += '&' + key + '=' + encodeURIComponent(value);
        }
        window.history.pushState({}, document.title, newUrl);

        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = 1;
            HeaderPagination.load();
        }
    }

    function filterType(typeVal) {
        const menu = document.getElementById('type-dropdown-menu');
        if (menu) menu.style.display = 'none';
        
        const current = new URLSearchParams(window.location.search);
        current.delete('page');
        current.delete('posts_per_page');
        for (const key of Array.from(current.keys())) {
            if (key.match(/^p\d+_s\d+$/)) current.delete(key);
        }
        
        let filterVal = '';
        if (typeVal === '积分类') filterVal = 'points';
        else if (typeVal === '资源类') filterVal = 'resource';
        else if (typeVal === '工具类') filterVal = 'tool';
        else if (typeVal === '商品类') filterVal = 'goods';
        
        if (filterVal) current.set('filter', filterVal);
        else current.delete('filter');

        const pageSize = (typeof HeaderPagination !== 'undefined' && HeaderPagination.state && HeaderPagination.state.pageSize) ? HeaderPagination.state.pageSize : 30;
        let newUrl = '?tab=order&p1_s' + pageSize;
        for (const [key, value] of current.entries()) {
            if (key !== 'tab') newUrl += '&' + key + '=' + encodeURIComponent(value);
        }
        window.history.pushState({}, document.title, newUrl);

        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = 1;
            HeaderPagination.load();
        }
    }

    function filterPay(payType) {
        const menu = document.getElementById('pay-dropdown-menu');
        if (menu) menu.style.display = 'none';
        
        const current = new URLSearchParams(window.location.search);
        current.delete('page');
        current.delete('posts_per_page');
        for (const key of Array.from(current.keys())) {
            if (key.match(/^p\d+_s\d+$/)) current.delete(key);
        }
        
        let filterVal = '';
        if (payType === '微信') filterVal = 'wechat';
        else if (payType === '支付宝') filterVal = 'alipay';
        
        if (filterVal) current.set('filter', filterVal);
        else current.delete('filter');

        const pageSize = (typeof HeaderPagination !== 'undefined' && HeaderPagination.state && HeaderPagination.state.pageSize) ? HeaderPagination.state.pageSize : 30;
        let newUrl = '?tab=order&p1_s' + pageSize;
        for (const [key, value] of current.entries()) {
            if (key !== 'tab') newUrl += '&' + key + '=' + encodeURIComponent(value);
        }
        window.history.pushState({}, document.title, newUrl);

        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = 1;
            HeaderPagination.load();
        }
    }

    function filterStatus(statusVal) {
        const menu = document.getElementById('status-dropdown-menu');
        if (menu) menu.style.display = 'none';
        
        const current = new URLSearchParams(window.location.search);
        current.delete('page');
        current.delete('posts_per_page');
        for (const key of Array.from(current.keys())) {
            if (key.match(/^p\d+_s\d+$/)) current.delete(key);
        }
        
        if (statusVal) current.set('filter', statusVal);
        else current.delete('filter');

        const pageSize = (typeof HeaderPagination !== 'undefined' && HeaderPagination.state && HeaderPagination.state.pageSize) ? HeaderPagination.state.pageSize : 30;
        let newUrl = '?tab=order&p1_s' + pageSize;
        for (const [key, value] of current.entries()) {
            if (key !== 'tab') newUrl += '&' + key + '=' + encodeURIComponent(value);
        }
        window.history.pushState({}, document.title, newUrl);

        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = 1;
            HeaderPagination.load();
        }
    }

    document.addEventListener('click', function(e) {
        const menus = ['time-dropdown-menu', 'type-dropdown-menu', 'pay-dropdown-menu', 'status-dropdown-menu'];
        const headers = ['time-header', 'type-header', 'pay-header', 'status-header'];
        
        let clickedOnMenu = false;
        let clickedOnHeader = false;
        
        for (let i = 0; i < menus.length; i++) {
            if (e.target.closest('#' + menus[i])) {
                clickedOnMenu = true;
                break;
            }
        }
        
        for (let i = 0; i < headers.length; i++) {
            if (e.target.closest('#' + headers[i])) {
                clickedOnHeader = true;
                break;
            }
        }
        
        if (!clickedOnMenu && !clickedOnHeader) {
            closeAllMenus();
        }
    });

    window.addEventListener('scroll', function() {
        closeAllMenus();
    }, { passive: true });

    function applyOrderFilter() {
        const filter = document.getElementById('order-filter').value;
        const timeRange = document.getElementById('time-range').value;
        const current = new URLSearchParams(window.location.search);
        current.delete('page');
        current.delete('posts_per_page');
        for (const key of Array.from(current.keys())) {
            if (key.match(/^p\d+_s\d+$/)) current.delete(key);
        }
        if (filter) current.set('filter', filter);
        else current.delete('filter');
        if (timeRange) current.set('time_range', timeRange);
        else current.delete('time_range');

        const pageSize = (typeof HeaderPagination !== 'undefined' && HeaderPagination.state && HeaderPagination.state.pageSize) ? HeaderPagination.state.pageSize : 30;
        let newUrl = '?tab=order&p1_s' + pageSize;
        for (const [key, value] of current.entries()) {
            if (key !== 'tab') newUrl += '&' + key + '=' + encodeURIComponent(value);
        }
        window.history.pushState({}, document.title, newUrl);

        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = 1;
            HeaderPagination.load();
        }
    }

    function applyTimeFilter() {
        const timeRange = document.getElementById('time-range').value;
        const filter = document.getElementById('order-filter').value;
        const current = new URLSearchParams(window.location.search);
        current.delete('page');
        current.delete('posts_per_page');
        for (const key of Array.from(current.keys())) {
            if (key.match(/^p\d+_s\d+$/)) current.delete(key);
        }
        if (timeRange) current.set('time_range', timeRange);
        else current.delete('time_range');
        if (filter) current.set('filter', filter);
        else current.delete('filter');

        const pageSize = (typeof HeaderPagination !== 'undefined' && HeaderPagination.state && HeaderPagination.state.pageSize) ? HeaderPagination.state.pageSize : 30;
        let newUrl = '?tab=order&p1_s' + pageSize;
        for (const [key, value] of current.entries()) {
            if (key !== 'tab') newUrl += '&' + key + '=' + encodeURIComponent(value);
        }
        window.history.pushState({}, document.title, newUrl);

        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = 1;
            HeaderPagination.load();
        }
    }

    function updateOrdersList(orders) {
        const tbody = document.querySelector('.admin-table.order-manage tbody');
        if (tbody) {
            tbody.innerHTML = '';
            if (orders.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td></tr>';
                return;
            }
            window._ordersCache = {};
            orders.forEach(order => {
                window._ordersCache[order.id] = order;
                const row = document.createElement('tr');
                const goodsName = getGoodsName(order.goods_info);
                const shipVal = (order.shipping_status === undefined || order.shipping_status === null || order.shipping_status === '') ? '0' : String(order.shipping_status);
                
                let orderTime = '-';
                if (order.created_at) {
                    const date = new Date(order.created_at);
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    orderTime = `${year}-${month}-${day} ${hours}:${minutes}`;
                }
                
                let payType = order.pay_type || '';
                let payTagHtml = getPayTagHtml(payType);

                row.innerHTML = `
                <td>${order.id}</td>
                <td>${orderTime}</td>
                <td>${escapeHtml(order.type || '')}</td>
                <td>${payTagHtml}</td>
                <td>${escapeHtml(order.order_no)}</td>
                <td><span class="goods-name-cell">${escapeHtml(goodsName)}</span></td>
                <td class="text-right">¥${parseFloat(order.amount).toFixed(2)}</td>
                <td>
                    <select class="form-control shipping-status-select status-${shipVal}" style="width:55px;height:28px;padding:4px 6px;font-size:12px;" onchange="updateShippingStatus(${order.id}, this.value)">
                        <option value="0" ${shipVal === '0' ? 'selected' : ''}>未发货</option>
                        <option value="1" ${shipVal === '1' ? 'selected' : ''}>已发货</option>
                    </select>
                </td>
                <td class="text-right">
                    <button type="button" class="btn btn-sm btn-secondary" data-order='${escapeHtml(JSON.stringify(order))}' onclick="showOrderDetailsBtn(this)">详情</button>
                    <button type="button" onclick="deleteOrder(${order.id}, '')" class="btn btn-sm btn-danger">删除</button>
                </td>
            `;
                tbody.appendChild(row);
            });
        }
    }

    function getGoodsName(info) {
        if (!info) return '';
        if (typeof info === 'object' && info !== null) {
            if (info.name) return String(info.name);
            try {
                info = JSON.stringify(info);
            } catch (e) {
                info = String(info);
            }
        }
        let s = String(info).trim();
        try {
            const div = document.createElement('div');
            div.innerHTML = s;
            s = div.textContent || s;
        } catch (e) {}
        try {
            const obj = JSON.parse(s);
            if (obj && obj.name) return String(obj.name);
        } catch (e) {}
        const m1 = s.match(/"name"\s*:\s*"([^"]+)"/);
        if (m1) return m1[1];
        const m2 = s.match(/'name'\s*:\s*'([^']+)'/);
        if (m2) return m2[1];
        return s.slice(0, 80);
    }

    function showOrderDetailsBtn(el) {
        const data = el.getAttribute('data-order') || '';
        let order = null;
        try {
            order = JSON.parse(data);
        } catch (e) {}
        if (!order && el && el.closest('tr')) {
            const idCell = el.closest('tr').querySelector('td:first-child');
            const id = idCell ? parseInt(idCell.textContent.trim()) : 0;
            order = window._ordersCache ? window._ordersCache[id] : null;
        }
        if (!order) return;
        showOrderDetails(order);
    }

    function showOrderDetails(order) {
        const modal = document.getElementById('order-detail-modal');
        const body = document.getElementById('order-detail-body');
        if (!modal || !body) return;
        const goodsName = getGoodsName(order.goods_info);
        const typeVal = (order.type || '').trim();
        const isGoods = typeVal === '商品类';
        const isPoints = typeVal === '积分类' || typeVal === '积分充值';
        const isToolOrRes = typeVal === '工具类' || typeVal === '资源类';
        const rows = [];
        rows.push(['类型', order.type || '']);
        rows.push(['订单号', order.order_no]);
        rows.push(['商品名称', goodsName]);
        if (isGoods) {
            rows.push(['收货地址', order.address || '无']);
            rows.push(['留言', order.message || '无']);
        }
        rows.push(['用户名（ID）', (order.username || '') + '（' + String(order.user_id || '') + '）']);
        rows.push(['支付方式', order.pay_type || '']);
        rows.push(['金额', '¥' + (parseFloat(order.amount).toFixed(2))]);
        if (isPoints) {
            rows.push(['积分', String(order.points || 0)]);
        }
        if (isGoods) {
            rows.push(['商品ID', String(order.goods_id || 0)]);
        }
        rows.push(['付款时间', order.pay_time || '']);
        let html = '';
        for (let i = 0; i < rows.length; i++) {
            const label = rows[i][0] === null || rows[i][0] === undefined ? '' : String(rows[i][0]);
            const value = rows[i][1] === null || rows[i][1] === undefined ? '' : String(rows[i][1]);
            const showCopy = label === '商品名称' || label === '订单号' || label === '用户名' || label === '用户名（ID）' || label === '收货地址' || label === '留言';
            const copyBtn = showCopy ? `<button type="button" class="btn btn-sm btn-secondary detail-copy-btn" data-copy="${encodeURIComponent(value)}" onclick="copyDetailRow(this)">复制</button>` : '';
            html += `<div class="detail-row"><span class="detail-label">${escapeHtml(label)}</span><span class="detail-value">${escapeHtml(value)}</span><span class="detail-actions">${copyBtn}</span></div>`;
        }
        body.innerHTML = html;
        modal.classList.add('modal-visible');
    }

    function closeOrderDetailModal() {
        const modal = document.getElementById('order-detail-modal');
        if (modal) {
            modal.classList.remove('modal-visible');
        }
    }

    function renderOrdersList(pageData) {
        const d = pageData && (pageData.data || pageData) || {};
        let list = d.orders || [];
        const filterSelect = document.getElementById('order-filter');
        const currentFilter = filterSelect ? filterSelect.value : '';
        if (currentFilter) {
            list = list.filter(function(order) {
                const type = (order.type || '').trim();
                const payType = (order.pay_type || '').trim();
                const shippingStatus = order.shipping_status || 0;
                switch (currentFilter) {
                    case 'wechat':
                        return payType === '微信';
                    case 'alipay':
                        return payType === '支付宝';
                    case 'shipped':
                        return shippingStatus === 1;
                    case 'unshipped':
                        return shippingStatus === 0;
                    case 'points':
                        return type === '积分类' || type === '积分充值';
                    case 'resource':
                        return type === '资源类';
                    case 'tool':
                        return type === '工具类';
                    case 'goods':
                        return type === '商品类';
                    default:
                        return true;
                }
            });
        }
        updateOrdersList(list);
        if (d.total_amount !== undefined) {
            const totalAmountElement = document.querySelector('.order-total-amount');
            if (totalAmountElement) {
                totalAmountElement.textContent = ' 总销售额: ¥' + parseFloat(d.total_amount).toFixed(2) + ' ';
            }
        }
    }

    function escapeHtml(text) {
        if (text === null || text === undefined) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function copyDetailRow(btn) {
        const encoded = btn ? (btn.getAttribute('data-copy') || '') : '';
        let text = '';
        try {
            text = decodeURIComponent(encoded);
        } catch (e) {
            text = encoded;
        }
        const toast = function(ok) {
            if (typeof showToast === 'function') showToast(ok ? '已复制' : '复制失败', ok ? 'info' : 'error', 1500);
        };
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(function() {
                toast(true);
            }).catch(function() {
                toast(false);
            });
            return;
        }
        try {
            const ta = document.createElement('textarea');
            ta.value = text;
            ta.style.position = 'fixed';
            ta.style.left = '-9999px';
            ta.style.top = '-9999px';
            document.body.appendChild(ta);
            ta.focus();
            ta.select();
            const ok = document.execCommand('copy');
            document.body.removeChild(ta);
            toast(!!ok);
        } catch (e) {
            toast(false);
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        const urlParams = new URLSearchParams(window.location.search);
        const filter = urlParams.get('filter') || '';
        const timeRange = urlParams.get('time_range') || '';

        if (filter) {
            const filterSelect = document.getElementById('order-filter');
            if (filterSelect) filterSelect.value = filter;
        }

        if (timeRange) {
            const timeRangeSelect = document.getElementById('time-range');
            if (timeRangeSelect) timeRangeSelect.value = timeRange;
        }

        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = <?php echo $page; ?>;
            HeaderPagination.state.pageSize = <?php echo $posts_per_page; ?>;
            HeaderPagination.state.total = <?php echo $total_orders ?? 0; ?>;
            HeaderPagination.state.totalPages = <?php echo $total_pages ?? 1; ?>;

            HeaderPagination.cache.page = <?php echo $page; ?>;
            HeaderPagination.cache.pageSize = <?php echo $posts_per_page; ?>;
            HeaderPagination.cache.totalPages = <?php echo $total_pages ?? 1; ?>;

            HeaderPagination.init();
            HeaderPagination.updateUI();
        }
    });
</script>

<style>
    .action-buttons {
        display: flex;
        align-items: center;
        gap: 20px;
        flex-wrap: wrap;
    }

    .time-filter {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-right: 0px;
        width: 100px;
    }

    .order-filter {
        display: flex;
        align-items: center;
        width: 100px;
    }

    .time-filter select,
    .order-filter select {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        background-color: #fff;
        height: 36px;
        margin: 0;
        box-sizing: border-box;
        width: 100%;
        min-width: 100px;
    }



    .order-total-amount {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        height: 46px;
        padding: 0 18px;
        margin-right: 0px;
        border-radius: 5px;
        background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
        border: 1px solid #f59e0b;
        color: #92400e;
        font-size: 15px;
        font-weight: 600;
        white-space: nowrap;
        box-shadow: 0 2px 6px rgba(245, 158, 11, 0.15);
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }
    .order-total-amount:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 10px rgba(245, 158, 11, 0.25);
    }
    .order-total-amount svg {
        flex-shrink: 0;
    }
    .order-total-amount .amount-value {
        font-family: Consolas, 'Courier New', monospace;
        font-size: 17px;
        font-weight: 700;
        letter-spacing: 0.5px;
    }

    @media (max-width: 768px) {
        .section-header:has(.action-buttons) {
            flex-wrap: nowrap;
            gap: 10px;
            align-items: center;
        }

        .section-header:has(.action-buttons) h2 {
            flex-shrink: 0;
            white-space: nowrap;
            font-size: 16px;
        }

        .action-buttons {
            position: relative;
            width: auto;
            justify-content: flex-end;
            flex-wrap: nowrap;
            gap: 20px;
        }

        .action-buttons .time-filter,
        .action-buttons .order-filter {
            width: auto;
            max-width: none;
            margin-bottom: 0;
        }

        .action-buttons .time-filter select,
        .action-buttons .order-filter select {
            width: auto;
            min-width: 80px;
            padding: 6px 8px;
            font-size: 13px;
            height: 32px;
        }

        .action-buttons .order-total-amount {
            display: none !important;
        }

        .action-buttons .clear-all-btn,
        .action-buttons .btn.action-button.clear-all-btn {
            display: none !important;
        }
    }

    .admin-table.order-manage th:first-child,
    .admin-table.order-manage td:first-child {
        width: 80px !important;
        min-width: 80px !important;
        max-width: 80px !important;
    }


    
    .admin-table.order-manage select.shipping-status-select.status-0 {
        background-color: #ffece8 !important;
        border: 1px solid #ffcdd2 !important;
        color: #c62828 !important;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23c62828' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E") !important;
    }

    .admin-table.order-manage select.shipping-status-select.status-1 {
        background-color: #e8f5e8 !important;
        border: 1px solid #c8e6c9 !important;
        color: #2e7d32 !important;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%232e7d32' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E") !important;
    }

    .admin-table.order-manage select.shipping-status-select option {
        background-color: #ffffff !important;
        color: #333333 !important;
        font-weight: normal !important;
    }

    .admin-table.order-manage select.shipping-status-select:focus {
        outline: none !important;
    }

    .admin-table.order-manage th,
    .admin-table.order-manage td {
        height: 45px !important;
        line-height: 45px !important;
        padding: 0 20px !important;
        white-space: nowrap !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        box-sizing: border-box !important;
    }

    .admin-table.order-manage thead tr,
    .admin-table.order-manage tbody tr {
        height: 75px !important;
    }

    .goods-name-cell {
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        color: var(--text);
    }

    .detail-row {
        display: grid;
        grid-template-columns: 120px 1fr 70px;
        align-items: flex-start;
        padding: 8px 0;
        border-bottom: 1px solid #eee;
        column-gap: 15px;
    }

    .detail-row:last-child {
        border-bottom: none;
    }

    .detail-label {
        color: #64748b;
        font-size: 14px;
        text-align: left;
    }

    .detail-value {
        color: #334155;
        font-size: 14px;
        text-align: left;
        overflow-wrap: anywhere;
        word-break: break-word;
        white-space: pre-wrap;
        line-height: 1.4;
    }

    .detail-actions {
        text-align: left;
    }

    .detail-copy-btn {
        padding: 2px 12px !important;
        height: 24px;
        line-height: 20px !important;
        font-size: 12px !important;
        min-width: 44px;
        white-space: nowrap;
        background: #f1f5f9 !important;
        border: 1px solid #e2e8f0 !important;
        color: #64748b !important;
        box-shadow: none !important;
    }

    .detail-copy-btn:hover {
        background: #e2e8f0 !important;
        border-color: #cbd5e1 !important;
        color: #475569 !important;
    }

    .detail-copy-btn:disabled {
        opacity: 0.9 !important;
        cursor: default !important;
    }

    #order-detail-modal .modal-content {
        max-width: 600px !important;
        max-height: 460px !important;
        height: 460px !important;
        overflow: hidden !important;
        display: flex !important;
        flex-direction: column !important;
    }

    #order-detail-modal .modal-header {
        flex: 0 0 auto !important;
    }

    #order-detail-modal .modal-body {
        flex: 1 1 auto !important;
        overflow-y: auto !important;
    }

    .audit-header-wrap {
        position: relative;
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
    }

    #time-header.audit-header-trigger,
    #type-header.audit-header-trigger,
    #pay-header.audit-header-trigger,
    #status-header.audit-header-trigger {
        display: inline-flex;
        align-items: center;
        position: relative;
        padding-right: 30px;
        cursor: pointer;
        font-weight: 600;
    }

    #time-header.audit-header-trigger::after,
    #type-header.audit-header-trigger::after,
    #pay-header.audit-header-trigger::after,
    #status-header.audit-header-trigger::after {
        content: '';
        position: absolute;
        right: 6px;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        height: 16px;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23666' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 16px;
        pointer-events: none;
    }

    #time-dropdown-menu,
    #type-dropdown-menu,
    #pay-dropdown-menu,
    #status-dropdown-menu {
        border: 1px solid #ddd;
        border-radius: 0px;
        background-color: #fff;
        box-shadow: none;
        max-height: 300px;
        overflow-y: auto;
        padding: 0;
        width: 125px;
        display: none !important;
    }

    #time-dropdown-menu .time-dropdown-item,
    #type-dropdown-menu .type-dropdown-item,
    #pay-dropdown-menu .pay-dropdown-item,
    #status-dropdown-menu .status-dropdown-item {
        height: 30px;
        line-height: 30px;
        padding: 0 10px;
        font-size: 14px;
        cursor: pointer;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #333;
    }

    #time-dropdown-menu .time-dropdown-item:hover,
    #type-dropdown-menu .type-dropdown-item:hover,
    #pay-dropdown-menu .pay-dropdown-item:hover,
    #status-dropdown-menu .status-dropdown-item:hover {
        background-color: var(--primary-color);
        color: #fff;
    }

    /* 手机端下拉框高度调整 */
    @media (max-width: 768px) {
        #time-range,
        #order-filter {
            height: 38px !important;
            line-height: 38px !important;
        }
        
        /* 确保清空订单按钮在手机端显示 - 使用最高优先级 */
        body .section-header .clear-all-btn,
        body .section-header .clear-all-btn.section-header-mobile-btn,
        body .section-header .section-header-mobile-btn {
            display: inline-flex !important;
            width: 38px !important;
            height: 38px !important;
            min-width: 38px !important;
            padding: 0 !important;
            line-height: 38px !important;
            visibility: visible !important;
        }
        body .section-header .clear-all-btn span,
        body .section-header .section-header-mobile-btn .section-header-btn-text {
            display: none !important;
        }
        body .section-header .clear-all-btn svg,
        body .section-header .section-header-mobile-btn .section-header-btn-icon {
            margin-right: 0 !important;
        }
    }
</style>

<div class="section-header">
    <h2>订单管理</h2>
    <div class="action-buttons">
        <div class="order-total-amount"> 总销售额: ¥<?php echo number_format($total_amount, 2); ?> </div>
        <button type="button" id="order-page-clear-btn" onclick="clearAllOrders();" class="btn btn-danger action-button clear-all-btn section-header-mobile-btn" style="width: 128px; display: inline-flex; align-items: center; justify-content: center; margin-left: 0; margin-right: 0;">
          <svg class="section-header-btn-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
            <path d="M3 6h18"></path>
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
            <line x1="10" y1="11" x2="10" y2="17"></line>
            <line x1="14" y1="11" x2="14" y2="17"></line>
          </svg>
          <span class="section-header-btn-text">清空订单</span>
        </button>
    </div>
</div>

<style>
@media (max-width: 768px) {
    /* 强制清空订单按钮在手机端显示 */
    #order-page-clear-btn {
        display: inline-flex !important;
        width: 38px !important;
        height: 38px !important;
        min-width: 38px !important;
        padding: 0 !important;
        line-height: 38px !important;
        visibility: visible !important;
    }
    #order-page-clear-btn span {
        display: none !important;
    }
    #order-page-clear-btn svg {
        margin-right: 0 !important;
    }
}
</style>
<style>
/* 订单表格样式调整 */
.admin-table.order-manage th,
.admin-table.order-manage td {
    text-align: left !important;
}
.admin-table.order-manage th.text-right,
.admin-table.order-manage td.text-right {
    text-align: right !important;
}
/* 只保留一套样式 - 使用 id 选择器最高优先级 */
#order-page-table th:nth-child(1),
#order-page-table td:nth-child(1) { width: 60px !important; min-width: 60px !important; max-width: 60px !important; }
#order-page-table th:nth-child(2),
#order-page-table td:nth-child(2) { width: 160px !important; min-width: 160px !important; max-width: 160px !important; white-space: nowrap; }
#order-page-table th:nth-child(3),
#order-page-table td:nth-child(3) { width: 100px !important; min-width: 100px !important; max-width: 100px !important; }
#order-page-table th:nth-child(4),
#order-page-table td:nth-child(4) { width:100px !important; min-width: 100px !important; max-width: 100px !important; }
#order-page-table th:nth-child(5),
#order-page-table td:nth-child(5) { width: 180px !important; min-width:180px !important; max-width: 180px !important; }
#order-page-table th:nth-child(6),
#order-page-table td:nth-child(6) { width: auto !important; }
#order-page-table th:nth-child(7),
#order-page-table td:nth-child(7) { width: 100px !important; min-width: 100px !important; max-width: 100px !important; text-align: left !important; }
#order-page-table th:nth-child(8),
#order-page-table td:nth-child(8) { width: 125px !important; min-width: 125px !important; max-width: 125px !important; text-align: left !important; }
#order-page-table th:nth-child(9),
#order-page-table td:nth-child(9) { width: 160px !important; min-width: 160px !important; max-width: 160px !important; }

/* 支付类型标签样式 */
.pay-type-tag {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0 8px;
    height: 24px;
    line-height: 1;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}
.pay-type-tag-default {
    background-color: #f5f5f5;
    color: #666;
    border: 1px solid rgba(100,116,139,0.25);
}
</style>
<div class="admin-card">
    <div class="table-container">
        <table id="order-page-table" class="admin-table order-manage">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>
                        <div class="audit-header-wrap">
                            <span id="time-header" class="audit-header-trigger" onclick="toggleTimeMenu()">时间</span>
                        </div>
                    </th>
                    <th>
                        <div class="audit-header-wrap">
                            <span id="type-header" class="audit-header-trigger" onclick="toggleTypeMenu()">类型</span>
                        </div>
                    </th>
                    <th>
                        <div class="audit-header-wrap">
                            <span id="pay-header" class="audit-header-trigger" onclick="togglePayMenu()">支付</span>
                        </div>
                    </th>
                    <th>订单号</th>
                    <th>商品名称</th>
                    <th>价格</th>
                    <th>
                        <div class="audit-header-wrap">
                            <span id="status-header" class="audit-header-trigger" onclick="toggleStatusMenu()">状态</span>
                        </div>
                    </th>
                    <th class="text-right">操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($orders)): ?>
                    <tr><td colspan="9" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td></tr>
                <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                        <?php
                        $payType = !empty($order['pay_type']) ? $order['pay_type'] : '';
                        $payTagStyle = isset($payTypeStyleMap[$payType]) ? $payTypeStyleMap[$payType] : null;
                        ?>
                        <tr>
                            <td><?php echo $order['id']; ?></td>
                            <td><?php echo !empty($order['created_at']) ? date('Y-m-d H:i', strtotime($order['created_at'])) : '-'; ?></td>
                            <td><?php echo htmlspecialchars($order['type'] ?? ''); ?></td>
                            <td>
                                <?php if ($payType): ?>
                                    <?php if (is_array($payTagStyle)): ?>
                                        <span class="pay-type-tag" style="background-color:<?php echo htmlspecialchars($payTagStyle['bg'] ?? '', ENT_QUOTES); ?>;color:<?php echo htmlspecialchars($payTagStyle['color'] ?? '', ENT_QUOTES); ?>;border:1px solid <?php echo htmlspecialchars($payTagStyle['border'] ?? '', ENT_QUOTES); ?>;"><?php echo htmlspecialchars($payType); ?></span>
                                    <?php else: ?>
                                        <span class="pay-type-tag pay-type-tag-default"><?php echo htmlspecialchars($payType); ?></span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($order['order_no']); ?></td>
                            <td>
                                <span class="goods-name-cell">
                                    <?php
                                    $goodsName = '';
                                    if (!empty($order['goods_info'])) {
                                        $decoded = json_decode($order['goods_info'], true);
                                        if (is_array($decoded) && isset($decoded['name'])) $goodsName = $decoded['name'];
                                        else $goodsName = $order['goods_info'];
                                    }
                                    echo htmlspecialchars(mb_substr($goodsName, 0, 80, 'utf-8'));
                                    ?>
                                </span>
                            </td>
                            <td class="text-right">¥<?php echo number_format($order['amount'], 2); ?></td>
                            <td>
                                <?php $shipping_status = isset($order['shipping_status']) ? intval($order['shipping_status']) : 0; ?>
                                <select class="form-control shipping-status-select status-<?php echo $shipping_status; ?>" style="width:55px;height:28px;padding:4px 6px;font-size:12px;" onchange="updateShippingStatus(<?php echo intval($order['id']); ?>, this.value)">
                                    <option value="0" <?php echo $shipping_status === 0 ? 'selected' : ''; ?>>未发货</option>
                                    <option value="1" <?php echo $shipping_status === 1 ? 'selected' : ''; ?>>已发货</option>
                                </select>
                            </td>
                            <td class="text-right">
                                <button type="button" class="btn btn-sm btn-secondary" data-order='<?php echo htmlspecialchars(json_encode($order), ENT_QUOTES); ?>' onclick="showOrderDetailsBtn(this)">详情</button>
                                <button type="button" onclick="deleteOrder(<?php echo $order['id']; ?>, '<?php echo !empty($search_query) ? htmlspecialchars($search_query) : ''; ?>');" class="btn btn-sm btn-danger">删除</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="order-detail-modal" class="modal">
    <div class="modal-backdrop" onclick="closeOrderDetailModal()"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">订单详情</h3>
            <button type="button" class="modal-close" onclick="closeOrderDetailModal()">×</button>
        </div>
        <div class="modal-body" id="order-detail-body"></div>
    </div>
</div>

<div id="time-dropdown-menu" style="display: none;">
    <div class="time-dropdown-item" onclick="filterTime('')">全部</div>
    <div class="time-dropdown-item" onclick="filterTime('today')">1天内</div>
    <div class="time-dropdown-item" onclick="filterTime('yesterday')">昨天</div>
    <div class="time-dropdown-item" onclick="filterTime('this_month')">一个月</div>
    <div class="time-dropdown-item" onclick="filterTime('three_months')">3个月</div>
    <div class="time-dropdown-item" onclick="filterTime('this_year')">一年</div>
</div>

<div id="type-dropdown-menu" style="display: none;">
    <div class="type-dropdown-item" onclick="filterType('')">全部</div>
    <div class="type-dropdown-item" onclick="filterType('积分类')">积分类</div>
    <div class="type-dropdown-item" onclick="filterType('资源类')">资源类</div>
    <div class="type-dropdown-item" onclick="filterType('工具类')">工具类</div>
    <div class="type-dropdown-item" onclick="filterType('商品类')">商品类</div>
</div>

<div id="pay-dropdown-menu" style="display: none;">
    <div class="pay-dropdown-item" onclick="filterPay('')">全部</div>
    <div class="pay-dropdown-item" onclick="filterPay('微信')">微信</div>
    <div class="pay-dropdown-item" onclick="filterPay('支付宝')">支付宝</div>
</div>

<div id="status-dropdown-menu" style="display: none;">
    <div class="status-dropdown-item" onclick="filterStatus('')">全部</div>
    <div class="status-dropdown-item" onclick="filterStatus('unshipped')">未发货</div>
    <div class="status-dropdown-item" onclick="filterStatus('shipped')">已发货</div>
</div>
