let formDiv = $(".form-select-two");

formDiv.select2({
    ajax: {
        url: mpPanelBaseUrl + "/form-request",
        type: "post",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                search: $.trim(params.term)
            };
        },
        processResults: function (data) {
            return {
                results: data
            };
        },
        cache: true
    },
    language: {
        inputTooShort: function () {
            return "جستجو در فرم‌های ساده";
        },
        noResults: function () {
            return "جستجو نتیجه‌ای نداشت";
        }
    },
    dir: "rtl",
    minimumInputLength: 0,
    templateResult: formatForm,
    templateSelection: formatFormSelection
});

let formClearBtn = formDiv.parent().find('.clear-s2');

formDiv.on("change",function(e){
    let selectedValue = formDiv.val();
    if(selectedValue == null || selectedValue == 0 || selectedValue == "" ){
        formClearBtn.hide();
    }else{
        formClearBtn.show();
    }
});

formClearBtn.click(function(){
    formDiv.val(0);
    formDiv.trigger('change');
});

function getFormNatureText(nature){
    switch (nature){
        case "form_order" : return "فرم پیشرفته";
        case "normal" : return "فرم ساده";
    }
    return nature;
}


function formatForm(cat) {
    if (cat.loading) {
        return cat.text;
    }
    let $container = $(
        "<div class='select2-result clearfix'>" +
        "<div class='select2-result-id'></div>" +
        "<div class='select2-result-meta'>" +
        "<div class='select2-rfdata'><div class='select2-result-text'></div><div class='select2-result-nature frn-"+cat.nature+"'></div></div>" +
        "<div class='select2-result-summary'></div>" +
        "</div>" +
        "</div>"
    );

    $container.find(".select2-result-id").text(cat.id);
    $container.find(".select2-result-text").text(cat.text);
    $container.find(".select2-result-summary").text(cat.description);
    $container.find(".select2-result-nature").text(getFormNatureText(cat.nature));

    return $container;
}

function formatFormSelection(cat) {
    return cat.text;
}