$(document).ready(function() {
    // 示例数据 - 国家
    const countries = [];
    // 初始化下拉框控件
    function initDropdown(dropdownId, data, selectedIdDisplay, selectedNameDisplay) {
        const $dropdown = $(`#${dropdownId}`);
        const $toggle = $dropdown.find('.dropdown-toggle');
        const $menu = $dropdown.find('.dropdown-menu');
        const $itemsContainer = $dropdown.find('.dropdown-items');
        const $searchInput = $dropdown.find('.search-input');
        const $prevBtn = $dropdown.find('.prev-btn');
        const $nextBtn = $dropdown.find('.next-btn');
        const $currentPage = $dropdown.find('.current-page');
        const $totalPages = $dropdown.find('.total-pages');
        const $hiddenInput = $dropdown.find('input[type="hidden"]');
        const $placeholder = $dropdown.find('.placeholder');

        let currentPage = 1;
        let itemsPerPage = 5;
        let filteredData = [...data];
        let searchTerm = '';
        let selectedItem = null;

        // 渲染选项
        function renderItems() {
            $itemsContainer.empty();

            // 计算分页
            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const pageData = filteredData.slice(startIndex, endIndex);

            // 如果没有数据
            if (pageData.length === 0) {
                $itemsContainer.append('<div class="dropdown-item" style="text-align: center; color: #95a5a6;">没有找到匹配的选项</div>');
                return;
            }

            // 渲染当前页的选项
            pageData.forEach(item => {
                const isSelected = selectedItem && selectedItem.id === item.id;
                const $item = $(`
                            <div class="dropdown-item ${isSelected ? 'selected' : ''}" data-id="${item.id}">
                                ${item.name}
                            </div>
                        `);

                $itemsContainer.append($item);
            });

            // 更新分页信息
            const totalPages = Math.ceil(filteredData.length / itemsPerPage);
            $currentPage.text(currentPage);
            $totalPages.text(totalPages);

            // 更新分页按钮状态
            $prevBtn.prop('disabled', currentPage === 1);
            $nextBtn.prop('disabled', currentPage === totalPages || totalPages === 0);

            // 如果没有数据，隐藏分页
            $dropdown.find('.dropdown-footer').toggle(filteredData.length > 0);
        }

        // 搜索过滤
        function filterItems() {
            searchTerm = $searchInput.val().toLowerCase();

            if (searchTerm) {
                filteredData = data.filter(item =>
                    item.name.toLowerCase().includes(searchTerm)
                );
            } else {
                filteredData = [...data];
            }

            currentPage = 1; // 重置到第一页
            renderItems();
        }

        // 选择选项
        function selectItem(item) {
            selectedItem = item;
            $hiddenInput.val(item.id);
            $placeholder.text(item.name).removeClass('placeholder');

            // 更新显示
            $(selectedIdDisplay).text(item.id);
            $(selectedNameDisplay).text(item.name);

            // 关闭下拉菜单
            $menu.hide();
            $toggle.removeClass('active');

            // 重新渲染以更新选中状态
            renderItems();
        }

        // 清除选择
        function clearSelection() {
            selectedItem = null;
            $hiddenInput.val('');
            $placeholder.text('请选择一个选项').addClass('placeholder');

            // 更新显示
            $(selectedIdDisplay).text('未选择');
            $(selectedNameDisplay).text('未选择');

            // 重新渲染
            renderItems();
        }

        // 初始化
        renderItems();

        // 事件绑定
        $toggle.on('click', function(e) {
            e.stopPropagation();
            $menu.toggle();
            $toggle.toggleClass('active');

            // 如果展开，聚焦搜索框
            if ($menu.is(':visible')) {
                setTimeout(() => $searchInput.focus(), 10);
            }
        });

        $searchInput.on('input', function() {
            filterItems();
        });

        $itemsContainer.on('click', '.dropdown-item', function() {
            const id = parseInt($(this).data('id'));
            const item = data.find(d => d.id === id);
            if (item) {
                selectItem(item);
            }
        });

        $prevBtn.on('click', function() {
            if (currentPage > 1) {
                currentPage--;
                renderItems();
            }
        });

        $nextBtn.on('click', function() {
            const totalPages = Math.ceil(filteredData.length / itemsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                renderItems();
            }
        });

        // 点击页面其他地方关闭下拉菜单
        $(document).on('click', function(e) {
            if (!$dropdown.is(e.target) && $dropdown.has(e.target).length === 0) {
                $menu.hide();
                $toggle.removeClass('active');
            }
        });

        // 防止下拉菜单内部点击事件冒泡到document
        $menu.on('click', function(e) {
            e.stopPropagation();
        });

        // 返回清除选择的方法，以便外部调用
        return {
            clearSelection: clearSelection,
            setSelection: function(id) {
                const item = data.find(d => d.id === id);
                if (item) {
                    selectItem(item);
                }
            }
        };
    }

    // 初始化两个下拉框
    const countryDropdown = initDropdown(
        'country-dropdown',
        countries,
        '#selected-id-display',
        '#selected-country-name'
    );
});