(function ($) {
    $.fn.smartDropdown = function (options) {
        // 配置参数
        const CONFIG = {
            grid: {
                pageNo: 1,
                pageRows: 5
            }
        }
        const settings = $.extend({
            url: '',
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            hiddenId: '',
            valueField: '',
            textField: '',
            placeholder: '请选择',
            searchPlaceholder: '请输入搜索关键字...',
            minSearchLength: 1,
            searchDelay: 300,
            pageSize: 5,
            params: {},
            onSelect: null,
            onLoad: null,
            formatResult: null,
            formatPagination: null
        }, options);

        //抽取的公共方法
        return this.each(function () {
            const $container = $(this);
            //默认当前页
            let currentPage = 1;

            // 初始化结构
            $container.addClass('smart-dropdown');
            $container.html(`
                <input type="text" class="smart-dropdown-input" readonly placeholder="${settings.placeholder}">
                <div class="smart-dropdown-arrow">▼</div>
                <div class="smart-dropdown-menu">
                    <div class="smart-dropdown-search">
                        <input type="text" class="smart-search-input" placeholder="${settings.searchPlaceholder}">
                    </div>
                    <div class="smart-dropdown-content"></div>
                    <div class="smart-dropdown-pagination">
                        <div class="smart-pagination-info"></div>
                        <div class="smart-pagination-controls">
                            <button class="smart-page-prev">上一页</button>
                            <button class="smart-page-next">下一页</button>
                        </div>
                    </div>
                </div>
            `);
            //缓存选择器
            const $input = $container.find('.smart-dropdown-input');
            const $arrow = $container.find('.smart-dropdown-arrow');
            const $menu = $container.find('.smart-dropdown-menu');
            const $searchInput = $container.find('.smart-search-input');
            const $content = $container.find('.smart-dropdown-content');
            const $prevBtn = $container.find('.smart-page-prev');
            const $nextBtn = $container.find('.smart-page-next');
            const $paginationInfo = $container.find('.smart-pagination-info');

            // 显示/隐藏下拉菜单
            // 点击输入框时显示对应的自定义div
            $input.click(function () {
                $menu.css('display', 'block');
                initInfo();
            });
            //点击其它区域时关闭下拉框
            $(document).click(function (event) {
                if (!$(event.target).closest('.smart-dropdown').length) {
                    $menu.css('display', 'none');
                }
            });

            // 显示错误信息
            function showError(title, msg) {
                layer.msg(msg || '操作失败', {icon: 2});
            }

            //初始化信息
            function initInfo() {
                var requestData = $.extend({
                    searchKey: $searchInput.val()
                }, CONFIG.grid);
                $.ajax({
                    url: settings.url,
                    type: settings.method,
                    dataType: settings.dataType,
                    contentType: settings.contentType,
                    data: JSON.stringify(requestData),
                    success: function (res) {
                        if (res.code === 200) {
                            setInfo(res.data);
                        } else {
                            showError("加载失败", res.msg);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error("请求失败:", error);
                        showError("请求失败", "网络错误或服务器异常");
                    }
                });
            }

            //渲染列表
            function setInfo(data) {
                const items = data.dataList || [];
                const pageCount = data.pageCount || 1;
                const totalRows = data.totalRows || 0;
                const currentRows = items.length;


                // 渲染列表项
                let html = '';
                if (items.length > 0) {
                    items.forEach(function (item) {
                        const valueField = settings.valueField;
                        const textField = settings.textField;
                        const value = item[valueField];
                        const text = item[textField];
                        let itemHtml = '';
                        itemHtml = `<div class="smart-dropdown-item" 
                                          data-value="${value}" 
                                          data-text="${text}">${text}</div>`;
                        html += itemHtml;
                    });
                } else {
                    html = '<div class="loading">暂无数据</div>';
                }
                $content.html(html);

                // 渲染分页信息
                let paginationText = '';
                const start = (currentPage - 1) * data.pageRows + 1;
                const end = start + currentRows - 1;
                paginationText = `第${start}-${end}条,共${totalRows}条`;

                $paginationInfo.text(paginationText);

                // 更新分页按钮状态
                $prevBtn.prop('disabled', currentPage <= 1);
                $nextBtn.prop('disabled', currentPage >= pageCount);
            }

            //选择
            $content.on('click', '.smart-dropdown-item', function () {
                const value = $(this).data('value');
                const text = $(this).data('text');
                selectItem(value, text);
            });

            // 选择项
            function selectItem(value, text) {
                $input.val(text)
                $searchInput.val("");
                $menu.css('display', 'none');
                $('#'+settings.hiddenId).val(value);
            }

            //实时搜索
            $searchInput.on('input', function () {
                initInfo();
            });
            //上一页
            $prevBtn.click(function () {
                CONFIG.grid.pageNo = currentPage - 1;
                currentPage = currentPage - 1;
                initInfo();
            })
            //下一页
            $nextBtn.click(function () {
                CONFIG.grid.pageNo = currentPage + 1;
                currentPage = currentPage + 1;
                initInfo();
            })
        });
    };
})(jQuery);