$(document).ready(function() {

    let base = $('base').attr('href');

    $('.action').click(function(e) {
        e.preventDefault();
        $('.window').addClass('active');
    });
    $('a[href="#file"]').click(function(e) {
        e.preventDefault();
        $('.window').addClass('active');
    });
    $('.filter').click(function(e) {
        e.preventDefault();
        $('.window').addClass('active');
    });
    $('.window .close').click(function(e) {
        e.preventDefault();
        $('.window').removeClass('active');
    });

    $('.simulator .delete').click(function(e) {
        e.preventDefault();
        let id = $(this).attr('href').split('/');
        swal({
                title: "Você tem certeza?",
                text: `Que deseje excluir esse registro?`,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Sim, eu tenho",
                cancelButtonText: "Não, cancele",
                closeOnConfirm: false,
                closeOnCancel: false
            },
            function(isConfirm) {
                if (isConfirm) {
                    $.ajax({
                        url: `${base}simulator/delete`,
                        data: {
                            id: id[id.length - 1],
                        },
                        type: 'DELETE',
                        success: function(response) {
                            swal("Deletado!", `O registro foi deletado com sucesso!`, "success");
                            setTimeout(() => {
                                location.reload();
                            }, 1000);
                        }
                    });
                } else {
                    swal("Cancelado", "O registro não será deletado :)", "error");
                }
            }
        )
    });

    $(".simulator .sortable").sortable({
        update: function() {
            let lista = $('.sortable').sortable('toArray');
            $.ajax({
                type: "POST",
                url: `${base}simulator/steps`,
                data: {
                    lista: lista,
                },
                success: function(response) {

                }
            });
        }
    });

    $(".files .sortable").sortable({
        update: function() {
            let lista = $('.sortable').sortable('toArray');
            $.ajax({
                type: "POST",
                url: `${base}galery/steps`,
                data: {
                    lista: lista,
                },
                success: function(response) {

                }
            });
        }
    });

    $('.files .delete').click(function(e) {
        e.preventDefault();
        let id = $(this).attr('href').split('/');
        swal({
                title: "Você tem certeza?",
                text: `Que deseje excluir esse registro?`,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Sim, eu tenho",
                cancelButtonText: "Não, cancele",
                closeOnConfirm: false,
                closeOnCancel: false
            },
            function(isConfirm) {
                if (isConfirm) {
                    $.ajax({
                        url: `${base}galery/delete`,
                        data: {
                            id: id[id.length - 1],
                        },
                        type: 'DELETE',
                        success: function(response) {
                            swal("Deletado!", `O registro foi deletado com sucesso!`, "success");
                            setTimeout(() => {
                                location.reload();
                            }, 1000);
                        }
                    });
                } else {
                    swal("Cancelado", "O registro não será deletado :)", "error");
                }
            }
        )
    });

    $('.window select[name="type"]').change(function(e) {
        e.preventDefault();
        if (this.value == 'text' || this.value == 'tel' || this.value == 'email' || this.value == 'money' || this.value == 'date' || this.value == 'file') {
            $('.window .active').slideUp();
            $('.window .active').addClass('hide');
            $('.window .active').remove();
            $('.window #content').append(`
                <div id="text" class="hide">
                    <label for="name" class="col s12">
                        Qual será a descrição desse campo?
                        <input type="text" name="name" required>
                    </label>
                    <div class="flex">
                        <p>Este campo é obrigatório?</p>
                        <div class="switch">
                            <label>
                                Não
                                <input type="checkbox" name="required">
                                <span class="lever"></span>
                                Sim
                            </label>
                        </div>
                    </div>
                </div>
            `);
            $('#text').slideDown();
            $('#text').removeClass('hide');
            $('#text').addClass('active');
        } else if (this.value == 'number') {
            $('.window .active').slideUp();
            $('.window .active').addClass('hide');
            $('.window .active').remove();
            $('.window #content').append(`
                <div id="quantidade" class="hide">
                    <label for="name" class="col s12">
                        Qual será a descrição desse campo?
                        <input type="text" name="name" required>
                    </label>
                    <label for="minQ" class="col s6">
                        Quantidade minima
                        <input type="number" name="minQ" value="1" min="1">
                    </label>
                    <label for="maxQ" class="col s6">
                        Quantidade maxima
                        <input type="number" name="maxQ" value="1" min="1">
                    </label>
                    <div class="flex">
                        <p>Este campo é obrigatório?</p>
                        <div class="switch">
                            <label>
                                Não
                                <input type="checkbox" name="required">
                                <span class="lever"></span>
                                Sim
                            </label>
                        </div>
                    </div>
                </div>
            `);
            $('#quantidade').slideDown();
            $('#quantidade').removeClass('hide');
            $('#quantidade').addClass('active');
        } else if (this.value == 'select' || this.value == 'radio' || this.value == 'checkbox') {
            $('.window .active').slideUp();
            $('.window .active').addClass('hide');
            $('.window .active').remove();
            $('.window #content').append(`
                <div id="options" class="hide">
                    <label for="name" class="col s12">
                        Qual será a descrição desse campo?
                        <input type="text" name="name" required>
                    </label>
                    <label for="options" class="col s12">
                        Adicione as opções
                        <div class="flex">
                            <input type="text" name="options[]" required>
                            <a href="" class="more"><span class="fa fa-plus"></span></a>
                        </div>
                    </label>
                    <div class="flex">
                        <p>Este campo é obrigatório?</p>
                        <div class="switch">
                            <label>
                                Não
                                <input type="checkbox" name="required">
                                <span class="lever"></span>
                                Sim
                            </label>
                        </div>
                    </div>
                </div>
            `);
            $('#options').slideDown();
            $('#options').removeClass('hide');
            $('#options').addClass('active');

            $('.more').click(function(e) {
                e.preventDefault();
                $('label[for="options"]').append(`
                    <div class="flex">
                        <input type="text" name="options[]" required>
                        <a href="" class="minus"><span class="far fa-trash-alt"></span></a>
                    </div>
                `);

                $('.minus').click(function(e) {
                    e.preventDefault();
                    $(this).parent().remove();
                });
            });
        } else if (this.value == 'textarea') {
            $('.window .active').slideUp();
            $('.window .active').addClass('hide');
            $('.window .active').remove();
            $('.window #content').append(`
                <div id="textarea" class="hide">
                    <label for="name" class="col s12">
                        Qual será a descrição desse campo?
                        <input type="text" name="name" required>
                    </label>
                    <label for="minQ" class="col s12">
                        Quantidade máxima de caracteres
                        <input type="number" name="maxLength" value="1" min="1">
                    </label>
                    <div class="flex">
                        <p>Este campo é obrigatório?</p>
                        <div class="switch">
                            <label>
                                Não
                                <input type="checkbox" name="required">
                                <span class="lever"></span>
                                Sim
                            </label>
                        </div>
                    </div>
                </div>
            `);
            $('#textarea').slideDown();
            $('#textarea').removeClass('hide');
            $('#textarea').addClass('active');
        }
    });

    $('.new').click(function(e) {
        e.preventDefault();
        let value = $('input[name="name"]').val()
        if (value != '') {
            $.ajax({
                type: "POST",
                url: `${base}leads/filters`,
                data: {
                    name: value
                },
                success: function(response) {
                    $('.filters .flex').html(response);
                    filters();
                }
            });
        }
    });

    filters();

    function filters() {
        $('input[name="filter[]"]').change(function(e) {
            e.preventDefault();
            let filters = [];
            let notChecked = [];
            $('input[name="filter[]"]:checked').each(function(index, element) {
                filters.push(element.value);
            });

            $('input[name="filter[]"]').each(function(index, element) {
                notChecked.push(element.value);
            });

            $.ajax({
                type: "POST",
                url: `${base}leads/change`,
                data: {
                    filter: filters,
                    all: notChecked
                },
                success: function(response) {

                }
            });
        });

        $('.window.filters .remove').click(function(e) {
            e.preventDefault();
            let elem = $(this);
            let id = $(this).attr('href');
            $.ajax({
                type: "DELETE",
                url: `${base}leads/remove`,
                data: {
                    id: id
                },
                success: function(response) {
                    $(elem).parent().remove();
                }
            });
        });
    }

    $('.data-table-simple .delete').click(function(e) {
        e.preventDefault();
        let id = $(this).attr('href').split('/');
        swal({
                title: "Você tem certeza?",
                text: `Que deseje excluir esse registro?`,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Sim, eu tenho",
                cancelButtonText: "Não, cancele",
                closeOnConfirm: false,
                closeOnCancel: false
            },
            function(isConfirm) {
                if (isConfirm) {
                    $.ajax({
                        url: `${base}leads/delete`,
                        data: {
                            id: id[id.length - 1],
                        },
                        type: 'DELETE',
                        success: function(response) {
                            swal("Deletado!", `O registro foi deletado com sucesso!`, "success");
                            setTimeout(() => {
                                location.reload();
                            }, 1000);
                        }
                    });
                } else {
                    swal("Cancelado", "O registro não será deletado :)", "error");
                }
            }
        )
    });

    $('.newR').click(function(e) {
        e.preventDefault();
        $('.modalRecord:nth-of-type(1)').addClass('active');
    });

    $('.newq').click(function(e) {
        e.preventDefault();
        $('.modalRecord.q').addClass('active');
    });

    $('.modalRecord .close').click(function(e) {
        e.preventDefault();
        $('.modalRecord').removeClass('active');
    });

    $('input[name="transfer"]').change(function(e) {
        if ($('input[name="transfer"]:checked').length > 0) {
            $('.modalRecord select').show();
        } else {
            $('.modalRecord select').hide();
        }
    });

    $('select[name="sector"]').change(function(e) {
        if ($(this).val() == 1) {
            $('.modalRecord .price').show();
        } else {
            $('.modalRecord .price').hide();
        }
    });

    $('select[name="type"]').change(function(e) {
        if ($(this).val() == 0) {
            $('.q .col:nth-of-type(2)').removeClass('disabled');
            $('.q .col:nth-of-type(3)').addClass('disabled');
        } else {
            $('.q .col:nth-of-type(2)').addClass('disabled');
            $('.q .col:nth-of-type(3)').removeClass('disabled');
        }
    });

    if ($('.editor').is(':visible')) {
        ClassicEditor
            .create(document.querySelector('.editor'), {
                toolbar: {
                    items: [
                        'bold',
                        'italic',
                        'link',
                        'bulletedList',
                        'numberedList',
                        '|',
                        'undo',
                        'redo',
                        '|'
                    ]
                },
                language: 'pt-br',
                licenseKey: '',
            })
            .then(editor => {
                window.editor = editor;
            })
            .catch(error => {
                console.error('Oops, something went wrong!');
                console.error('Please, report the following error on https://github.com/ckeditor/ckeditor5/issues with the build id and the error stack trace:');
                console.warn('Build id: nofltlx4alsd-av3vandobeov');
                console.error(error);
            });
    }

    if ($('.answer').is(':visible')) {
        ClassicEditor
            .create(document.querySelector('.answer'), {
                toolbar: {
                    items: [
                        'bold',
                        'italic',
                        'link',
                        'bulletedList',
                        'numberedList',
                        '|',
                        'undo',
                        'redo',
                        '|'
                    ]
                },
                language: 'pt-br',
                licenseKey: '',
            })
            .then(editor => {
                window.editor = editor;
            })
            .catch(error => {
                console.error('Oops, something went wrong!');
                console.error('Please, report the following error on https://github.com/ckeditor/ckeditor5/issues with the build id and the error stack trace:');
                console.warn('Build id: nofltlx4alsd-av3vandobeov');
                console.error(error);
            });
    }

    if ($('.inline').is(':visible')) {
        InlineEditor
            .create(document.querySelector('.inline'), {
                toolbar: {
                    items: [
                        'bold',
                        'italic',
                        'link',
                        'bulletedList',
                        'numberedList',
                    ]
                },
                language: 'pt-br',
                licenseKey: '',
            })
            .then(editor => {
                window.editor = editor;
            })
            .catch(error => {
                console.error('Oops, something went wrong!');
                console.error('Please, report the following error on https://github.com/ckeditor/ckeditor5/issues with the build id and the error stack trace:');
                console.warn('Build id: nofltlx4alsd-av3vandobeov');
                console.error(error);
            });
    }

});