/**
 * Select渲染器
 */
class SelectRenderer {
    constructor(config = {}) {
        this.config = $.extend({
            placeholder: true,
            placeholderText: '请选择',
            allowClear: false,
            searchable: false,
            ajax: false,
            data: [],
            valueField: 'value',
            textField: 'text',
            disabledField: 'disabled',
            selectedField: 'selected',
            groupField: 'group'
        }, config);
    }

    /**
     * 渲染单个select
     * @param {jQuery|string} selector - 选择器或jQuery对象
     * @param {Array|Object} data - 数据
     * @param {Object} options - 选项
     */
    render(selector, data = null, options = {}) {
        var $select = $(selector);
        if (!$select.length) return;

        var config = $.extend({}, this.config, options);
        var renderData = data || config.data;

        // 清空现有选项
        $select.empty();

        // 添加占位符
        if (config.placeholder) {
            var $placeholder = $('<option>', {
                value: '',
                text: config.placeholderText
            });

            if (config.allowClear) {
                $placeholder.attr('data-allow-clear', 'true');
            }

            $select.append($placeholder);
        }

        // 渲染选项
        if ($.isArray(renderData)) {
            this._renderOptions($select, renderData, config);
        } else if (renderData && renderData.url) {
            this._renderWithAjax($select, renderData, config);
        }

        // 触发渲染完成事件
        $select.trigger('select:rendered');

        return $select;
    }

    /**
     * 渲染多个select
     * @param {string} className - 类选择器
     * @param {Array} data - 数据
     * @param {Object} options - 选项
     */
    renderAll(className, data = null, options = {}) {
        var self = this;
        var results = [];

        $(className).each(function() {
            var $select = $(this);
            var specificOptions = $.extend({}, options);

            // 从data-*属性读取配置
            var dataAttrs = self._getDataAttributes($select);
            $.extend(specificOptions, dataAttrs);

            results.push(self.render($select, data, specificOptions));
        });

        return results;
    }

    /**
     * 内部方法：渲染选项
     */
    _renderOptions($select, data, config) {
        var groups = {};

        $.each(data, function(index, item) {
            // 分组处理
            if (config.groupField && item[config.groupField]) {
                var groupName = item[config.groupField];
                if (!groups[groupName]) {
                    groups[groupName] = [];
                }
                groups[groupName].push(item);
            } else {
                var $option = $('<option>', {
                    value: item[config.valueField] || item.value || '',
                    text: item[config.textField] || item.text || '',
                    disabled: item[config.disabledField] || item.disabled || false,
                    selected: item[config.selectedField] || item.selected || false
                });

                // 添加自定义属性
                $.each(item, function(key, value) {
                    if (!['value', 'text', 'disabled', 'selected'].includes(key)) {
                        $option.attr('data-' + key, value);
                    }
                });

                $select.append($option);
            }
        });

        // 渲染分组
        this._renderOptionGroups($select, groups, config);
    }

    /**
     * 内部方法：渲染分组
     */
    _renderOptionGroups($select, groups, config) {
        $.each(groups, function(groupName, items) {
            var $optgroup = $('<optgroup>', {
                label: groupName
            });

            $.each(items, function(index, item) {
                var $option = $('<option>', {
                    value: item[config.valueField] || item.value || '',
                    text: item[config.textField] || item.text || '',
                    disabled: item[config.disabledField] || item.disabled || false,
                    selected: item[config.selectedField] || item.selected || false
                });

                $optgroup.append($option);
            });

            $select.append($optgroup);
        });
    }

    /**
     * 内部方法：通过AJAX渲染
     */
    _renderWithAjax($select, ajaxConfig, config) {
        var self = this;

        // 显示加载状态
        $select.prop('disabled', true).addClass('loading');

        $.ajax($.extend({
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                // 处理响应数据
                var data = response;
                if (ajaxConfig.dataProcessor && typeof ajaxConfig.dataProcessor === 'function') {
                    data = ajaxConfig.dataProcessor(response);
                } else if (response.data) {
                    data = response.data;
                }

                // 渲染数据
                self._renderOptions($select, data, config);

                // 恢复select状态
                $select.prop('disabled', false).removeClass('loading');

                // 触发完成事件
                $select.trigger('select:ajax:complete', [response]);
            },
            error: function(xhr, status, error) {
                console.error('加载下拉框数据失败:', error);

                // 添加错误选项
                $select.empty();
                $select.append($('<option>', {
                    value: '',
                    text: '数据加载失败',
                    disabled: true
                }));

                // 恢复状态
                $select.prop('disabled', false).removeClass('loading');

                // 触发错误事件
                $select.trigger('select:ajax:error', [xhr, status, error]);
            }
        }, ajaxConfig));
    }

    /**
     * 获取data-*属性
     */
    _getDataAttributes($element) {
        var attrs = {};
        var data = $element.data();

        // 转换属性名
        $.each(data, function(key, value) {
            if (key.startsWith('select')) {
                var newKey = key.replace(/^select/, '');
                newKey = newKey.charAt(0).toLowerCase() + newKey.slice(1);
                attrs[newKey] = value;
            }
        });

        return attrs;
    }

    /**
     * 设置选中值
     */
    setValue($select, value) {
        $select.val(value).trigger('change');
        return this;
    }

    /**
     * 启用/禁用
     */
    setDisabled($select, disabled) {
        $select.prop('disabled', disabled);
        return this;
    }

    /**
     * 重新加载数据
     */
    reload($select) {
        var dataAttrs = this._getDataAttributes($select);
        if (dataAttrs.url) {
            this._renderWithAjax($select, { url: dataAttrs.url }, dataAttrs);
        }
        return this;
    }
}