"use strict";
(function ($) {
    $.view_list_services = function (element, options) {
        let defaults = {
            row_state_template: "",
            page_list_service:'',
            min_price:0,
            max_price:1099,
            user_id:'',
            limit:'',
            list_service:[],
            format_currency:''
        };
        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 limit=parseInt(plugin.settings.limit);
            let list_service=plugin.settings.list_service;
            let format_currency = plugin.settings.format_currency;
            plugin.filterSystem(10, 100);
            $element.find('select[name="location"]').select2();
            $element.find('#slider-container-1').slider({
                range: true,
                min: 0,
                max: 1099,
                values: [min_price, max_price],
                create: function () {
                    $("#amount_1").val(format_currency + min_price + " - " + format_currency + max_price);
                },
                slide: function (event, ui) {
                    $("#amount_1").val(format_currency + ui.values[0] + " - " + format_currency + 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);
                    $element.find(`input[name="price_search"]`).val(JSON.stringify(price_value)).trigger('change');
                }
            });

            $element.find('.block-filter-price-more-option').slideUp();
            $element.find('.block-service-categories').slideUp();
            $element.find('.srat-ratings').slideUp();
            $element.find('.more-option').on('click',function (e) {
                let $block_more_option = $(this).closest('.block-more-option');
                $block_more_option.find('.block-filter-price-more-option').slideToggle();
                $block_more_option.find('.block-service-categories').slideToggle();
                $block_more_option.find('.srat-ratings').slideToggle();
            });
            $element.find('.title-item').on('click',function (e) {
                let $parent = $(this).parent();
                $parent.find('div:nth-child(2)').slideToggle();
                $(this).toggleClass('slide-up')
            });

            $element.find('input.input-near-me').on('change', function () {
                if($(this).is(":checked")) {
                    if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function(position) {
                            var latitude = position.coords.latitude;
                            var longitude = position.coords.longitude;
                            $element.find('input[name="latitude"]').val(latitude);
                            $element.find('input[name="longitude"]').val(longitude);
                        }, function () {
                            $element.find('input[name="latitude"]').val('');
                            $element.find('input[name="longitude"]').val('');
                        })
                    } else {
                        alert("Sorry, your browser does not support HTML5 geolocation.");
                    }
                } else {
                    $element.find('input[name="latitude"]').val('');
                    $element.find('input[name="longitude"]').val('');
                }
            })

            $element.find('.sort-display a').on('click',function (e) {
                let key_sort=$(this).data('key_sort');
                let direction=$(this).data('direction');
                $element.find('input[name="sort"]').val(key_sort);
                $element.find('input[name="direction"]').val(direction);
                $element.find('.sort-display li').removeClass('active');
                $element.find('.sort-display a').removeClass('active');
                $(this).addClass('active');
                $(this).closest('li').addClass('active');
                let text = $(this).text();
                $element.find('span.select-by-default').text(text);
            });

            $element.find('.sort-by-block .dropdown').on('click', function () {
                $(this).find('i').addClass('active');
                if($(this).hasClass('open') === false) {
                    $(this).find('i').removeClass('active');
                }
            });

            $element.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;
                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');

                    },
                })
            });
            $element.find('.block-service-item-display-list i.fa-heart').on('click', function () {
                $(this).toggleClass('active');
                let $block_service_item_display_list = $(this).closest('.block-service-item-display-list');
                let service_id = $block_service_item_display_list.data('service_id');
                let user_id = plugin.settings.user_id;
                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');

                    },
                })
            });

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

            plugin.renderPaginationService(total_page, visiblePages);

            var filterServiceAjax = plugin.debounce(function () {
                let $form = $element.find('form[name="filter-form"]');
                var output = plugin.convert_data_form($form);
                let dataObj = {};
                $(output).each(function(i, field){
                    dataObj[field.name] = field.value;
                });
                $.ajax({
                    url: wpbookingpro_root_url+wpbookingpro_api_task,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        dataObj: dataObj,
                        task: "services.get_list_service_ajax"
                    },
                    beforeSend: function() {
                        $('body').loadingModal();
                    },
                    success: function(res) {
                        res = JSON.parse(res);
                        let result = res.data;
                        $form.find('.wrapper-result-body').empty();
                        $form.find('.wrapper-result-body').append(result.html);
                        $form.find('input[name="total_result"]').val(result.total_service);
                        $form.find('.total-service').text(result.total_service)
                        items_per_page = 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-services`).twbsPagination('destroy');
                        plugin.renderPaginationService(total_page, visiblePages);

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

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

                    },
                })
            }, 2000);
            $element.find('select[name="location"]').on('change', filterServiceAjax);
            $element.find('input[name="near_me"]').on('change', filterServiceAjax);
            $element.find('input[name="vendor[]"]').on('change', filterServiceAjax);
            $element.find('input[name="employee[]"]').on('change', filterServiceAjax);
            $element.find('input[name="rating[]"]').on('change', filterServiceAjax);
            $element.find('input[name="price_search"]').on('change', filterServiceAjax);
            $element.find('input[name="category[]"]').on('change', filterServiceAjax);
            $element.find('.sort-display a').on('click',filterServiceAjax);

            $element.find("select#searchByCurrency").select2();
            $element.find("select#searchByCurrency").on('change', function () {
                let $form = $(this).closest('form[name="filter-form"]');
                var formData = new FormData();
                formData.append("task", "service.set_currency");
                formData.append("currency", $(this).val());
                var request = new XMLHttpRequest();
                request.open("POST", "");
                request.send(formData);
                setTimeout(function () {
                    window.location.href = plugin.settings.page_list_service;
                }, 1000)

            });


        };

        plugin.renderPaginationService = function(total_page, visiblePages) {
            $element.find('.pagination-services').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-form"]');
                    $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;
                    });

                    $.ajax({
                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            dataObj: dataObj,
                            task: "services.get_list_service_ajax"
                        },
                        beforeSend: function() {
                            $('body').loadingModal();
                        },
                        success: function(res) {
                            res = JSON.parse(res);
                            let result = res.data;
                            $form.find('.wrapper-result-body').empty();
                            $form.find('.wrapper-result-body').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;

                                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');

                                        },
                                    })
                                }

                            });
                            $form.find('.block-service-item-display-list i.fa-heart').on('click', function () {
                                $(this).toggleClass('active');
                                let $block_service_item_display_list = $(this).closest('.block-service-item-display-list');
                                let service_id = $block_service_item_display_list.data('service_id');
                                let user_id = plugin.settings.user_id;
                                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();
            dataArray = dataArray.map(function (item) {
                item.name = item.name.replace('[]','');
                return item;
            });
            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_list_services = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_list_services')) {
                let plugin = new $.view_list_services(this, options);
                $(this).data('view_list_services', plugin);
            }
        });
    }
})(jQuery);
