(function ($) {
    $.field_calendarrate = function (element, options) {
        var defaults = {
            service_id: 0,
            list_rate: []
        }
        var plugin = this;
        plugin.settings = {}
        var $element = $(element),
            element = element;

        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            let service_id = plugin.settings.service_id;
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    task: "services.get_service_available_date",
                    service_id: service_id
                },
                beforeSend: function () {
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.result === "success") {
                        $element.find('.calendar').datepicker({
                            altField: "#alternate",
                            altFormat: "DD, d MM, yy",
                            beforeShowDay: function (date) {
                                let list_rate = response.data[0].list_rate;
                                var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                                var date = moment(date);
                                for (let i = 0; i < list_rate.length; i++) {
                                    let current_rate = list_rate[i];
                                    let startDate = moment(current_rate.from);
                                    let endDate = moment(current_rate.to);
                                    if (date.isBefore(endDate) && date.isAfter(startDate) || (date.isSame(startDate) || date.isSame(endDate))) {
                                        return [true, `date-${string}`];
                                    }
                                }
                                return [false, `date-${string}`];
                            },
                            onSelect: function (date, instant) {
                                plugin.get_rates_of_date(service_id, date);
                            },
                        });
                    }
                }
            })
            $element.find('.btn-book-now').click(function (e) {
                $('.form-input').animate({width: 'toggle'}, "slow");
                $('.select-date').animate({width: 'toggle'}, "slow");
            });
        };
        plugin.get_rates_of_date = function (service_id, date) {
            let $select_date_time = $element.find('.select-date-time');
            let data = {};
            data.service_id = service_id;
            data.date = date;
            let data_post = {
                task: "rates.get_rates_of_date",
                data: data,
            };
            setTimeout(function () {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: wpbookingpro_root_url + wpbookingpro_api_task,
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(data_post),
                    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);

                        $element.find('.btn-book-now').hide();
                        if (response.result === "success") {
                            let data = response.data;
                            let list_rate = [];
                            $.each(data, function (index, rate) {
                                list_rate.push(`<li class="rate-item"><span  data-event_id="${rate.id}" class="time "><i class="fas fa-check"></i> ${moment(rate.from).format('HH:mm A')}-${moment(rate.to).format('HH:mm A')}</span><input style="display: none" value="${rate.id}" type="checkbox" name="rates[]"></li>`);
                            });
                            list_rate = list_rate.join('');

                            let moment_date = moment(date);
                            let date_item = moment_date.format('YYYY-MM-DD');
                            let $td = $element.find(`.calendar td.date-${date_item}`);
                            let $tr = $td.closest('tr');
                            let $insert_tr = $(`<tr><td colspan="8"><ul class="list-range-time">${list_rate}</ul></td></tr>`);

                            $insert_tr.insertAfter($tr);
                            $insert_tr.find('.time').click(function (e) {
                                let $list_range = $(this).closest('.list-range-time');
                                let $rate_item = $(this).closest('.rate-item');
                                $list_range.find('.time').removeClass('active');
                                $(this).addClass('active');
                                $element.find('.btn-book-now').show();

                                $list_range.find('input[name="rates[]"]').prop('checked', false);
                                $list_range.find('input[name="rates[]"]').attr('data-checked', "fasle");

                                $rate_item.find('input[name="rates[]"]').prop('checked', true);
                                $rate_item.find('input[name="rates[]"]').attr('data-checked', "true");
                            });
                        }
                    }
                });
            }, 300);
            console.log("length", $element.find('form.basic-data').length);
            $('form.basic-data').serializeObject().done(function (data) {

            });
        }
        plugin.example_function = function () {
        };
        plugin.init();
    }

    $.fn.field_calendarrate = function (options) {

        return this.each(function () {

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