"use strict";
(function ($) {
    $.view_vendor_detail = function (element, options) {
        let defaults = {
            min_price:0,
            max_price:1099,
            list_category:[],
            limit:0,
            user_id:'',
            list_review:[],
            user_id_login:''
        }
        let plugin = this;
        plugin.settings = {}
        let $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);

            let min_price=parseInt(plugin.settings.min_price);
            let max_price=parseInt(plugin.settings.max_price);
            let list_category=plugin.settings.list_category;
            let limit = plugin.settings.limit;
            let list_review = plugin.settings.list_review;
            let $form_filter_all = $element.find('form[name="filter-all"]');
            $element.find('.gallery-graphic-slider').slick({
                infinite: true,
                slidesToShow: 1,
                slidesToScroll: 1,
                arrows: false,
                dots: true,
                autoplay: true,
                autoplaySpeed: 2000,
            });

            $element.find('.wrapper-product-slider').slick({
                slidesToShow: 4,
                slidesToScroll: 1,
                dots: false,
                prevArrow: $element.find('.arrow-left'),
                nextArrow: $element.find('.arrow-right'),
                responsive: [
                    {
                        breakpoint: 1200,
                        settings: {
                            slidesToShow: 3,
                            slidesToScroll: 3,
                            infinite: true,
                        }
                    },
                    {
                        breakpoint: 992,
                        settings: {
                            slidesToShow: 3,
                            slidesToScroll: 3,
                            infinite: true,
                        }
                    },
                    {
                        breakpoint: 768,
                        settings: {
                            slidesToShow: 2,
                            slidesToScroll: 2
                        }
                    },
                    {

                        breakpoint: 576,
                        settings: {
                            arrows: false,
                            slidesToShow: 1,
                            slidesToScroll: 1,
                            dots: true,
                        }
                    }
                    // You can unslick at a given breakpoint now by adding:
                    // settings: "unslick"
                    // instead of a settings object
                ]
            });
            $.each(list_category, function (index, item) {
                let items_per_page = parseInt(limit);
                let total_result = parseInt(item.number_service);
                let total_page = Math.ceil(total_result / items_per_page);
                let visiblePages = (total_page < 2) ? (total_page % 2): 2;
                $element.find(`#slider-container-category-${item.id}`).slider({
                    range: true,
                    min: 0,
                    max: 1099,
                    values: [min_price, max_price],
                    create: function () {
                        let $block_filter_price = $(this).closest(".block-filter-price");
                        $block_filter_price.find(`#amount_category_${item.id}`).val("$" + min_price + " - " + "$" + max_price);
                    },
                    slide: function (event, ui) {
                        let $block_filter_price = $(this).closest(".block-filter-price");
                        $block_filter_price.find(`#amount_category_${item.id}`).val("$" + ui.values[0] + " - $" + ui.values[1]);
                        var mi = ui.values[0];
                        var mx = ui.values[1];
                        plugin.filterSystem(mi, mx);
                    },
                    change: function(event, ui) {
                        var mi = ui.values[0];
                        var mx = ui.values[1];
                        let price_value=[];
                        price_value.push(mi);
                        price_value.push(mx);
                        let $block_filter_price = $(this).closest(".block-filter-price");
                        $block_filter_price.find(`input[name="price_search"]`).val(JSON.stringify(price_value)).trigger('change');
                    }
                });
                plugin.renderPaginationCategory(item, total_page, visiblePages);
                let $form = $element.find(`form[name="filter-category-${item.id}"]`);
                $form.find('.sort-display a').on('click',function (e) {
                    let key_sort=$(this).data('key_sort');
                    let direction=$(this).data('direction');
                    $form.find('input[name="sort"]').val(key_sort);
                    $form.find('input[name="direction"]').val(direction);
                    $form.find('.sort-display li').removeClass('active');
                    $form.find('.sort-display a').removeClass('active');
                    $(this).addClass('active');
                    $(this).closest('li').addClass('active');
                    let text = $(this).text();
                    $form.find('span.select-by-default').text(text);
                });

                $form.find('.sort-by-block .dropdown').on('click', function () {
                    $(this).find('i').addClass('active');
                    if($(this).hasClass('open') === false) {
                        $(this).find('i').removeClass('active');
                    }
                });
                var filterAjax = plugin.debounce(function () {
                    var output = plugin.convert_data_form($form);
                    let dataObj = {};
                    $(output).each(function(i, field){
                        dataObj[field.name] = field.value;
                    });
                    dataObj['category_id'] = item.id;
                    dataObj['total_result'] = item.number_service;
                    $.ajax({
                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            dataObj: dataObj,
                            task: "category.get_list_services_ajax"
                        },
                        beforeSend: function() {
                            $('body').loadingModal();
                        },
                        success: function(res) {
                            res = JSON.parse(res);
                            let result = res.data;
                            $form.find(`.category-${item.id}`).empty();
                            $form.find(`.category-${item.id}`).append(result.html);
                            items_per_page = parseInt(limit);
                            total_result = parseInt(result.total_service);
                            total_page = Math.ceil(total_result / items_per_page);
                            visiblePages = (total_page < 2) ? (total_page % 2): 2;
                            $form.find(`.pagination-category-${item.id}`).twbsPagination('destroy');
                            plugin.renderPaginationCategory(item, total_page, visiblePages);

                        },
                        error: function(xhr) { // if error occured

                        },
                        complete: function() {
                            $('body').loadingModal('destroy');

                        },
                    })
                }, 2000);
                $form.find('input[name="price_search"]').on('change',filterAjax);
                $form.find('input[name="keyword"]').on('keyup', filterAjax);
                $form.find('.sort-display a').on('click',filterAjax);
            });
            $form_filter_all.find('#slider-container-1').slider({
                range: true,
                min: 0,
                max: 1099,
                values: [min_price, max_price],
                create: function () {
                    let $block_filter_price = $(this).closest(".block-filter-price");
                    $block_filter_price.find("#amount_1").val("$" + min_price + " - " + "$" + max_price);
                },
                slide: function (event, ui) {
                    let $block_filter_price = $(this).closest(".block-filter-price");
                    $block_filter_price.find("#amount_1").val("$" + ui.values[0] + " - $" + ui.values[1]);
                    var mi = ui.values[0];
                    var mx = ui.values[1];
                    plugin.filterSystem(mi, mx);
                },
                change: function(event, ui) {
                    var mi = ui.values[0];
                    var mx = ui.values[1];
                    let price_value=[];
                    price_value.push(mi);
                    price_value.push(mx);
                    let $block_filter_price = $(this).closest(".block-filter-price");
                    $block_filter_price.find(`input[name="price_search"]`).val(JSON.stringify(price_value)).trigger('change');
                }
            });
            $form_filter_all.find('.sort-display a').on('click',function (e) {
                let key_sort=$(this).data('key_sort');
                let direction=$(this).data('direction');
                $form_filter_all.find('input[name="sort"]').val(key_sort);
                $form_filter_all.find('input[name="direction"]').val(direction);
                $form_filter_all.find('.sort-display li').removeClass('active');
                $form_filter_all.find('.sort-display a').removeClass('active');
                $(this).addClass('active');
                $(this).closest('li').addClass('active');
                let text = $(this).text();
                $form_filter_all.find('span.select-by-default').text(text);
            });

            $form_filter_all.find('.sort-by-block .dropdown').on('click', function () {
                $(this).find('i').addClass('active');
                if($(this).hasClass('open') === false) {
                    $(this).find('i').removeClass('active');
                }
            });
            var filterAjaxAll = plugin.debounce(function () {
                var output = plugin.convert_data_form($form_filter_all);
                let dataObj = {};
                $(output).each(function(i, field){
                    dataObj[field.name] = field.value;
                });
                dataObj['user_id'] = plugin.settings.user_id;
                $.ajax({
                    url: wpbookingpro_root_url+wpbookingpro_api_task,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        dataObj: dataObj,
                        task: "vendor.get_list_services_ajax"
                    },
                    beforeSend: function() {
                        $('body').loadingModal();
                    },
                    success: function(res) {
                        res = JSON.parse(res);
                        let result = res.data;
                        $form_filter_all.find('.wrapper-product-slider').slick('unslick');
                        $form_filter_all.find('.wrapper-product-slider').empty();
                        $form_filter_all.find('.wrapper-product-slider').append(result.html);
                        if(result.total_service > 0) {
                            $form_filter_all.find('.wrapper-product-slider').slick({
                                slidesToShow: 4,
                                slidesToScroll: 1,
                                dots: false,
                                prevArrow: $element.find('.arrow-left'),
                                nextArrow: $element.find('.arrow-right'),
                                responsive: [
                                    {
                                        breakpoint: 1200,
                                        settings: {
                                            slidesToShow: 3,
                                            slidesToScroll: 3,
                                            infinite: true,
                                        }
                                    },
                                    {
                                        breakpoint: 992,
                                        settings: {
                                            slidesToShow: 3,
                                            slidesToScroll: 3,
                                            infinite: true,
                                        }
                                    },
                                    {
                                        breakpoint: 768,
                                        settings: {
                                            slidesToShow: 2,
                                            slidesToScroll: 2
                                        }
                                    },
                                    {

                                        breakpoint: 576,
                                        settings: {
                                            arrows: false,
                                            slidesToShow: 1,
                                            slidesToScroll: 1,
                                            dots: true,
                                        }
                                    }
                                    // You can unslick at a given breakpoint now by adding:
                                    // settings: "unslick"
                                    // instead of a settings object
                                ]
                            });
                            $form_filter_all.find('.arrow-left').css('display','flex');
                            $form_filter_all.find('.arrow-right').css('display','flex');
                        } else {
                            $form_filter_all.find('.arrow-left').css('display','none');
                            $form_filter_all.find('.arrow-right').css('display','none');
                        }
                        $form_filter_all.find('.block-service-item i.fa-heart').on('click', function () {
                            $(this).toggleClass('active');
                            let $block_service_item = $(this).closest('.block-service-item');
                            let service_id = $block_service_item.data('service_id');
                            let user_id = plugin.settings.user_id_login;

                            if($(this).hasClass('active')) {
                                let data = {
                                    service_id: service_id,
                                    user_id: user_id,
                                    task: 'wishlist.save_user_wishlist'
                                };
                                $.ajax({
                                    url: wpbookingpro_root_url+wpbookingpro_api_task,
                                    type: 'POST',
                                    dataType: 'json',
                                    data: data,
                                    beforeSend: function() {
                                        $('body').loadingModal();
                                    },
                                    success: function(res) {
                                    },
                                    error: function(xhr) { // if error occured

                                    },
                                    complete: function() {
                                        $('body').loadingModal('destroy');

                                    },
                                })
                            } else {
                                let data = {
                                    service_id: service_id,
                                    user_id: user_id,
                                    task: 'wishlist.delete_user_wishlist'
                                };
                                $.ajax({
                                    url: wpbookingpro_root_url+wpbookingpro_api_task,
                                    type: 'POST',
                                    dataType: 'json',
                                    data: data,
                                    beforeSend: function() {
                                        $('body').loadingModal();
                                    },
                                    success: function(res) {
                                    },
                                    error: function(xhr) { // if error occured

                                    },
                                    complete: function() {
                                        $('body').loadingModal('destroy');

                                    },
                                })
                            }

                        });


                    },
                    error: function(xhr) { // if error occured

                    },
                    complete: function() {
                        $('body').loadingModal('destroy');

                    },
                })
            }, 2000);
            $form_filter_all.find('input[name="price_search"]').on('change',filterAjaxAll);
            $form_filter_all.find('input[name="keyword"]').on('keyup', filterAjaxAll);
            $form_filter_all.find('.sort-display a').on('click',filterAjaxAll);
            $form_filter_all.find('.block-service-item i.fa-heart').on('click', function () {
                $(this).toggleClass('active');
                let $block_service_item = $(this).closest('.block-service-item');
                let service_id = $block_service_item.data('service_id');
                let user_id = plugin.settings.user_id_login;

                if($(this).hasClass('active')) {
                    let data = {
                        service_id: service_id,
                        user_id: user_id,
                        task: 'wishlist.save_user_wishlist'
                    };
                    $.ajax({
                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                        type: 'POST',
                        dataType: 'json',
                        data: data,
                        beforeSend: function() {
                            $('body').loadingModal();
                        },
                        success: function(res) {
                        },
                        error: function(xhr) { // if error occured

                        },
                        complete: function() {
                            $('body').loadingModal('destroy');

                        },
                    })
                } else {
                    let data = {
                        service_id: service_id,
                        user_id: user_id,
                        task: 'wishlist.delete_user_wishlist'
                    };
                    $.ajax({
                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                        type: 'POST',
                        dataType: 'json',
                        data: data,
                        beforeSend: function() {
                            $('body').loadingModal();
                        },
                        success: function(res) {
                        },
                        error: function(xhr) { // if error occured

                        },
                        complete: function() {
                            $('body').loadingModal('destroy');

                        },
                    })
                }

            });

            $element.find('form[name="form-review"]').each(function (e) {
                $(this).validate({
                    ignore: ""
                });
            });
            $element.find('.btn-save-review').on('click', function () {
                let $form = $(this).closest('form[name="form-review"]');
                let rating_vendor = $form.find('input[name="rating_vendor"]').val();
                if(rating_vendor === '') {
                    $.alert({
                        title:'',
                        content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please rating star</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                        container:'.block-alert',
                        buttons: {
                            formSubmit: {
                                text: '<i class="icon-nb-close"></i>',
                                btnClass: 'btn-red',
                            }
                        }
                    });
                    return false;
                }
                if (!$form.valid()) {
                    return false;
                }
                $form.submit();
            });

            let items_per_page = parseInt(limit);
            let total_result = parseInt(list_review.length);
            let total_page = Math.ceil(total_result / items_per_page);
            let visiblePages = (total_page < 2) ? (total_page % 2): 2;

            $element.find('.pagination-review').twbsPagination({
                totalPages:(total_page === 0)?1:total_page,
                visiblePages: visiblePages,
                hideOnlyOnePage:true,
                first: '<i class="fas fa-angle-double-left"></i>',
                prev: '<i class="fas fa-angle-left"></i>',
                next: '<i class="fas fa-angle-right"></i>',
                last: '<i class="fas fa-angle-double-right"></i>',
                onPageClick: function (event, page) {
                    let $form = $(this).closest('form[name="form-list_review"]');
                    $form.find('input[name="start"]').val(page -  1);
                    var output = plugin.convert_data_form($form);
                    let dataObj = {};
                    $(output).each(function(i, field){
                        dataObj[field.name] = field.value;
                    });
                    dataObj['total_result'] = list_review.length;
                    dataObj['user_id'] = plugin.settings.user_id;
                    $.ajax({
                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            dataObj: dataObj,
                            task: "vendor.get_list_review_ajax"
                        },
                        beforeSend: function() {
                            $('body').loadingModal();
                        },
                        success: function(res) {
                            res = JSON.parse(res);
                            let result = res.data;
                            $form.find('.wrapper-list-review').empty();
                            $form.find('.wrapper-list-review').append(result);
                        },
                        error: function(xhr) { // if error occured

                        },
                        complete: function() {
                            $('body').loadingModal('destroy');

                        },
                    })
                }
            });


        };

        plugin.renderPaginationCategory = function(item,total_page, visiblePages) {
            $element.find(`.pagination-category-${item.id}`).twbsPagination({
                totalPages:(total_page === 0)?1:total_page,
                visiblePages: visiblePages,
                hideOnlyOnePage:true,
                first: '<i class="fas fa-angle-double-left"></i>',
                prev: '<i class="fas fa-angle-left"></i>',
                next: '<i class="fas fa-angle-right"></i>',
                last: '<i class="fas fa-angle-double-right"></i>',
                onPageClick: function (event, page) {
                    let $form = $(this).closest(`form[name="filter-category-${item.id}"]`);
                    $form.find('input[name="start"]').val(page -  1);
                    var output = plugin.convert_data_form($form);
                    let dataObj = {};
                    $(output).each(function(i, field){
                        dataObj[field.name] = field.value;
                    });
                    dataObj['category_id'] = item.id;
                    dataObj['total_result'] = item.number_service;
                    $.ajax({
                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            dataObj: dataObj,
                            task: "category.get_list_services_ajax"
                        },
                        beforeSend: function() {
                            $('body').loadingModal();
                        },
                        success: function(res) {
                            res = JSON.parse(res);
                            let result = res.data;
                            $form.find(`.category-${item.id}`).empty();
                            $form.find(`.category-${item.id}`).append(result.html);
                            $form.find('.block-service-item i.fa-heart').on('click', function () {
                                $(this).toggleClass('active');
                                let $block_service_item = $(this).closest('.block-service-item');
                                let service_id = $block_service_item.data('service_id');
                                let user_id = plugin.settings.user_id_login;

                                if($(this).hasClass('active')) {
                                    let data = {
                                        service_id: service_id,
                                        user_id: user_id,
                                        task: 'wishlist.save_user_wishlist'
                                    };
                                    $.ajax({
                                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                                        type: 'POST',
                                        dataType: 'json',
                                        data: data,
                                        beforeSend: function() {
                                            $('body').loadingModal();
                                        },
                                        success: function(res) {
                                        },
                                        error: function(xhr) { // if error occured

                                        },
                                        complete: function() {
                                            $('body').loadingModal('destroy');

                                        },
                                    })
                                } else {
                                    let data = {
                                        service_id: service_id,
                                        user_id: user_id,
                                        task: 'wishlist.delete_user_wishlist'
                                    };
                                    $.ajax({
                                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                                        type: 'POST',
                                        dataType: 'json',
                                        data: data,
                                        beforeSend: function() {
                                            $('body').loadingModal();
                                        },
                                        success: function(res) {
                                        },
                                        error: function(xhr) { // if error occured

                                        },
                                        complete: function() {
                                            $('body').loadingModal('destroy');

                                        },
                                    })
                                }

                            });
                        },
                        error: function(xhr) { // if error occured

                        },
                        complete: function() {
                            $('body').loadingModal('destroy');

                        },
                    })
                }
            });

        }

        plugin.debounce = function(func, wait) {
            var timeout;

            return function() {
                var context = this,
                    args = arguments;

                var executeFunction = function() {
                    func.apply(context, args);
                };

                clearTimeout(timeout);
                timeout = setTimeout(executeFunction, wait);
            };
        };
        plugin.convert_data_form = function($form) {
            var dataArray = $form.serializeArray();
            var output = [];
            dataArray.forEach(function(item) {
                var existing = output.filter(function(v, i) {
                    return v.name == item.name;
                });
                if (existing.length) {
                    var existingIndex = output.indexOf(existing[0]);
                    output[existingIndex].value = output[existingIndex].value.concat(item.value);
                } else {
                    if (typeof item.value == 'string')
                        item.value = [item.value];
                    output.push(item);
                }
            });
            return output;
        };

        plugin.filterSystem = function (minPrice, maxPrice) {
            $("#computers div.system").hide().filter(function () {
                var price = parseInt($(this).data("price"), 10);
                return price >= minPrice && price <= maxPrice;
            }).show();
        }
        plugin.example_function = function () {
        };
        plugin.init();
    }
    $.fn.view_vendor_detail = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_vendor_detail')) {
                let plugin = new $.view_vendor_detail(this, options);
                $(this).data('view_vendor_detail', plugin);
            }
        });
    }
})(jQuery);
