(function ($) {
    $.fn.Users = function (options) {
        var settings = $.extend({
            id: '',
            defaultUsers: [],
            labelText: '',
            defaultAvatar: '/static/image/defaultportrait.jpg',
            placeholder: ''
        }, options);

        return this.each(function () {
            if (!settings.id) {
                return;
            }
            var defaultUserIds = [];
            if (settings.defaultUsers.length > 0) {
                for (var i = 0; i < settings.defaultUsers.length; i++) {
                    defaultUserIds.push(settings.defaultUsers[i].Id);
                }
            }
            var fetchUsers = [];
            var selectedId = 'selected' + settings.id;
            var searchedContainerId = 'searchedContainer' + settings.id;
            var searchedResultId = 'searchedResult' + settings.id;
            var inputId = 'input' + settings.id;
            var label = document.createElement('label');
            label.className = 'form-label';
            label.textContent = settings.labelText;
            var divGroup = document.createElement('div');
            divGroup.className = 'input-group';

            var divContainer = document.createElement('div');
            divContainer.className = 'border me-2 p-2 mb-3 d-flex container-fluid';
            var divSelected = document.createElement('div');
            divSelected.className = 'flex-grow-1';
            if (settings.defaultUsers.length > 0) {
                for (var i = 0; i < settings.defaultUsers.length; i++) {
                    var item = settings.defaultUsers[i];
                    var span = document.createElement('span');
                    span.setAttribute('data-id', item.Id);
                    span.className = 'badge text-bg-secondary cursor-pointer me-1';
                    span.onclick = (event) => {
                        var currId = parseInt($(event.currentTarget).attr('data-id'));
                        event.currentTarget.remove();
                        settings.defaultUsers = settings.defaultUsers.filter(x => x.Id !== currId);
                        defaultUserIds = defaultUserIds.filter(x => x !== currId)
                        $('#' + settings.id).val(defaultUserIds.join(','));
                    };
                    var img = document.createElement('img');
                    img.className = 'rounded me-1';
                    img.style.width = '24px';
                    img.style.height = '24px';
                    img.src = item.Portrait ?? settings.defaultAvatar;
                    var icon = document.createElement('i');
                    icon.className = 'bi bi-x ms-1';
                    span.append(img);
                    span.append(item.LoginId);
                    span.append(icon);
                    divSelected.append(span);
                }
            }
            divContainer.append(divSelected);
            var divAddBtnContainer = document.createElement('div');
            var btnAdd = document.createElement('button');
            btnAdd.className = 'btn btn-sm btn-outline-primary';
            btnAdd.type = 'button';
            btnAdd.onclick = (event) => {
                var currIcon = $(event.currentTarget).find('i');
                if (currIcon.length > 0) {
                    var searchedContainer = $('#' + searchedContainerId);
                    if (searchedContainer.css("display") === "none") {
                        currIcon[0].className = 'bi bi-x-lg';
                        searchedContainer.show();
                    } else {
                        currIcon[0].className = 'bi bi-plus-lg';
                        searchedContainer.hide();
                    }
                }
            };
            var iconAdd = document.createElement('i');
            iconAdd.className = 'bi bi-plus-lg';
            btnAdd.append(iconAdd);
            divAddBtnContainer.append(btnAdd);
            divContainer.append(divAddBtnContainer);
            divGroup.append(divContainer);
            var inputHidden = document.createElement('input');
            inputHidden.type = 'hidden';
            inputHidden.id = settings.id;
            inputHidden.name = settings.id;
            if (defaultUserIds.length > 0) {
                inputHidden.value = defaultUserIds.join(',');
            }
            divGroup.append(inputHidden);

            var divSearchGroup = document.createElement('div');
            divSearchGroup.className = 'alert alert-secondary pb-0';
            divSearchGroup.role = 'alert';
            divSearchGroup.id = searchedContainerId;
            divSearchGroup.style.display = 'none';
            var divSearchContainer = document.createElement('div');
            divSearchContainer.className = 'row flex-grow-1';
            var divInputContainer = document.createElement('div');
            divInputContainer.className = 'col-auto mb-2 pe-0';
            var inputUser = document.createElement('input');
            inputUser.type = 'text';
            inputUser.className = 'form-control form-control-sm';
            inputUser.id = inputId;
            inputUser.placeholder = settings.placeholder;
            divInputContainer.append(inputUser);
            divSearchContainer.append(divInputContainer);
            var divSearchButtonContainer = document.createElement('div');
            divSearchButtonContainer.className = 'col-auto mb-2 pe-0';
            var btnSearch = document.createElement('button');
            btnSearch.className = 'btn btn-primary btn-sm';
            btnSearch.type = 'button';
            btnSearch.textContent = '查询';
            btnSearch.onclick = (event) => {
                var loginId = $('#' + inputId).val();
                if (loginId) {
                    $('#' + searchedResultId).html('查询中...');
                    $.ajax({
                        type: 'GET',
                        url: '/manage/forums/users?loginidcontains=' + encodeURIComponent(loginId),
                        dataType: 'json',
                        success: function (result) {
                            if (result.Success) {
                                if (result.Data && result.Data.length > 0) {
                                    fetchUsers = result.Data;
                                    $('#' + searchedResultId).html('');
                                    for (var i = 0; i < result.Data.length; i++) {
                                        var item = result.Data[i];
                                        var span = document.createElement('span');
                                        span.className = 'badge text-bg-light cursor-pointer me-1';
                                        span.setAttribute('data-id', item.Id);
                                        span.onclick = (event) => {
                                            var currId = parseInt($(event.currentTarget).attr('data-id'));
                                            if (defaultUserIds.indexOf(currId) === -1) {
                                                var curr = fetchUsers.filter(x => x.Id === currId)[0];
                                                defaultUserIds.push(currId);
                                                settings.defaultUsers.push(curr);
                                                $('#' + settings.id).val(defaultUserIds.join(','));
                                                event.currentTarget.remove();
                                                var span = document.createElement('span');
                                                span.setAttribute('data-id', curr.Id);
                                                span.className = 'badge text-bg-secondary cursor-pointer me-1';
                                                span.onclick = (event) => {
                                                    var currId = parseInt($(event.currentTarget).attr('data-id'));
                                                    event.currentTarget.remove();
                                                    settings.defaultUsers = settings.defaultUsers.filter(x => x.Id !== currId);
                                                    defaultUserIds = defaultUserIds.filter(x => x !== currId)
                                                    $('#' + settings.id).val(defaultUserIds.join(','));
                                                };
                                                var img = document.createElement('img');
                                                img.className = 'rounded me-1';
                                                img.style.width = '24px';
                                                img.style.height = '24px';
                                                img.src = curr.Portrait ?? settings.defaultAvatar;
                                                var icon = document.createElement('i');
                                                icon.className = 'bi bi-x ms-1';
                                                span.append(img);
                                                span.append(curr.LoginId);
                                                span.append(icon);
                                                divSelected.append(span);
                                            }
                                        }
                                        var img = document.createElement('img');
                                        img.className = 'rounded me-1';
                                        img.style.width = '24px';
                                        img.style.height = '24px';
                                        img.src = item.Portrait ?? settings.defaultAvatar;
                                        var icon = document.createElement('i');
                                        icon.className = 'bi bi-plus ms-1';
                                        span.append(img);
                                        span.append(item.LoginId);
                                        span.append(icon);
                                        $('#' + searchedResultId).append(span);
                                    }
                                } else {
                                    fetchUsers = [];
                                    $('#' + searchedResultId).html('没有查到用户');
                                }
                            } else {
                                fetchUsers = [];
                                $('#' + searchedResultId).html(result.Message);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {

                        }
                    });
                }
            };
            divSearchButtonContainer.append(btnSearch);
            divSearchContainer.append(divSearchButtonContainer);
            var divUsers = document.createElement('div');
            divUsers.className = 'mb-3';
            divUsers.id = searchedResultId;
            divSearchGroup.append(divSearchContainer);
            divSearchGroup.append(divUsers);
            $(this).append(label);
            $(this).append(divGroup);
            $(this).append(divSearchGroup);
        });
    }
}(jQuery));