"use strict";
(function ($) {
    $.view_service_detail = function (element, options) {
        let defaults = {
            list_event:[],
            person:1,
            service_item:[],
            booking_style:'',
            deposit_percent:'',
            limit:'',
            list_review:'',
            coupon: {},
            format_currency:'',
            rate_exchange:''
        }
        let plugin = this;
        plugin.settings = {}
        let $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            let list_event=plugin.settings.list_event;
            let service_item=plugin.settings.service_item;
            let booking_style = plugin.settings.booking_style;
            let limit = plugin.settings.limit;
            let list_review = plugin.settings.list_review;
            let deposit_percent = parseInt(plugin.settings.deposit_percent);
            let $gallery_large = $element.find('.block-gallery-slider-large');
            let $gallery_small = $element.find('.block-gallery-slider-small');
            let format_currency = plugin.settings.format_currency;
            let rate_exchange = plugin.settings.rate_exchange;
            $gallery_large.slick({
                slidesToShow: 1,
                slidesToScroll: 1,
                prevArrow: ".arrow-prev",
                nextArrow: ".arrow-next",
                fade: true,
                asNavFor: '.block-gallery-slider-small',
                responsive: [
                    {
                        breakpoint: 576,
                        settings: {
                            arrows: false,
                            slidesToShow: 1,
                            slidesToScroll: 1
                        }
                    }
                ]

            });
            setTimeout(function () {
                $(window).trigger('resize');
                $gallery_small.slick({
                    slidesToShow: 4,
                    slidesToScroll: 1,
                    asNavFor: '.block-gallery-slider-large',
                    arrows:false,
                    focusOnSelect: true,
                    responsive: [
                        {
                            breakpoint: 576,
                            settings: {
                                arrows: false,
                                dots:true,
                                slidesToShow: 2,
                                slidesToScroll: 2
                            }
                        }
                    ]
                });

            }, 10);
            let person=plugin.settings.person;
            $element.find('form[name="client-form"]').each(function (e) {
                $(this).validate({
                    ignore: ""
                });
            });
            let $employee_input = $element.find('input[name=employee_id]');
            $employee_input.on('change', function () {
                let employee_id= $(this).val();
                let list_employee = service_item.list_employee;
                let is_repeat = $element.find('.is-recurring input[type="radio"]:checked').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                let employee_choosen = list_employee.find(function (employee) {
                    if(employee.id == employee_id) {
                        return employee;
                    }
                });
                $element.find('.trainer-info').text(`${employee_choosen.first_name} ${employee_choosen.last_name}`);

                let event_id = $element.find('input[name="event_id"]').val();
                let event_choosen = list_event.find(function (event) {
                    if(event.id == event_id) {
                        return event;
                    }
                });

                if(is_repeat === '0') {
                    let time_start = moment($element.find('input[name="calendar"]').val()).format('HH:mm:ss');
                    if(event_id.trim() !== '' && Object.keys(event_choosen).length !== 0) {
                        $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(event_choosen.price) * parseFloat(rate_exchange)).toFixed(2)));
                        $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(event_choosen.price) * parseFloat(rate_exchange)).toFixed(2)));
                    } else {
                        $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                        $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                    }
                    for(let i=0; i< list_employee.length;i++) {
                        if(list_employee[i].id == employee_id && moment(time_start,'HH:mm:ss').valueOf() >= array_start_time[i].valueOf() && moment(time_start,'HH:mm:ss').valueOf() <= array_end_time[i].valueOf()) {
                            $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i]).toFixed(2)));
                            $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i]).toFixed(2)));
                        }

                    }
                } else {
                    plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);

                }

            });

            let list_working_day= service_item.working_day;
            let array_day_by_number = [];
            if(typeof list_working_day !== 'undefined' && list_working_day !== null && list_working_day.trim() !== '' ) {
                list_working_day = JSON.parse(list_working_day);
                let week = ['Monday','Tuesday' ,'Wednesday' ,'Thursday' ,'Friday','Saturday','Sunday'];
                let array_diff = plugin.arr_diff(list_working_day, week);
                let day_of_week = {
                    'Sunday':0,
                    'Monday':1,
                    'Tuesday':2,
                    'Wednesday':3,
                    'Thursday':4,
                    'Friday':5,
                    'Saturday':6
                };
                for(const prop in day_of_week) {
                    for(let i = 0; i < array_diff.length; i++) {
                        if(prop === array_diff[i]) {
                            array_day_by_number.push(day_of_week[prop]);
                        }
                    }
                }
            }
            let open_time_hour = 0 ;
            let open_time_minute = 0 ;
            if(typeof service_item.open_time !== 'undefined') {
                open_time_hour = parseInt(service_item.open_time.split(':')['0']);
                open_time_minute = parseInt(service_item.open_time.split(':')['1']);
            }
            let close_time_hour = 0;
            let close_time_minute = 0;
            if (typeof service_item.close_time !== 'undefined') {
                close_time_hour = parseInt(service_item.close_time.split(':')['0']);
                close_time_minute = parseInt(service_item.close_time.split(':')['1']);
            }
            let time_disable_array = [];
            for(let i =0; i<=23;i++) {
                if(i < open_time_hour || i > close_time_hour){
                    time_disable_array.push(i);
                }
            }


            $element.find('.form_datetime').data("DateTimePicker").daysOfWeekDisabled ( array_day_by_number);
            $element.find('.form_datetime').data("DateTimePicker").disabledHours ( time_disable_array);
            $element.find('.form_datetime').data("DateTimePicker").disabledTimeIntervals (
                [[moment({h:0}), moment({h:open_time_hour,m:open_time_minute})],
                [moment({h:close_time_hour,m:close_time_minute}), moment({h:24})]]
            );
            $element.find('.time-start-recurring').data("DateTimePicker").disabledTimeIntervals (
                [[moment({h:0}), moment({h:open_time_hour,m:open_time_minute})],
                [moment({h:close_time_hour-(service_item.duration)%10,m:close_time_minute - (service_item.duration - (service_item.duration)%10)*60}), moment({h:24})]]
            );
            $element.find('.time-end-recurring').data("DateTimePicker").disabledTimeIntervals (
                [[moment({h:0}), moment({h:open_time_hour,m:open_time_minute})],
                [moment({h:close_time_hour,m:close_time_minute}), moment({h:24})]]
            );
            $element.find('.form_datetime').on('dp.change', function (e) {
                let value = e.date;
                let time_start = moment(value).format('LT');
                let time_end = moment(value).add(service_item.duration,'hour').format('LT');
                let date_book=moment(value).format('YYYY-MM-DD');
                let list_employee = service_item.list_employee;
                let employee_id = $element.find('input[name="employee_id"]').val();
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));

                if(value !== '') {
                    $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                    $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                    for(let i=0; i< list_employee.length;i++) {
                        if(list_employee[i].id === employee_id && moment(time_start,'LT').valueOf() >= array_start_time[i].valueOf() && moment(time_start,'LT').valueOf() <= array_end_time[i].valueOf()) {
                            $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i]).toFixed(2)));
                            $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i]).toFixed(2)));
                        }

                    }
                    $element.find('.local-time').text(`${time_start} - ${time_end}`);
                    $element.find('.date-info').text(date_book);
                } else {
                    $element.find('.local-time').text('');
                    $element.find('.date-info').text('');
                }
            });
            $element.find('input.date-start-recurring').on('change',  function () {
                let date_start = $(this).val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                if(date_end !== '') {
                    $element.find('.date-info').text('from '+ date_start +' to '+date_end);
                }

                plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);

            });
            $element.find('input.date-end-recurring').on('change',  function () {
                let date_end = $(this).val();
                let date_start = $element.find('input.date-start-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                if(date_end !== '') {
                    $element.find('.date-info').text('from '+ date_start +' to '+date_end);
                }
                plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);


            });
            $element.find('input[name="type_recurring"]').on('change', function () {
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $(this).val();
                let day_of_week = [];
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                if(date_end !== '') {
                    $element.find('.date-info').text('from '+ date_start +' to '+date_end);
                }

                plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);



            });

            $element.find('input.time-start-recurring').on('dp.change', function (e) {
                let value = e.date;
                let time_start = moment(value).format('LT');
                let time_end = moment(value).add(service_item.duration,'hour').format('LT');
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let day_of_week = [];
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                if(value !== '') {
                    plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);

                    $element.find('.local-time').text(`${time_start} - ${time_end}`);
                } else {
                    $element.find('.local-time').text('');
                }

            });
            $element.find('.is-recurring-item input[type="radio"]').on('change', function () {
                let val = $(this).val();
                if(val === '1') {
                    let date_start = $element.find('input.date-start-recurring').val();
                    let date_end = $element.find('input.date-end-recurring').val();
                    if(date_end !== '') {
                        $element.find('.date-info').text('from '+ date_start +' to '+date_end);
                    }
                    $element.find('.total-day-recurring').show();
                    $element.find('.block-select-payment-schedule').slideDown();
                    $element.find('.block-payment-schedule-item').each(function (index, item) {
                        if(index === 0) {
                            $(item).find('input[type="radio"]').prop('checked',  true);
                        } else {
                            $(item).find('input[type="radio"]').prop('checked',  false);
                        }
                    });
                } else {
                    $element.find('.total-day-recurring').hide();
                    $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                    $element.find('.block-select-payment-schedule').slideUp()
                    $element.find('.block-payment-schedule-item').each(function (index, item) {
                        $(item).find('input[type="radio"]').prop('checked',  false);
                    });
                    $element.find('input[name="deposit_percent"]').val('');
                    $element.find('.deposit-block').hide();
                }
            });
            $element.find('input[name="payment_schedule"]').on('change', function () {
                let val = $(this).val();
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                if(date_end !== '') {
                    $element.find('.date-info').text('from '+ date_start +' to '+date_end);
                }
                if(val === 'pay-later') {
                    $element.find('.deposit-block').show();
                    $element.find('input[name="deposit_percent"]').val(deposit_percent);
                    $element.find('.payment-deposit').show();
                    $element.find('.payment-balance').show();
                    plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, val, day_of_week, deposit_percent, plugin.settings.coupon);

                } else {
                    $element.find('.deposit-block').hide();
                    $element.find('input[name="deposit_percent"]').val('');
                    $element.find('.payment-deposit').hide();
                    $element.find('.payment-balance').hide();
                }
            });
            $element.find('.block-number-week-recurring input[type="text"]').on('change', function () {
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                if(date_end !== '') {
                    $element.find('.date-info').text('from '+ date_start +' to '+date_end);
                }
                plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);

            });
            $element.find('.block-number-month-recurring input[type="text"]').on('change', function () {
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                if(date_end !== '') {
                    $element.find('.date-info').text('from '+ date_start +' to '+date_end);
                }
                let arrDayInMonth = plugin.getDayAnDateBetweenToDate(date_start, date_end);
                let block_input = $element.find('.block-specific-day-select').children('.block-input');
                $(block_input).empty()
                for(let i = 0; i< day_of_week.length; i++) {
                    let block_day = $(`<div class="wrapper-day-specific">
                                            <h6 class="title-specific-day">${day_of_week[i]}</h6>
                                        </div>`);
                    let block_date = $('<div class="wrapper-date-specific"></div>');
                    for(let j= 0; j < arrDayInMonth['0'].length; j++) {
                        if(day_of_week[i].toLowerCase() == arrDayInMonth['0'][j].toLowerCase()) {
                            let input_day = `<label>
                                                    <input type="checkbox" name="day_recurring_in_month[]" value="${arrDayInMonth['1'][j]}"/>
                                                    ${arrDayInMonth['1'][j]}
                                                </label>`;
                            $(block_date).append(input_day);
                            $(input_day).find('input[name="day_recurring_in_month[]"]').trigger('change');
                        }
                    }
                    $(block_date).find('input[name="day_recurring_in_month[]"]').on('change', function () {
                        plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week_onchange, deposit_percent, plugin.settings.coupon);
                    });
                    $(block_day).append(block_date);
                    $(block_input).append(block_day);
                }
                plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);

            });
            let day_of_week_onchange = [];

            $element.find('.day-off-week input[type="checkbox"]').on('change', function () {
                if($(this).is(":checked")) {
                    day_of_week_onchange.push($(this).val())
                } else {
                    let index = day_of_week_onchange.indexOf($(this).val());
                    if(index > -1) {
                        day_of_week_onchange.splice(index,1);
                    }
                }
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                let arrDayInMonth = plugin.getDayAnDateBetweenToDate(date_start, date_end);
                let block_input = $element.find('.block-specific-day-select').children('.block-input');
                $(block_input).empty()
                for(let i = 0; i< day_of_week_onchange.length; i++) {
                    let block_day = $(`<div class="wrapper-day-specific">
                                            <h6 class="title-specific-day">${day_of_week_onchange[i]}</h6>
                                        </div>`);
                    let block_date = $('<div class="wrapper-date-specific"></div>');
                    for(let j= 0; j < arrDayInMonth['0'].length; j++) {
                        if(day_of_week_onchange[i].toLowerCase() == arrDayInMonth['0'][j].toLowerCase()) {
                            let input_day = `<label>
                                                    <input type="checkbox" name="day_recurring_in_month[]" value="${arrDayInMonth['1'][j]}"/>
                                                    ${arrDayInMonth['1'][j]}
                                                </label>`;
                            $(block_date).append(input_day);
                        }
                    }
                    $(block_date).find('input[name="day_recurring_in_month[]"]').on('change', function () {
                        plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week_onchange, deposit_percent, plugin.settings.coupon);
                    });
                    $(block_day).append(block_date);
                    $(block_input).append(block_day);
                }
                plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week_onchange, deposit_percent, plugin.settings.coupon);

            });

            $element.find('.block-select-allday .block-input input[type="radio"]').on('change', function () {
                let  val = $(this).val();
                if(val === 'specific-day') {
                    $element.find('.block-specific-day-select').show();
                } else {
                    $element.find('.block-specific-day-select').hide();
                    $element.find('.block-specific-day-select .block-input input[type="checkbox"]').prop('checked', false);
                }
            });
            $element.find('.block-select-allday input[type="radio"]').on('change', function () {
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);
            });

            $element.find('.block-specific-day-select input[name="day_recurring_in_month[]"]').on('change', function () {
                let date_start = $element.find('input.date-start-recurring').val();
                let date_end = $element.find('input.date-end-recurring').val();
                let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let time_start = $element.find('input[name="time_start_recurring"]').val();
                let list_employee = service_item.list_employee;
                let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                let employee_id = $element.find('input[name="employee_id"]').val();
                let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);

            });
            $element.find('.btn-book-now').on('click',function (e) {
                let $form = $(this).closest('form[name="client-form"]');
                let is_repeat = $form.find('.is-recurring input[type="radio"]:checked').val();
                let type_repeat = $form.find('.block-type-of-recurring input[type="radio"]:checked').val();
                let allday_or_specificday = $form.find('.block-select-allday input[type="radio"]:checked').val();
                let employee_id = $form.find('input[name="employee_id"]').val();
                let time_value = $form.find('.mirror_field').val();
                let day_of_week = [];
                $element.find('input[name="day_of_week[]"]:checked').each(function () {
                    day_of_week.push($(this).val())
                });
                let day_specific_in_month = [];
                $form.find('input[name="day_recurring_in_month[]"]:checked').each(function () {
                    day_specific_in_month.push($(this).val())
                });
                let number_week_recurring = $form.find('input[name="number_week_recurring"]').val();
                let number_month_recurring = $form.find('input[name="number_month_recurring"]').val();
                let date_start_recurring = $form.find('input[name="date_start_recurring"]').val();
                let time_start_recurring = $form.find('input[name="time_start_recurring"]').val();
                let date_end_recurring = $form.find('input[name="date_end_recurring"]').val();
                let time_end_recurring = $form.find('input[name="time_end_recurring"]').val();
                if (employee_id === "") {
                    $('body,html').animate({
                        scrollTop: $element.find('.block-booking-information').offset().top
                    },500,"linear");
                    $.alert({
                        title:'',
                        content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your Expert</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                        container:'.block-alert',
                        buttons: {
                            formSubmit: {
                                text: '<i class="icon-nb-close"></i>',
                                btnClass: 'btn-red',
                            }
                        }
                    });
                    return false;
                }
                if(is_repeat === '0') {
                    if (time_value === "") {
                        $('body,html').animate({
                            scrollTop: $element.find('.block-booking-information').offset().top
                        },500,"linear");
                        $.alert({
                            title:'',
                            content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your Time</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                            container:'.block-alert',
                            buttons: {
                                formSubmit: {
                                    text: '<i class="icon-nb-close"></i>',
                                    btnClass: 'btn-red',
                                }
                            }
                        });
                        return false;
                    }
                } else {
                    if(date_start_recurring === '' || time_start_recurring === '' || date_end_recurring === '' || time_end_recurring === '') {
                        $('body,html').animate({
                            scrollTop: $element.find('.block-set-recurring-time').offset().top
                        },500,"linear");
                        $.alert({
                            title:'',
                            content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your time</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                            container:'.block-alert',
                            buttons: {
                                formSubmit: {
                                    text: '<i class="icon-nb-close"></i>',
                                    btnClass: 'btn-red',
                                }
                            }
                        });
                        return false;
                    }
                    if(type_repeat === 'weekly') {
                        if(day_of_week.length === 0) {
                            $('body,html').animate({
                                scrollTop: $element.find('.day-off-week').offset().top
                            },500,"linear");
                            $.alert({
                                title:'',
                                content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your day of week</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                                container:'.block-alert',
                                buttons: {
                                    formSubmit: {
                                        text: '<i class="icon-nb-close"></i>',
                                        btnClass: 'btn-red',
                                    }
                                }
                            });
                            return false;
                        }
                        if(number_week_recurring==='' || number_week_recurring===0) {
                            $('body,html').animate({
                                scrollTop: $element.find('.block-number-week-recurring').offset().top
                            },500,"linear");
                            $.alert({
                                title:'',
                                content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your number of week</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                                container:'.block-alert',
                                buttons: {
                                    formSubmit: {
                                        text: '<i class="icon-nb-close"></i>',
                                        btnClass: 'btn-red',
                                    }
                                }
                            });
                            return false;
                        }

                    } else if (type_repeat === 'monthly') {
                        if(day_of_week.length === 0) {
                            $('body,html').animate({
                                scrollTop: $element.find('.day-off-week').offset().top
                            },500,"linear");
                            $.alert({
                                title:'',
                                content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your day of week</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                                container:'.block-alert',
                                buttons: {
                                    formSubmit: {
                                        text: '<i class="icon-nb-close"></i>',
                                        btnClass: 'btn-red',
                                    }
                                }
                            });
                            return false;
                        }
                        if(number_month_recurring==='' || number_month_recurring===0) {
                            $('body,html').animate({
                                scrollTop: $element.find('.block-number-month-recurring').offset().top
                            },500,"linear");
                            $.alert({
                                title:'',
                                content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your number of month</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                                container:'.block-alert',
                                buttons: {
                                    formSubmit: {
                                        text: '<i class="icon-nb-close"></i>',
                                        btnClass: 'btn-red',
                                    }
                                }
                            });
                            return false;
                        }
                        if(allday_or_specificday === 'specific-day') {
                            if(day_specific_in_month.length === 0) {
                                $('body,html').animate({
                                    scrollTop: $element.find('.block-specific-day-select').offset().top
                                },500,"linear");
                                $.alert({
                                    title:'',
                                    content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your specific day</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                                    container:'.block-alert',
                                    buttons: {
                                        formSubmit: {
                                            text: '<i class="icon-nb-close"></i>',
                                            btnClass: 'btn-red',
                                        }
                                    }
                                });
                                return false;
                            }
                        }
                    }
                }
                if (!$form.valid()) {
                    $('body,html').animate({
                        scrollTop: $element.find('.wrapper-block-check-out').offset().top
                    },500,"linear");
                    return false;
                }
                $form.submit();
            });
            $element.find('.btn-booknow').on('click',function () {
                let $block_event= $(this).closest('.block-event-item');
                $('body,html').animate({
                    scrollTop: $element.find('form.booking-form').offset().top
                },500,"linear");
                let event_id=$block_event.data('event_id');
                let event_choosen = list_event.find(function (event) {
                    if(event.id == event_id) {
                        return event;
                    }
                });
                $element.find('input[name="event_id"]').val(event_id);
                $element.find('.location-info').text(event_choosen.list_location[0].address)
                $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(event_choosen.price) * parseFloat(rate_exchange)).toFixed(2)));
                $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(event_choosen.price) * parseFloat(rate_exchange)).toFixed(2)));
            });

            $element.find('form[name="form-review"]').each(function (e) {
                $(this).validate({
                    ignore: ""
                });
            });
            $element.find('.btn-save-review').on('click', function () {
                let $form = $(this).closest('form[name="form-review"]');
                let rating_ambience = $form.find('input[name="rating_ambience"]').val();
                let rating_cleanliness = $form.find('input[name="rating_cleanliness"]').val();
                let rating_staff = $form.find('input[name="rating_staff"]').val();
                let rating_value = $form.find('input[name="rating_value"]').val();
                if(rating_ambience === '' || rating_cleanliness === '' || rating_staff === '' || rating_value === '') {
                    $.alert({
                        title:'',
                        content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please rating star</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                        container:'.block-alert',
                        buttons: {
                            formSubmit: {
                                text: '<i class="icon-nb-close"></i>',
                                btnClass: 'btn-red',
                            }
                        }
                    });
                    return false;
                }
                if (!$form.valid()) {
                    return false;
                }
                $form.submit();
            });


            let items_per_page = parseInt(limit);
            let total_result = parseInt(list_review.length);
            let total_page = Math.ceil(total_result / items_per_page);
            let visiblePages = (total_page < 2) ? (total_page % 2): 2;

            $element.find('.pagination-review').twbsPagination({
                totalPages:(total_page === 0)?1:total_page,
                visiblePages: visiblePages,
                hideOnlyOnePage:true,
                first: '<i class="fas fa-angle-double-left"></i>',
                prev: '<i class="fas fa-angle-left"></i>',
                next: '<i class="fas fa-angle-right"></i>',
                last: '<i class="fas fa-angle-double-right"></i>',
                onPageClick: function (event, page) {
                    let $form = $(this).closest('form[name="form-list-review-service"]');
                    $form.find('input[name="start"]').val(page -  1);
                    var output = plugin.convert_data_form($form);
                    let dataObj = {};
                    $(output).each(function(i, field){
                        dataObj[field.name] = field.value;
                    });
                    dataObj['total_result'] = list_review.length;
                    dataObj['service_id'] = service_item.id;
                    $.ajax({
                        url: wpbookingpro_root_url+wpbookingpro_api_task,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            dataObj: dataObj,
                            task: "reviews.get_list_review_ajax"
                        },
                        beforeSend: function() {
                            $('body').loadingModal();
                        },
                        success: function(res) {
                            res = JSON.parse(res);
                            let result = res.data;
                            $form.find('.wrapper-list-review').empty();
                            $form.find('.wrapper-list-review').append(result);
                        },
                        error: function(xhr) { // if error occured

                        },
                        complete: function() {
                            $('body').loadingModal('destroy');

                        },
                    })
                }
            });

            $element.find('input.input-coupon').on('change', function () {
                let $block_add_coupon = $(this).closest('.block-add-coupon');
                let val = $(this).val();
                if(val.trim() !== '') {
                    $block_add_coupon.find('.add-coupon').prop('disabled', false)
                } else {
                    $block_add_coupon.find('.add-coupon').prop('disabled', true)
                }

            });

            $element.find('.add-coupon').on('click', function () {
                let $wrapper_block_add_coupon = $(this).closest('.wrapper-block-add-coupon');
                let $block_add_coupon = $(this).closest('.block-add-coupon');
                let coupon_code = $block_add_coupon.find('input.input-coupon').val();
                $.ajax({
                    url: wpbookingpro_root_url+wpbookingpro_api_task,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        coupon_code: coupon_code,
                        service_id: service_item.id,
                        task: "coupon.check_coupon"
                    },
                    beforeSend: function() {
                        $('body').loadingModal();
                    },
                    success: function(res) {
                        res = JSON.parse(res);
                        let result = res.data;
                        if(result['is_ok']) {
                            $wrapper_block_add_coupon.find('.message-success').show();
                            $wrapper_block_add_coupon.find('.message-error').hide();
                            $block_add_coupon.find('input.input-coupon').prop('disabled', true);
                            $block_add_coupon.find('.add-coupon').prop('disabled', true);
                            let coupon = result['coupon'];
                            $block_add_coupon.find('input[name="coupon_id"]').val(coupon.id);
                            plugin.settings.coupon = result['coupon'];
                            if(coupon.amount > 0) {
                                $element.find('.discount').show();
                                $element.find('.discount-value').html(`- <span>'+ format_currency+'</span> ${plugin.formatNumber((parseFloat(coupon.amount) * parseFloat(rate_exchange)).toFixed(2))}`);
                                $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price  - coupon.amount) * parseFloat(rate_exchange) ).toFixed(2)));
                            } else if(coupon.percent > 0) {
                                $element.find('.discount').show()
                                $element.find('.discount-value').html(`- ${coupon.percent} %`);
                                $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * (1 - coupon.percent / 100) ) * parseFloat(rate_exchange)).toFixed(2)));
                            }
                            let date_start = $element.find('input.date-start-recurring').val();
                            let date_end = $element.find('input.date-end-recurring').val();
                            let type_recurring = $element.find('.block-type-of-recurring input[type="radio"]:checked').val();
                            let time_start = $element.find('input[name="time_start_recurring"]').val();
                            let list_employee = service_item.list_employee;
                            let array_start_time = list_employee.map(v=>moment(v.start_time,'HH:mm:ss'));
                            let array_end_time = list_employee.map(v=>moment(v.end_time,'HH:mm:ss'));
                            let array_price = list_employee.map(v=>parseFloat(v.price) * parseFloat(rate_exchange));
                            let employee_id = $element.find('input[name="employee_id"]').val();
                            let payment_schedule = $element.find('input[name="payment_schedule"]:checked').val();
                            let day_of_week = [];
                            $element.find('input[name="day_of_week[]"]:checked').each(function () {
                                day_of_week.push($(this).val())
                            });
                            plugin.caculatePrice(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, plugin.settings.coupon);

                        } else {
                            $wrapper_block_add_coupon.find('.message-success').hide();
                            $wrapper_block_add_coupon.find('.message-error').show();
                            $block_add_coupon.find('input.input-coupon').prop('disabled', false)
                        }
                    },
                    error: function(xhr) { // if error occured

                    },
                    complete: function() {
                        $('body').loadingModal('destroy');

                    },
                })

            })

        };

        plugin.debounce = function(func, wait) {
            var timeout;

            return function() {
                var context = this,
                    args = arguments;

                var executeFunction = function() {
                    func.apply(context, args);
                };

                clearTimeout(timeout);
                timeout = setTimeout(executeFunction, wait);
            };
        };
        plugin.convert_data_form = function($form) {
            var dataArray = $form.serializeArray();
            var output = [];
            dataArray.forEach(function(item) {
                var existing = output.filter(function(v, i) {
                    return v.name == item.name;
                });
                if (existing.length) {
                    var existingIndex = output.indexOf(existing[0]);
                    output[existingIndex].value = output[existingIndex].value.concat(item.value);
                } else {
                    if (typeof item.value == 'string')
                        item.value = [item.value];
                    output.push(item);
                }
            });
            return output;
        };

        plugin.caculatePrice = function(service_item, date_start, date_end, type_recurring, time_start,list_employee,array_start_time, array_end_time, array_price, employee_id, payment_schedule, day_of_week, deposit_percent, coupon) {
            let format_currency = plugin.settings.format_currency;
            let rate_exchange = plugin.settings.rate_exchange;
            if(type_recurring === 'daily') {
                let number_day_recurring = plugin.countDayRecurringDaily(date_start, date_end);
                $element.find('.sum-day-recurring').text(number_day_recurring);
                $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                if(!jQuery.isEmptyObject(coupon)) {
                    if(coupon.amount > 0) {
                        $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring) - coupon.amount) * parseFloat(rate_exchange)).toFixed(2)));
                        if(payment_schedule === 'pay-later') {
                            $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring - coupon.amount) * deposit_percent / 100) * parseFloat(rate_exchange)).toFixed(2)));
                            $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring - coupon.amount) * (1 - deposit_percent / 100)) * parseFloat(rate_exchange)).toFixed(2)));
                        }
                    } else if(coupon.percent > 0) {
                        $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * number_day_recurring * (1 - coupon.percent / 100)) * parseFloat(rate_exchange)).toFixed(2)));
                        if(payment_schedule === 'pay-later') {
                            $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring * (1 - coupon.percent / 100)) * deposit_percent / 100) * parseFloat(rate_exchange)).toFixed(2)));
                            $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring * (1 - coupon.percent / 100)) * (1 - deposit_percent / 100)) * parseFloat(rate_exchange)).toFixed(2)));
                        }
                    }
                } else {
                    $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * number_day_recurring) * parseFloat(rate_exchange)).toFixed(2)));
                    if(payment_schedule === 'pay-later') {
                        $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * number_day_recurring * deposit_percent / 100) * parseFloat(rate_exchange)).toFixed(2)));
                        $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * number_day_recurring * (1 - deposit_percent / 100)) * parseFloat(rate_exchange)).toFixed(2)));
                    }
                }


            } else if( type_recurring === 'weekly' || type_recurring === 'monthly') {
                if(day_of_week.length > 0) {
                    let number_day_recurring = plugin.countDayRecurringWeeklyAndMonthly(date_start,date_end,day_of_week);
                    let allday_or_specificday = $element.find('.block-select-allday input[type="radio"]:checked').val();
                    let day_recurring_in_month = [];
                    $element.find('input[name="day_recurring_in_month[]"]:checked').each(function (index, item) {
                        day_recurring_in_month.push($(this).val())
                    });
                    if(type_recurring === 'monthly') {
                        if(allday_or_specificday === 'specific-day') {
                            number_day_recurring = day_recurring_in_month.length;
                        }
                    }

                    $element.find('.sum-day-recurring').text(number_day_recurring);
                    $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                    if(!jQuery.isEmptyObject(coupon)) {
                        if(coupon.amount > 0) {
                            $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring) - coupon.amount) * parseFloat(rate_exchange)).toFixed(2)));
                            if(payment_schedule === 'pay-later') {
                                $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring - coupon.amount) * deposit_percent / 100) * parseFloat(rate_exchange)).toFixed(2)));
                                $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring - coupon.amount) * (1 - deposit_percent / 100)) * parseFloat(rate_exchange)).toFixed(2)));
                            }
                        } else if(coupon.percent > 0) {
                            $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * number_day_recurring * (1 - coupon.percent / 100)) * parseFloat(rate_exchange)).toFixed(2)));
                            if(payment_schedule === 'pay-later') {
                                $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring * (1 - coupon.percent / 100)) * deposit_percent / 100) * parseFloat(rate_exchange)).toFixed(2)));
                                $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat((service_item.price * number_day_recurring * (1 - coupon.percent / 100)) * (1 - deposit_percent / 100)) * parseFloat(rate_exchange)).toFixed(2)));
                            }
                        }
                    } else {
                        $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * number_day_recurring) * parseFloat(rate_exchange)).toFixed(2)));
                        if(payment_schedule === 'pay-later') {
                            $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * number_day_recurring * deposit_percent / 100) * parseFloat(rate_exchange)).toFixed(2)));
                            $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price * number_day_recurring * (1 - deposit_percent / 100)) * parseFloat(rate_exchange)).toFixed(2)));
                        }
                    }
                } else {
                    $element.find('.sum-day-recurring').text(0);
                    $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                    $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(service_item.price * 0).toFixed(2)));
                    if(payment_schedule === 'pay-later') {
                        $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(service_item.price * 0).toFixed(2)));
                        $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(service_item.price * 0).toFixed(2)));
                    }
                }

            }

            for(let i=0; i< list_employee.length;i++) {
                if(list_employee[i].id === employee_id && moment(time_start,'HH:mm:ss').valueOf() >= array_start_time[i].valueOf() && moment(time_start,'HH:mm:ss').valueOf() <= array_end_time[i].valueOf()) {
                    if(type_recurring === 'daily') {
                        let number_day_recurring = plugin.countDayRecurringDaily(date_start, date_end);
                        $element.find('.sum-day-recurring').text(number_day_recurring);
                        $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i]).toFixed(2)));
                        if(!jQuery.isEmptyObject(coupon)) {
                            if(coupon.amount > 0) {
                                $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring - coupon.amount).toFixed(2)));
                                if(payment_schedule === 'pay-later') {
                                    $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat((array_price[i] * number_day_recurring -coupon.amount) * deposit_percent / 100).toFixed(2)));
                                    $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat((array_price[i] * number_day_recurring - coupon.amount) * (1 - deposit_percent / 100)).toFixed(2)));
                                }
                            } else if(coupon.percent > 0) {
                                $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring * (1 - coupon.percent / 100)).toFixed(2)));
                                if(payment_schedule === 'pay-later') {
                                    $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat((array_price[i] * number_day_recurring * (1 - coupon.percent / 100)) * deposit_percent / 100).toFixed(2)));
                                    $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat((array_price[i] * number_day_recurring * (1 - coupon.percent / 100)) * (1 - deposit_percent / 100)).toFixed(2)));
                                }
                            }
                        } else {
                            $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring).toFixed(2)));
                            if(payment_schedule === 'pay-later') {
                                $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring * deposit_percent / 100).toFixed(2)));
                                $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring * (1 - deposit_percent / 100)).toFixed(2)));
                            }
                        }
                    } else if( type_recurring === 'weekly' || type_recurring === 'monthly') {
                        if(day_of_week.length > 0) {
                            let number_day_recurring = plugin.countDayRecurringWeeklyAndMonthly(date_start,date_end,day_of_week);
                            let allday_or_specificday = $element.find('.block-select-allday input[type="radio"]:checked').val();
                            let day_recurring_in_month = [];
                            $element.find('input[name="day_recurring_in_month[]"]:checked').each(function (index, item) {
                                day_recurring_in_month.push($(this).val())
                            });
                            if(type_recurring === 'monthly') {
                                if(allday_or_specificday === 'specific-day') {
                                    number_day_recurring = day_recurring_in_month.length;
                                }
                            }
                            $element.find('.sum-day-recurring').text(number_day_recurring);
                            $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i]).toFixed(2)));
                            if(!jQuery.isEmptyObject(coupon)) {
                                if(coupon.amount > 0) {
                                    $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring - coupon.amount).toFixed(2)));
                                    if(payment_schedule === 'pay-later') {
                                        $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat((array_price[i] * number_day_recurring -coupon.amount) * deposit_percent / 100).toFixed(2)));
                                        $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat((array_price[i] * number_day_recurring - coupon.amount) * (1 - deposit_percent / 100)).toFixed(2)));
                                    }
                                } else if(coupon.percent > 0) {
                                    $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring * (1 - coupon.percent / 100)).toFixed(2)));
                                    if(payment_schedule === 'pay-later') {
                                        $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat((array_price[i] * number_day_recurring * (1 - coupon.percent / 100)) * deposit_percent / 100).toFixed(2)));
                                        $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat((array_price[i] * number_day_recurring * (1 - coupon.percent / 100)) * (1 - deposit_percent / 100)).toFixed(2)));
                                    }
                                }
                            } else {
                                $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring).toFixed(2)));
                                if(payment_schedule === 'pay-later') {
                                    $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring * deposit_percent / 100).toFixed(2)));
                                    $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * number_day_recurring * (1 - deposit_percent / 100)).toFixed(2)));
                                }
                            }
                        } else {
                            $element.find('.sum-day-recurring').text(0);
                            $element.find('.base-price').html('<span>'+ format_currency+'</span>' + plugin.formatNumber((parseFloat(service_item.price) * parseFloat(rate_exchange)).toFixed(2)));
                            $element.find('.total-cost-sum').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(service_item.price * 0).toFixed(2)));
                            if(payment_schedule === 'pay-later') {
                                $element.find('.deposit').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * 0).toFixed(2)));
                                $element.find('.balance').html('<span>'+ format_currency+'</span>' + plugin.formatNumber(parseFloat(array_price[i] * 0).toFixed(2)));
                            }
                        }

                    }
                }

            }
        }
        plugin.countDayRecurringDaily = function (startDate, endDate) {
            return moment(endDate).diff(moment(startDate), "days") + 1;
        };

        plugin.getDayAnDateBetweenToDate = function (date_start, date_end) {
            let arr_month = [];
            let arr_year = [];
            for (var d = new Date(date_start.split('-')[0], date_start.split('-')[1] - 1, date_start.split('-')[2]); d <= new Date(date_end.split('-')[0], date_end.split('-')[1] - 1, date_end.split('-')[2]); d.setMonth(d.getMonth() + 1)) {
                if(d.getMonth() + 1 >= date_start.split('-')['1'] && d.getMonth() + 1 <= date_end.split('-')['1']) {
                    arr_month.push(d.getMonth());
                    arr_year.push(d.getFullYear());
                }
            }
            var weekday=new Array(7);
            weekday[0]="Sunday";
            weekday[1]="Monday";
            weekday[2]="Tuesday";
            weekday[3]="Wednesday";
            weekday[4]="Thursday";
            weekday[5]="Friday";
            weekday[6]="Saturday";
            let arrayDay = [];
            let array_day_in =[];
            let array_date_in = [];
            for(let i = 0; i< arr_month.length; i++) {
                let arr_date1 = plugin.getDaysInMonth(arr_month[i],arr_year[i]);
                let day_in_arr_date1 = arr_date1.map(value => weekday[value.getDay()]);
                let date_in_arr_date1 = arr_date1.map(value => moment(value).format('YYYY-MM-DD'));
                for(let j = 0; j< date_in_arr_date1.length; j++) {
                    if(moment(date_start).valueOf() <= moment(date_in_arr_date1[j]).valueOf() && moment(date_end).valueOf() >= moment(date_in_arr_date1[j]).valueOf()) {
                        array_date_in.push(date_in_arr_date1[j]);
                        array_day_in.push(day_in_arr_date1[j])
                    }
                }
            }
            arrayDay.push(array_day_in);
            arrayDay.push(array_date_in);
            return arrayDay;
        };

        plugin.getDaysInMonth = function (month, year) {
            var date = new Date(year, month, 1);
            var days = [];
            while (date.getMonth() === month) {
                days.push(new Date(date));
                date.setDate(date.getDate() + 1);
            }
            return days;
        };
        plugin.countDayRecurringWeeklyAndMonthly = function (startDate, endDate, arrDayOfWeeek) {
            var number_day_recurring = 0;
            var arrStartDate = startDate.split('-');
            var arrEndDate = endDate.split('-');
            var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
            for (var d = new Date(arrStartDate[0], arrStartDate[1] - 1, arrStartDate[2]); d <= new Date(arrEndDate[0], arrEndDate[1] - 1, arrEndDate[2]); d.setDate(d.getDate() + 1)) {
                var day = days[ d.getDay() ];
                for(let i = 0; i < arrDayOfWeeek.length; i++) {
                    if(day.toLocaleLowerCase() === arrDayOfWeeek[i]) {
                        number_day_recurring++;
                    }
                }
            }
            return number_day_recurring;
        }
        plugin.formatNumber = function (num) {
            return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        };
        plugin.arr_diff = function (a1, a2) {
            let a = [], diff = [];
            if(a1.length > 0 && a2.length > 0) {
                for (let i = 0; i < a1.length; i++) {
                    a[a1[i]] = true;
                }
                for (let i = 0; i < a2.length; i++) {
                    if (a[a2[i]]) {
                        delete a[a2[i]];
                    } else {
                        a[a2[i]] = true;
                    }
                }
                for (let k in a) {
                    diff.push(k);
                }
            }
            return diff;
        };
        plugin.example_function = function () {
        };
        setTimeout(function(){
            plugin.init();
        },1);
        
    }
    $.fn.view_service_detail = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_service_detail')) {
                let plugin = new $.view_service_detail(this, options);
                $(this).data('view_service_detail', plugin);
            }
        });
    }
})(jQuery);
