jQuery(document).ready(function () {
    custom_switch_merchants();
    initAdminLtePlugin();
    initButtonConfirm()
    initNotice();
    initBtnEditReminder();
    $('form').on('focus', 'input[type=number]', function (e) {
        $(this).on('wheel.disableScroll', function (e) {
            e.preventDefault()
        })
    })
    $('form').on('blur', 'input[type=number]', function (e) {
        $(this).off('wheel.disableScroll')
    })
});

function initNotice() {
    $('#lc-flash-messages .notice').each(function (i, notice) {
        generateNotice($(notice).find('.type').html(), $(notice).find('.message').html());
    });
}

function initButtonConfirm() {
    $('.btn-confirm-js, .action-confirm').click(function () {
        return confirm('Êtes-vous sûr de vouloir réaliser cette action ?');
    });
}

function initLcNoty() {
    $('.lc-noty').each(function () {
        generateNotice($(this).data('type'), $(this).html());
    });
}


function custom_switch_merchants() {
    $('#switch-merchant').on('change', function () {
        $('#switch-merchant').parents('form').submit();
    });
}

function setBootstrapSwitch($checkbox) {

    $checkbox.bootstrapSwitch();
    $checkbox.bootstrapSwitch('state', true);
    $checkbox.on('switchChange.bootstrapSwitch', function (e, state) {
        var event = new Event('change');
        e.target.dispatchEvent(event);
    });
}

function initAdminLtePlugin() {

    /*$(".checkbox-switch input").each(function () {
        setBootstrapSwitch($(this));
    });*/

    $('[data-toggle="tooltip"]').tooltip();

    $(document).on('keypress', function (event) {

        /*if(event.keyCode == '13') {
            checkForm();
        }*/
    });
    $('form button[type="submit"]').on('click', function (e) {

        checkForm();
    })

    if ($('.select2, select.form-control').length) {

        $('form .form-widget>select.form-control, .select2').each(function (i, elm) {
            if (!$(this).hasClass('disable-select2')) {
                setSelect2($(elm));
            }
        });

        $('form .form-inline>select.form-control').each(function (i, elm) {
            if (!$(this).hasClass('disable-select2')) {
                setSelect2($(elm));
            }
        });
    }

    $('.autoresize textarea').each(function () {
        this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
    }).on('input', function () {
        log(this.scrollHeight);
        $(this).height('auto');
        log('BLOP' + this.scrollHeight);
        if (this.scrollHeight < 50) {
            $(this).outerHeight(this.scrollHeight - 12);
        } else {
            $(this).outerHeight(this.scrollHeight);
        }
    });


    $('.date-time-range, .date-range').each(function (i, picker) {
        options = {
            autoUpdateInput: false,
            locale: {
                "format": "DD/MM/YY",
                "separator": " - ",
                "applyLabel": "Appliquer",
                "cancelLabel": "Annuler",
                "fromLabel": "Du",
                "toLabel": "au",
                "customRangeLabel": "Custom",
                "daysOfWeek": ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
                "monthNames": ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Decembre"],
                "firstDay": 1
            }
        };
        if ($(picker).hasClass('date-time-range')){
            options = Object.assign(options, {
                timePicker: true,
                timePickerIncrement: 30,
                timePicker24Hour: true,
                locale: {
                    "format": "DD/MM/YYYY HH:mm",
                }
            });
        }
        if ($(picker).nextAll('.date-time-range-fields').find('.date-start').val()) {
            options.startDate = new Date($(picker).nextAll('.date-time-range-fields').find('.date-start').val());
            options.autoUpdateInput = true;
        }
        if ($(picker).nextAll('.date-time-range-fields').find('.date-end').val()) {
            options.endDate = new Date($(picker).nextAll('.date-time-range-fields').find('.date-end').val());
            options.autoUpdateInput = true;
        }
        $(picker).daterangepicker(options);
        $(picker).on('apply.daterangepicker', function (ev, pickerElm) {
            if ($(picker).hasClass('date-time-range')) {
                $(this).val(pickerElm.startDate.format('DD/MM/YY HH:mm') + ' - ' + pickerElm.endDate.format(options.locale.format));
            }else{
                $(this).val(pickerElm.startDate.format('DD/MM/YY') + ' - ' + pickerElm.endDate.format(options.locale.format));
            }
            if ($(picker).hasClass('date-time-range')) {
                $(picker).nextAll('.date-time-range-fields').find('.date-start').val(pickerElm.startDate.format('YYYY-MM-DD HH:mm'));
                $(picker).nextAll('.date-time-range-fields').find('.date-end').val(pickerElm.endDate.format('YYYY-MM-DD HH:mm'));
            }else{
                $(picker).nextAll('.date-time-range-fields').find('.date-start').val(pickerElm.startDate.format('YYYY-MM-DD'));
                $(picker).nextAll('.date-time-range-fields').find('.date-end').val(pickerElm.endDate.format('YYYY-MM-DD'));
            }
        });
    });


}

