(function ($) {
    $.field_extra = function (element, options) {
        var defaults = {
            content_extra: '',
            input_name: ''
        }
        var plugin = this;
        plugin.settings = {}
        var $element = $(element), 
            element = element;    
        
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('.list-extra').sortable({
                axis: "y"
            });
            $element.find('.wrapper-extra-item').each(function (e) {
                let $item_extra = $(this);
                plugin.setting_wrapper_item_extra($item_extra);
            });
            $element.find('.btn-add-extra').click(function (e) {
                if (!plugin.check_other_opening() || !plugin.validate()) {
                    return false;
                }
                let $item_extra = $(plugin.settings.content_extra);
                $element.find('.list-extra').append($item_extra);
                $item_extra.find('.body').show();
                $item_extra.data('new', true);
                plugin.setting_wrapper_item_extra($item_extra);
                $element.find('.list-extra').sortable('refresh');
            });
        };
        plugin.setting_wrapper_item_extra = function ($item_extra) {
            $item_extra.find('.extra-time-buffer').select2();
            $item_extra.find('.handle-counter').each(function (e) {
                $(this).handleCounter({
                    onChange: function (text) {
                    },
                    onMinimum: function () {
                    },
                    onMaximize: function () {
                    }
                });
            });
            $item_extra.find('.extra-price').autoNumeric('init', {});
            $item_extra.find(".btn-extra-edit").click(function () {
                if (!plugin.check_other_opening() || !plugin.validate()) {
                    return false;
                }
                $(this).hide();
                let $wrapper_item_extra = $(this).closest('.wrapper-extra-item');
                $wrapper_item_extra.find('.body').toggle("slow", function () {
                    
                });
            });
            $item_extra.find(".btn-extra-cancel").click(function () {
                let $wrapper_item_extra = $(this).closest('.wrapper-extra-item');
                $.confirm({
                    title: 'Confirm',
                    content: 'Are you sure cancel change extra ?',
                    buttons: {
                        confirm: function () {
                            let new_item = $wrapper_item_extra.data('new');
                            if (new_item) {
                                $wrapper_item_extra.remove();
                            } else {
                                $wrapper_item_extra.find('.body').toggle("slow", function () {
                                    
                                });
                                $wrapper_item_extra.find('.btn-extra-edit').show();
                                let id = $wrapper_item_extra.data('id');
                                if (id) {
                                    let extra_item = plugin.settings.list_extra[id];
                                    $wrapper_item_extra.find('input.extra-name').val(extra_item.name);
                                    $wrapper_item_extra.find('.extra-time-buffer').val(extra_item.duration);
                                    $wrapper_item_extra.find('.extra-price').autoNumeric('set', extra_item.price);
                                    $wrapper_item_extra.find('.extra-description').val(extra_item.description);
                                }
                            }
                        },
                        cancel: function () {
                        }
                    }
                });
            });
            $item_extra.find(".btn-extra-save").click(function () {
                let $wrapper_item_extra = $(this).closest('.wrapper-extra-item');
                if (!plugin.validate()) {
                    return false;
                }
                $.confirm({
                    title: 'Confirm',
                    content: 'Are you sure save extra ?',
                    buttons: {
                        confirm: function () {
                            $wrapper_item_extra.find('.body').toggle("slow", function () {
                                
                            });
                            $wrapper_item_extra.data('new', false);
                            $wrapper_item_extra.find('.btn-extra-remove').show();
                            $wrapper_item_extra.find('.btn-extra-edit').show();
                            let item = {};
                            item.name = $wrapper_item_extra.find('input.extra-name').val();
                            item.duration = $wrapper_item_extra.find('.extra-time-buffer').val();
                            item.price = $wrapper_item_extra.find('.extra-price').autoNumeric('get');
                            item.quality = $wrapper_item_extra.find('.increment-number').val();
                            item.description = $wrapper_item_extra.find('.extra-description').val();
                            $wrapper_item_extra.find('span.quality').text(item.quality);
                            $wrapper_item_extra.find('span.price').text(item.price);
                            $wrapper_item_extra.find('span.duration').text(item.duration);
                            plugin.update_data();
                        },
                        cancel: function () {
                        }
                    }
                });
            });
            $item_extra.find(".extra-name").keyup(function () {
                let $wrapper_item_extra = $(this).closest('.wrapper-extra-item');
                let extra_name = $(this).val();
                $wrapper_item_extra.find('span.extra-name').text(extra_name);
            });
            $item_extra.find(".btn-extra-remove").click(function () {
                let $wrapper_item_extra = $(this).closest('.wrapper-extra-item');
                $.confirm({
                    title: 'Confirm',
                    content: 'Are you sure delete this extra ?',
                    buttons: {
                        confirm: function () {
                            $wrapper_item_extra.remove();
                        },
                        cancel: function () {
                        }
                    }
                });
            });
        };
        plugin.check_other_opening = function () {
            for (let i = 0; i < $element.find('.wrapper-extra-item').length; i++) {
                let $item_extra = $($element.find('.wrapper-extra-item').get(i));
                let element_extra_id = $item_extra.attr('id');
                if ($item_extra.find('.body').is(':visible')) {
                    $item_extra.find('.body').addClass('error');
                    $element.scrollTo(`#${element_extra_id}`, 800);
                    return false;
                }
            }
            return true;
        }
        plugin.validate = function () {
            $element.find('.wrapper-extra-item .body').removeClass('error');
            for (let i = 0; i < $element.find('.wrapper-extra-item').length; i++) {
                let $item_extra = $($element.find('.wrapper-extra-item').get(i));
                $item_extra.attr('id', `extra-id-${i}`);
            }
            for (let i = 0; i < $element.find('.wrapper-extra-item').length; i++) {
                let $item_extra = $($element.find('.wrapper-extra-item').get(i));
                let name = $item_extra.find('input.extra-name').val();
                let duration = $item_extra.find('.extra-time-buffer').val();
                let price = $item_extra.find('.extra-price').autoNumeric('get');
                let quality = $item_extra.find('.increment-number').val();
                if (name.trim() === "") {
                    $.alert({
                        title: 'Error',
                        content: 'extra name must not empty',
                    });
                    $item_extra.find('.extra-name').focus();
                    $item_extra.find('.body').show();
                    return false;
                }
                if (price.trim() === "") {
                    $.alert({
                        title: 'Error',
                        content: 'extra price must not empty',
                    });
                    $item_extra.find('.extra-price').focus();
                    $item_extra.find('.body').show();
                    return false;
                }
                price = parseInt(price);
                if (price === 0) {
                    $.alert({
                        title: 'Error',
                        content: 'extra price must not zero',
                    });
                    $item_extra.find('.extra-price').focus();
                    $item_extra.find('.body').show();
                    return false;
                }
                if (duration.trim() === "") {
                    $.alert({
                        title: 'Error',
                        content: 'please select duration',
                    });
                    $item_extra.find('.extra-time-buffer').focus();
                    $item_extra.find('.body').show();
                    return false;
                }
                if (quality.trim() === "") {
                    $.alert({
                        title: 'Error',
                        content: 'extra quality must not zero or not empty',
                    });
                    $item_extra.find('.increment-number').focus();
                    $item_extra.find('.body').show();
                    return false;
                }
                if (quality.trim() === "") {
                    $.alert({
                        title: 'Error',
                        content: 'extra quality must not zero or not empty',
                    });
                    $item_extra.find('.increment-number').focus();
                    $item_extra.find('.body').show();
                    return false;
                }
            }
            return true;
        };
        plugin.update_data = function () {
            $element.find('.wrapper-extra-item').each(function (e) {
                let $item_extra = $(this);
                let item = {};
                let id = $item_extra.data('id');
                if (id) {
                    item.id = id;
                }
                item.name = $item_extra.find('input.extra-name').val();
                item.duration = $item_extra.find('.extra-time-buffer').val();
                item.price = $item_extra.find('.extra-price').autoNumeric('get');
                item.quality = $item_extra.find('.increment-number').val();
                item.description = $item_extra.find('.extra-description').val();
                let str_base64_encode = $.base64('encode', JSON.stringify(item));
                $item_extra.find(`input[name="${plugin.settings.input_name}[]"]`).val(str_base64_encode);
            });
        };
        plugin.example_function = function () {
        };
        plugin.readURL = function (input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    let $image = `<li class="image-item" ><i class="far fa-trash-alt remove"></i><img class="image" src="${e.target.result}"></li>`;
                    $element.find('.list-image').prepend($image);
                    $element.find('.list-image').sortable('refresh');
                    $('#blah').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        plugin.init();
    }
    
    $.fn.field_extra = function (options) {
        
        return this.each(function () {
            
            if (undefined == $(this).data('field_extra')) {
                var plugin = new $.field_extra(this, options);
                $(this).data('field_extra', plugin);
            }
        });
    }
})(jQuery);