"use strict";
(function ($) {
    $.view_list_service = function (element, options) {
        let defaults = {
            list_service_by_category: [],
            html_service_item: '',
            html_category_item: ''
        };
        let plugin = this;
        plugin.settings = {};
        let $element = $(element);
        plugin.validate_category = function ($item_category) {
            let name = $item_category.find('div.name').text();
            if (name.trim() === "") {
                $.alert({
                    title: 'Error',
                    content: 'category name must not empty !',
                });
                return false;
            }
            return true;
        };
        plugin.save_category = function ($item_category) {
            let id = $item_category.data('id');
            let category_name = $item_category.find('div.name').text();
            let data = {
                id: id,
                name: category_name,
                task: "category.ajax_save"
            };
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: data,
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.result === "success") {
                        $item_category.find('div.name').editable("finish");
                        $item_category.find('div.name').removeClass('editable');
                        $item_category.find('.category-save').hide();
                        $item_category.find('.category-edit').show();
                        $item_category.find('.category-cancel').hide();
                        $item_category.find('.category-clone').show();
                        $item_category.find('.category-remove').show();
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.delete_category = function ($item_category) {
            let id = $item_category.data('id');
            let data = {
                list_delete_category_id: id,
                task: "category.ajax_delete"
            };
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: data,
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.result === "success") {
                        $item_category.fadeOut(300, function () {
                            $(this).delete();
                            $element.find('.list-category').sortable('refresh');
                        });
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.clone_category = function ($item_category) {
            let id = $item_category.data('id');
            let data = {
                id: id,
                task: "category.duplicate"
            };
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: data,
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.result === "success") {
                        let category = response.data;
                        let $new_item_category = $item_category.clone();
                        $new_item_category.insertAfter($item_category);
                        $new_item_category.data(id, category.id);
                        $element.find('.list-category').sortable('refresh');
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.add_new_service = function () {
            let $item_category_active = $element.find('.wrapper-category-item.active');
            let category_id = $item_category_active.data('id');
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    category_id: category_id,
                    task: "service.ajax_get_item"
                },
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.result === "success") {
                        loadScripts(response);
                        $wooBooking.getDrawer().find('.drawerEl-content').html(response.data);
                        $('body').append(response.data_script);
                        $wooBooking.getDrawer().find('.toolbar-btn-save').data('task', "service.ajax_save");
                        $wooBooking.getDrawer().find('.toolbar-btn-duplicate').prop('disabled', true);
                        $wooBooking.getDrawer().find('.toolbar-btn-published').prop('disabled', true);
                        $wooBooking.getDrawer().find('.toolbar-btn-delete').prop('disabled', true);
                        $wooBooking.getDrawer().drawer('toggle');
                        $wooBooking.getDrawer().find('h4.title').html('Add new');
                        $element.find('.view-service-form').find('.service-tab a').on('click', function (e) {
                            e.preventDefault();
                            $(this).tab('show');
                            $element.find('.service-tab a').removeClass('active');
                            $(this).addClass('active');
                        });
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.add_new_category = function () {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    task: "category.ajax_add_new_category"
                },
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.result === "success") {
                        loadScripts(response);
                        let category = response.data;
                        let $item_category = $(plugin.settings.html_category_item);
                        $item_category.find('div.name').html(category.name);
                        $item_category.data('id', category.id);
                        $item_category.find('div.name').editable();
                        $element.find('.list-category').append($item_category);
                        $element.find('.list-category').sortable('refresh');
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        }
        plugin.edit_service = function ($item_service) {
            let id = $item_service.data('id');
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    task: "service.ajax_get_item",
                    id: id
                },
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.result === "success") {
                        $wooBooking.loadScripts(response);
                        $wooBooking.getDrawer().find('.drawerEl-content').html(response.data);
                        $('body').append(response.data_script);
                        $wooBooking.getDrawer().find('.toolbar-btn-save').data('task', "service.ajax_save");
                        $wooBooking.getDrawer().find('.toolbar-btn-duplicate').data('task', "service.ajax_duplicate");
                        $wooBooking.getDrawer().find('.toolbar-btn-duplicate').data('id', id);
                        $wooBooking.getDrawer().find('.toolbar-btn-delete').data('id', id);
                        $wooBooking.getDrawer().find('.toolbar-btn-delete').data('task', "service.ajax_delete");
                        $wooBooking.getDrawer().find('.toolbar-btn-save').data('main_table', "main-table");
                        $wooBooking.getDrawer().find('.toolbar-btn-duplicate').prop('disabled', false);
                        $wooBooking.getDrawer().find('.toolbar-btn-published').prop('disabled', false);
                        $wooBooking.getDrawer().find('.toolbar-btn-delete').prop('disabled', false);
                        $wooBooking.getDrawer().find('h4.title').html(`Edit service: ${id}`);
                        $wooBooking.getDrawer().drawer('toggle');
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.update_order_category = function ($item) {
            let list_ordering = [];
            $element.find('.list-category .wrapper-category-item').each(function (ordering, item) {
                let ordering_item = {
                    id: $(item).data('id'),
                    ordering: ordering + 1
                };
                list_ordering.push(ordering_item);
            });
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    task: "categories.ajax_sorting",
                    list_ordering: list_ordering
                },
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {

                    response = JSON.parse(response);
                    if (response.result === "success") {
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.update_order_service = function ($item) {
            let category_id = $item.data('category_id');
            let id = $item.data('id');
            let list_ordering = [];
            $element.find(`.list-service-by-category[data-category_id="${category_id}"] .wrapper-service-item`).each(function (ordering, item) {
                let ordering_item = {
                    id: $(item).data('id'),
                    ordering: ordering + 1
                };
                list_ordering.push(ordering_item);
            });
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    task: "services.ajax_sorting",
                    list_ordering: list_ordering
                },
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {

                    response = JSON.parse(response);
                    if (response.result === "success") {
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('input[type="checkbox"]').iCheck({
                checkboxClass: 'icheckbox_square-red',
                radioClass: 'iradio_square-red',
                increaseArea: '20%'
            });
            $element.find('.btn-add-service').click(function (e) {
                e.preventDefault();
                $wooBooking.getDrawer().drawer('toggle');
            });
            $element.find('.btn-edit-order').click(function (e) {
                e.preventDefault();
                $wooBooking.getDrawer().drawer('toggle');
            });
            $element.find('.list-category').sortable({
                axis: "y",
                stop: function (event, ui) {
                    plugin.update_order_category(ui.item);
                }
            });
            $wooBooking.settings.call_back_when_save_success = plugin.call_back_when_save_success;
            $wooBooking.settings.call_back_when_duplicate_success = plugin.call_back_when_duplicate_success;
            $wooBooking.settings.call_back_when_delete_success = plugin.call_back_when_delete_success;
            $element.find('.btn-add-category').click(function (e) {
                plugin.add_new_category();
            });
            $element.find('.btn-add-new-service').click(function (e) {
                plugin.add_new_service();
            });
            $element.find('.wrapper-category-item').live('click', function (e) {
                $element.find('.wrapper-category-item').removeClass('active');
                $(this).addClass('active');
            });
            $element.find('.wrapper-category-item:first').trigger('click');
            $element.find('.btn-category-edit').live('click', function (e) {
                let $category_item = $(this).closest('.wrapper-category-item');
                $category_item.find('div.name').editable({
                    multiline: false,
                    saveDelay: 600,
                    autoselect: true,
                    save: function (instance) {
                    }
                }).addClass('editable');
                $category_item.find('li.category-save').show();
                $category_item.find('li.category-cancel').show();
                $category_item.find('li.category-clone').hide();
                $category_item.find('li.category-remove').hide();
                $category_item.find('li.category-edit').hide();
            });
            $element.find('.icheckbox_square-red').click(function (e) {
                let $wrapper_service_item = $(this).closest('.wrapper-service-item');
                let service_id = $wrapper_service_item.data('id');
                $wrapper_service_item.find('.selected').toggle();
                let checkBoxes = $wrapper_service_item.find('.delete-service');
                checkBoxes.prop("checked", !checkBoxes.prop("checked"));
            });
            $element.find('.btn-delete-service').click(function (e) {
                let list_delete_service_id = [];
                $element.find('.delete-service:checked').each(function () {
                    list_delete_service_id.push($(this).val());
                });
                if (list_delete_service_id.length === 0) {
                    $.alert({
                        title: 'Error',
                        content: 'Please choose service before delete!'
                    });
                    return false;
                }
                $.confirm({
                    title: 'Confirm',
                    content: 'Are you sure delete this service ?',
                    buttons: {
                        confirm: function () {
                            $.ajax({
                                type: "POST",
                                dataType: "json",
                                url: wpbookingpro_root_url + wpbookingpro_api_task,
                                data: {
                                    task: "service.ajax_delete",
                                    list_delete_service_id: list_delete_service_id
                                },
                                success: function (response) {
                                    location.reload(true);
                                }
                            });
                        },
                        cancel: function () {
                        }
                    }
                });
            });
            $element.find('.btn-category-save').live('click', function (e) {
                let $item_category = $(this).closest('.wrapper-category-item');
                if (!plugin.validate_category($item_category)) {
                    return false;
                }
                $.confirm({
                    title: 'Confirm',
                    content: 'Are you sure save this item ?',
                    buttons: {
                        confirm: function () {
                            plugin.save_category($item_category);
                        },
                        cancel: function () {
                        }
                    }
                });
            });
            $element.find('.btn-category-cancel').live('click', function (e) {
                let $item_category = $(this).closest('.wrapper-category-item');
                $.confirm({
                    title: 'Confirm',
                    content: 'Are you sure cancel this item ?',
                    buttons: {
                        confirm: function () {
                            let id = $item_category.data('id');
                            id = parseInt(id);
                            let list_service_by_category = plugin.settings.list_service_by_category;

                            for (let i = 0; i < list_service_by_category.length; i++) {
                                let item = list_service_by_category[i];
                                if (id === parseInt(item.id)) {
                                    $item_category.find('div.name').html(item.name);
                                    break;
                                }
                            }
                            $item_category.find('div.name').editable("finish");
                            $item_category.find('div.name').removeClass('editable');
                            $item_category.find('.category-save').hide();
                            $item_category.find('.category-edit').show();
                            $item_category.find('.category-cancel').hide();
                            $item_category.find('.category-clone').show();
                            $item_category.find('.category-remove').show();
                        },
                        cancel: function () {
                        }
                    }
                });
            });
            $element.find('.btn-category-remove').live('click', function (e) {
                let $item_category = $(this).closest('.wrapper-category-item');
                $.confirm({
                    title: 'Confirm',
                    content: 'All service this item will be delete! Are you sure delete this category ?',
                    buttons: {
                        confirm: function () {
                            plugin.delete_category($item_category);
                        },
                        cancel: function () {
                        }
                    }
                });
            });
            $element.find('.list-service-by-category').click(function (e) {
                $(this).tab('show');
            });
            $element.find('.btn-category-clone').live('click', function (e) {
                let $item_category = $(this).closest('.wrapper-category-item');
                plugin.clone_category($item_category);
            });
            $element.find('.list-service-by-category').sortable({
                axis: "y",
                stop: function (event, ui) {
                    plugin.update_order_service(ui.item);
                }
            });
            $element.find('.wrapper-service-item').live('click', function (e) {
                let $item_service = $(this);
                plugin.edit_service($item_service);
            });
            $element.find('.checked-all').click(function (e) {
                $element.find('table.list-service').find('.checkbox-item').prop('checked', $(this).is(':checked'));
            });
            $element.find('table.list-service').find('.checkbox-item').click(function (e) {
                let checkall = true;
                let $all_checkbox = $element.find('table.list-service').find('.checkbox-item');
                for (let i = 0; i < $all_checkbox.length; i++) {
                    let $checkbox = $($all_checkbox[i]);
                    if (!$checkbox.is(':checked')) {
                        checkall = false;
                    }
                }
                if (checkall) {
                    $element.find('.checked-all').prop('checked', true);
                } else {
                    $element.find('.checked-all').prop('checked', false);
                }
            });
            $element.find('.btn-add-new').click(function (e) {
                let id = $(this).data('id');
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: wpbookingpro_root_url + wpbookingpro_api_task,
                    data: {
                        action: "get_data",
                        id: id
                    },
                    success: function (response) {
                        $wooBooking.getDrawer().find('.hy-drawer-content').html(response);
                        $wooBooking.getDrawer().drawer('toggle');
                        $element.find('.view-service-form').find('.service-tab a').on('click', function (e) {
                            e.preventDefault();
                            $(this).tab('show')
                        })
                    }
                });
            });
            $element.find('.btn-delete').click(function (e) {
                let id = $(this).data('id');
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: wpbookingpro_root_url + wpbookingpro_api_task,
                    data: {
                        action: "get_data",
                        id: id
                    },
                    beforeSend: function () {
                        $('body').loadingModal();
                    },
                    error: function (xhr) {
                        $.alert({
                            title: 'Error',
                            content: 'there are some error please contact admin !',
                        });
                    },
                    complete: function () {
                        $('body').loadingModal('destroy');
                    },
                    success: function (response) {
                        $wooBooking.getDrawer().find('.hy-drawer-content').html(response);
                        $wooBooking.getDrawer().drawer('toggle');
                        $element.find('.view-service-form').find('.service-tab a').on('click', function (e) {
                            e.preventDefault();
                            $(this).tab('show')
                        })
                    }
                });
            });
            $element.find('.btn-Attendees').click(function (e) {
                let id = $(this).data('id');
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: wpbookingpro_root_url + wpbookingpro_api_task,
                    data: {
                        action: "get_data",
                        id: id
                    },
                    beforeSend: function () {
                        $('body').loadingModal();
                    },
                    error: function (xhr) {
                        $.alert({
                            title: 'Error',
                            content: 'there are some error please contact admin !',
                        });
                    },
                    complete: function () {
                        $('body').loadingModal('destroy');
                    },
                    success: function (response) {
                        $wooBooking.getDrawer().drawer('toggle');
                        $element.find('.view-service-form').find('.service-tab a').on('click', function (e) {
                            e.preventDefault()
                            $(this).tab('show')
                        })
                    }
                });
            });
            $wooBooking.call_back_when_save_success = function (data, is_new) {
                location.reload(true);
            }
        };
        plugin.call_back_when_duplicate_success = function (item_service) {
        };
        plugin.call_back_when_save_success = function (item_service, is_new) {


            if (is_new) {
                let $service_item = $(plugin.settings.html_service_item);
                $service_item.data('id', item_service.id);
                $service_item.data('category_id', item_service.category_id);
                $service_item.attr('data-id', item_service.id);
                $service_item.attr('data-category_id', item_service.category_id);
                $service_item.find('.service-image').attr('src', `${wpbookingpro_root_url_plugin}/${item_service.image}`);
                $service_item.find('.name').html(item_service.name);
                $service_item.find('.duration').html(item_service.duration);
                $service_item.find('.price').html(item_service.price);
                $service_item.appendTo($element.find(`.list-service-by-category[data-category_id="${item_service.category_id}"]`));
                $element.find(`.list-service-by-category[data-category_id="${item_service.category_id}"]`).sortable('refresh');
            } else {

                let $service_item = $element.find(`.wrapper-service-item[data-id="${item_service.id}"]`);
                $service_item.data('category_id', item_service.category_id);
                $service_item.attr('data-category_id', item_service.category_id);
                $service_item.find('.service-image').attr('src', `${wpbookingpro_root_url_plugin}/${item_service.image}`);
                $service_item.find('.name').html(item_service.name);
                $service_item.find('.duration').html(item_service.duration);
                $service_item.find('.price').html(item_service.price);
            }
        };
        plugin.call_back_when_delete_success = function (id, data) {
            $element.find(`.wrapper-service-item[data-id="${id}"]`).remove();
            $element.find(`.list-service-by-category`).sortable({});
        };
        plugin.init();
    };
    $.fn.view_list_service = function (options) {
        return this.each(function () {
            if (undefined === $(this).data('view_list_service')) {
                let plugin = new $.view_list_service(this, options);
                $(this).data('view_list_service', plugin);
            }
        });
    }
})(jQuery);