function moment() {
    return '2020-04-08';
}


function checkForm() {
    $('form').addClass('form-sent');
    //Panel vues js
    if ($('form').find('.panel').length) {
        $('form').find('.panel').each(function (i, panel) {
            if ($(panel).find(':invalid').length) {
                $('#nav-params').find('.nav-item:eq(' + i + ')').addClass('has-invalid');
            } else {
                $('#nav-params').find('.nav-item:eq(' + i + ')').removeClass('has-invalid');
            }
        })
    }
}

function setSelect2($select) {
    if (typeof $select.data('select2-id') === 'undefined') {

        $select.data('init', 'set')
        var options = {
            width: "100%",
            theme: "bootstrap",
            dropdownAutoWidth: false,
            allowClear: true,
            minimumResultsForSearch: 8
        };

        if ($select.data('allow-clear') == 'false') {
            options.allowClear = false;
        }
        if ($select.data('width')) {
            options.width = 'auto'
        }
        if ($select.find('option[value=""]')) {
            options.placeholder = $select.find('option[value=""]').html()
        }
        /*if($select.is(':required') == false) {
            options.allowclear = true
        }*/
        myselect = $select.select2(options);

        myselect.on('select2:select', function (e) {
            var event = new Event('change');
            e.target.dispatchEvent(event);
        });
        myselect.on('select2:unselect', function (e) {
            var event = new Event('change');
            e.target.dispatchEvent(event);
        });

        return myselect;
    }
}


function initBtnEditReminder() {
    $('.btn-edit-reminder, .btn-add-reminder ').on('click', function () {
        $btn = $(this);
        var url = $(this).data('url');
        $('#modal-reminder').remove();
        $.ajax({
            url: url,
            method: "POST",
            dataType: "json",
            success: function (response) {
                $('body').append(response.data);
                if ($btn.hasClass('btn-add-reminder')) {
                    $('#reminder_entityName').val(getUrlParameter('entity'));
                    $('#reminder_entityId').val(getUrlParameter('id'));
                    $('#reminder_entityAction').val(getUrlParameter('action'));
                }
                $('#modal-reminder').modal('show');
                initReminderModal(url);
            }
        });
    });

    $('.checkbox-valid-reminder').on('change', function () {
        var url = $(this).data('url');
        if ($(this).is(':checked')) {
            url = url + '&done=true'
        } else {
            url = url + '&done=false'
        }
        $.ajax({
            url: url,
            method: "POST",
            dataType: "json",
            success: function (response) {
                setFlashMessages(response.flashMessages);

            }
        });
    });
}

function initReminderModal(url) {
    setSelect2($('#reminderForm').find('select.form-control'));


    $('#modal-reminder .btn-save').on('click', function () {
        $('#modal-reminder').modal('hide');
        $.ajax({
            url: url,
            data: $('#reminderForm').serialize(),
            method: "POST",
            dataType: "json",
            success: function (response) {
                setFlashMessages(response.flashMessages);
                $('#modal-reminder').remove();
            }
        });
    });

}
