"use strict";
(function ($) {
    $.view_find_event_new = function (element, options) {
        let defaults = {
            service_item: '',
            visiblePages: 3,
            services: [],
            rates: [],
            current_page: 1,
            items_per_page: 3,
            base_price: 0,
            base_price_format: 0,
            person: 1
        };
        let plugin = this;
        plugin.settings = {};
        let $element = $(element);
        plugin.fill_data = function (current_page) {
            let data = plugin.settings.services;
            let total_result = data.length;
            $element.find('.count-result').text(total_result);
            let items_per_page = plugin.settings.items_per_page;
            var data_page = data.slice((current_page - 1) * items_per_page, current_page * items_per_page);
            let $list_result = $element.find('.wrapper-search-result .list-result');
            $list_result.empty();
            $.each(data_page, function (index, service) {
                let $service_item = $(plugin.settings.service_item);
                $service_item.attr('data-event_id', service.object_id);
                $service_item.data('event_id', service.object_id);
                let list_employee = service.list_employee;
                let $ul = $(`<ul class="list-employee-image"></ul>`);
                $.each(list_employee, function (index, employee) {
                    $ul.append(`<li><img class="employee-image" src="${wpbookingpro_root_url_plugin}/${employee.image}"></li>`);
                });

                $service_item.find('.service_name').text(service.name);
                $service_item.find('.category').text(service.category_name);
                let duration = service.duration;
                if(duration * 10 % 2 === 0) {
                    duration = Math.floor(duration) + ' hour(s)';
                } else {
                    duration = Math.floor(duration)  + ' hour(s) ' + (duration - Math.floor(duration) ) * 60 +' minutes';
                }

                $service_item.find('.service_duration').text(duration);
                $service_item.find('.service_address').text(service.location.address);
                $service_item.find('.description-detail').html(plugin.decodeHTML(service.description));

                let $ul_rating = $service_item.find('.list-rating-star');
                let rating_avg = parseFloat((parseFloat(service.rating_ambience) + parseFloat(service.rating_cleanliness) + parseFloat(service.rating_staff) + parseFloat(service.rating_value))/4);
                let array_star  = plugin.getStarRating(rating_avg);
                let $li_star ='';
                let $li_half_star='' ;
                let $li_non_star='' ;
                for (let i = 0; i< array_star[0]; i++) {
                        $li_star +=`<li class="item-star"><i class="fas fa-star"></i></li>`;
                }
                for (let i = 0; i< array_star[1]; i++) {
                    $li_half_star +=`<li class="item-star"><i class="fas fa-star-half-alt"></i></li>`;
                }
                for (let i = 0; i< array_star[2]; i++) {
                    $li_non_star +=`<li class="item-star"><i class="far fa-star"></i></li>`;
                };
                $ul_rating.append($li_star);
                $ul_rating.append($li_half_star);
                $ul_rating.append($li_non_star);
                $service_item.find('.image-service-image').attr('src', `${wpbookingpro_root_url_plugin}/${service.image}`);
                $service_item.find('.service_name').attr('href', `${wpbookingpro_root_url}/wp-booking-pro/?page=service-detail_new&service_id=${service.id}`);
                $service_item.find('.book-service').attr('href', `${wpbookingpro_root_url}/wp-booking-pro/?page=service-detail_new&service_id=${service.id}`);
                $service_item.find('.event_price_format').html('<span>$</span>' + service.price);
                $service_item.find('.wrapper-employee').append($ul);
                $service_item.appendTo($list_result);
            });
        };
        plugin.search_by_filter = function () {
            let $ajax_search = {};
            $element.find("form.form-filter").serializeObject().done(function (data) {
                if (typeof $ajax_search.abort === "function") {
                    $ajax_search.abort();
                }
                let $list_result = $element.find('.list-result');
                $list_result.addClass('searching');
                $ajax_search = $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: wpbookingpro_root_url + wpbookingpro_api_task,
                    data: data,
                    beforeSend: function () {
                        $list_result.loadingModal('opacity', '0.2');
                    },
                    error: function (xhr) {
                        $list_result.loadingModal('destroy');
                        $.alert({
                            title: 'Error',
                            content: 'there are some error please contact admin !',
                        });
                        $list_result.removeClass('searching');
                    },
                    complete: function () {
                        $('body').loadingModal('destroy');
                        $list_result.removeClass('searching');
                    },
                    success: function (response) {
                        response = JSON.parse(response);

                        if (response.result === "success") {
                            loadScripts(response);
                            plugin.settings.services = response.data;
                            let data = response.data;
                            let total_result = data.length;
                            let items_per_page = plugin.settings.items_per_page;
                            let total_page = Math.ceil(total_result / items_per_page);
                            let visiblePages = (total_page <= 4) ? (total_page % 4): 4;
                            if(visiblePages === 1) {
                                $element.find('.pagination-list-service').css('display', 'none');
                            } else {
                                $element.find('.pagination-list-service').css('display', 'flex');
                            }
                            $element.find('.pagination-list-service').twbsPagination('destroy');
                            $element.find('.pagination-list-service').twbsPagination({
                                totalPages: total_page,
                                visiblePages: visiblePages,
                                onPageClick: function (event, page) {
                                    plugin.fill_data(page);
                                }
                            });
                        }
                    }
                });
            });
        };
        plugin.getStarRating = function(rating) {
            let star;
            let half_star;
            let non_star;
            let max_star=5;
            while (rating > max_star) {
                rating = rating - max_star;
            }
            star = Math.floor(rating);
            non_star = Math.floor(max_star-rating);
            half_star = Math.ceil(max_star - star - non_star);
            return [star, half_star, non_star];
        };
        plugin.decodeHTML = function (html) {
            var txt = document.createElement('textarea');
            txt.innerHTML = html;
            return txt.value;
        };
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('input.check-box-category').iCheck({
                checkboxClass: 'icheckbox_minimal',
                radioClass: 'iradio_minimal',
                increaseArea: '20%'
            });
            $element.find('input.check-box-service').iCheck({
                checkboxClass: 'icheckbox_minimal',
                radioClass: 'iradio_minimal',
                increaseArea: '20%'
            });
            var triggeredByChild = false;
            let $checkbox_category = $element.find('.check-box-category');
            let $checkbox_service = $element.find('.check-box-service');
            $checkbox_category.on('ifChecked', function (event) {
                let $block_label = $(this).closest('.block-label');
                let $ul_list_service = $block_label.next();
                $ul_list_service.find('.check-box-service').iCheck('check');
                triggeredByChild = false;
            });


            $checkbox_category.on('ifUnchecked', function (event) {
                let $block_label = $(this).closest('.block-label');
                let $ul_list_service = $block_label.next();
                if (!triggeredByChild) {
                    $ul_list_service.find('.check-box-service').iCheck('uncheck');
                }
                triggeredByChild = false;
            });
            $checkbox_service.on('ifUnchecked', function (event) {
                let $ul_list_service = $(this).closest('.ul-list-service');
                let $block_label = $ul_list_service.prev();
                triggeredByChild = true;
                $block_label.find('.check-box-category').iCheck('uncheck');
            });
            $checkbox_service.on('ifChecked', function (event) {
                let $ul_list_service = $(this).closest('.ul-list-service');
                let $block_label = $ul_list_service.prev();
                let $current_service=$ul_list_service.find('.check-box-service');
                if ($current_service.filter(':checked').length === $current_service.length) {
                    $block_label.find('.check-box-category').iCheck('check');
                }
            });

            $element.find('.ul-list-service').slideUp();
            $element.find('.block-label').click(function (e) {
                let $ul_list_service = $(this).next();
                $ul_list_service.slideToggle();
                $(this).find('i.icon-nb-down-arrow').toggleClass('active')
            });

            $element.find('select.list-location').select2();
            $element.find('select.list-employee').select2();
            $element.find('select.sorting-training').select2();
            $element.find("select").change(function (e) {
                plugin.search_by_filter();
            });
            $element.find('input[name="keyword"].search').change(function (e) {
                plugin.search_by_filter();
            });
            $element.find('input.check-box-service').on('ifChanged', function (event) {
                plugin.search_by_filter();
            });
           plugin.search_by_filter();
            $element.find(".calendar").datepicker({
                altField: "#alternate",
                altFormat: "DD, d MM, yy",
                onSelect: function (date, instant) {
                    plugin.search_by_filter();
                },
            });
        };
        plugin.example_function = function () {
        };
        plugin.init();
    };
    $.fn.view_find_event_new = function (options) {
        return this.each(function () {
            if (undefined === $(this).data('view_find_event_new')) {
                let plugin = new $.view_find_event_new(this, options);
                $(this).data('view_find_event_new', plugin);
            }
        });
    }
})(jQuery);
