(function ($) {
    $.field_rate = function (element, options) {
        var defaults = {
            values: []
        }
        var plugin = this;
        plugin.settings = {};
        var $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            plugin.settings.element = element;
            var values = plugin.settings.values;

            if (values.length > 0) {
                $.each(values, function (index, rate) {
                    plugin.set_daterangepicker($($element.find('.list-item input.rate')[index]), rate);
                });
            } else {
                plugin.set_daterangepicker($element.find('.list-item input.rate'));
            }
            $element.find('.btn-add').click(function (e) {
                plugin.set_task_when_click();
            });
        };
        plugin.set_daterangepicker = function ($input_element, rate) {
            $input_element.daterangepicker({
                opens: 'left',
                timePicker: true,
                startDate: (typeof rate !== "undefined" && rate.from !== "") ? moment(rate.from).startOf('minute') : moment().startOf('minute'),
                endDate: (typeof rate !== "undefined" && rate.to !== "") ? moment(rate.to).startOf('minute') : moment().startOf('minute').add(32, 'minute'),
                locale: {
                    format: 'M/DD/YYYY hh:mm A'
                }
            }, function (start, end, label) {

                $input_element = $(this.element);
                let $item = $input_element.closest('.item');
                let rate = `${start.format('YYYY-MM-DD hh:mm A')};${end.format('YYYY-MM-DD hh:mm A')}`;
                $item.find(`input[name="${plugin.settings.input_name}"]`).val(rate);
            });
        };
        plugin.set_task_when_click = function () {
            var $item_rate = $(plugin.settings.item_rate);
            $item_rate.appendTo($element.find('.list-item'));
            plugin.set_daterangepicker($item_rate.find('input.rate'));
            $item_rate.find('.btn-add').click(function (e) {
                plugin.set_task_when_click();
            });
            $item_rate.find('.btn-close-item').click(function (e) {
                if ($element.find('.list-item .item').length > 1) {
                    $element.find('.list-item .item:last-child').remove();
                }
            })
        }
        plugin.example_function = function () {
        };
        plugin.init();
    }
    $.fn.field_rate = function (options) {

        return this.each(function () {

            if (undefined == $(this).data('field_rate')) {
                var plugin = new $.field_rate(this, options);
                $(this).data('field_rate', plugin);
            }
        });
    }
})(jQuery);
