"use strict";
(function ($) {
    $.view_list_calendar = function (element, options) {
        let defaults = {
            list_order: [],
            list_service:[],
            is_demo: false,
            url_image_demo:''
        };
        let plugin = this;
        plugin.settings = {};
        let $element = $(element);
        plugin.up_event = function (id, start, end) {
            let data = {
                id: id,
                from: start,
                to: end,
                task: "orderdetailrate.save_change_time_order"
            };
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: data,
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);
                    if (response.result === "success") {
                        $.alert({
                            title: 'Success',
                            content: 'update day success !',
                        });
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        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.setCustomServiceChoosen = function(service_choosen, info) {

            $element.find('input.time-start-recurring').on('dp.change', function (e) {
                $element.find(`input[name="time_end_recurring"]`).val(moment(e.date).add(service_choosen.duration,'h').format('HH:mm:ss')).trigger('change');
                $element.find('input.time-end-recurring').val(moment(e.date).add(service_choosen.duration,'h').format('HH:mm'));
            });
            let list_working_day= service_choosen.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_choosen.open_time !== 'undefined') {
                open_time_hour = parseInt(service_choosen.open_time.split(':')['0']);
                open_time_minute = parseInt(service_choosen.open_time.split(':')['1']);
            }
            let close_time_hour = 0;
            let close_time_minute = 0;
            if (typeof service_choosen.close_time !== 'undefined') {
                close_time_hour = parseInt(service_choosen.close_time.split(':')['0']);
                close_time_minute = parseInt(service_choosen.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_choosen.duration)%10,m:close_time_minute - (service_choosen.duration - (service_choosen.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})]]
            );
            let is_recurring = info.event._def.extendedProps.is_recurring;
            let type_recurring = info.event._def.extendedProps.type_recurring;
            let number_week_recurring = info.event._def.extendedProps.number_week_recurring;
            let number_month_recurring = info.event._def.extendedProps.number_month_recurring;
            let date_start_recurring = info.event._def.extendedProps.date_start_recurring;
            let date_end_recurring = info.event._def.extendedProps.date_end_recurring;
            let time_start_recurring = info.event._def.extendedProps.time_start_recurring;
            let time_end_recurring = info.event._def.extendedProps.time_end_recurring;
            let start_date = info.event._def.extendedProps.start_date;
            let order_day_recurring = info.event._def.extendedProps.order_day_recurring;
            let all_or_specific = info.event._def.extendedProps.all_or_specific;
            let specific_day = info.event._def.extendedProps.specific_day;
            $element.find('.day-off-week input[type="checkbox"]').each(function (index, item) {
                let val = $(item).val();
                if(order_day_recurring.indexOf(val) !== -1) {
                    $(item).prop('checked', true);
                } else {
                    $(item).prop('checked', false);
                }
            });
            $element.find('.day-off-week input[type="checkbox"]').each(function (index, item) {
                let val = $(item).val();
                if(order_day_recurring.indexOf(val) !== -1) {
                    $(item).prop('checked', true);
                } else {
                    $(item).prop('checked', false);
                }
            });
            $element.find('.is-recurring-item input[type="radio"]').each(function (index,  item) {
                let val = $(item).val();
                if(val === is_recurring) {
                    $(item).prop('checked', true);
                    $element.find(".form_datetime").hide();
                    $element.find('.block-add-recurring').slideDown();
                } else {
                    $element.find(".form_datetime").show();
                    $element.find('.block-add-recurring').slideUp();
                    $element.find("#datetimepicker1").val(moment(start_date,'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm'));
                    $element.find('input[name="calendar"]').val(moment(start_date).format('YYYY-MM-DD HH:mm:ss'));
                    $element.find(`input[name="date_start_recurring"]`).val('');
                    $element.find(`input[name="date_end_recurring"]`).val('');
                    $element.find(`input[name="time_start_recurring"]`).val('');
                    $element.find(`input[name="time_end_recurring"]`).val('');
                }
            });
            $element.find('.block-type-of-recurring input[type="radio"]').each(function (index, item) {
                let val  = $(item).val();
                let $block_add_recurring = $(item).closest('.block-add-recurring');
                let $day_off_week = $block_add_recurring.find('.day-off-week');
                let $block_number_week_recurring = $block_add_recurring.find('.block-number-week-recurring');
                let $block_number_month_recurring = $block_add_recurring.find('.block-number-month-recurring');
                if(val === type_recurring && type_recurring === 'daily') {
                    $(item).prop('checked', true);
                    $day_off_week.slideUp();
                    $block_number_week_recurring.slideUp();
                    $block_number_month_recurring.slideUp();
                    $block_number_month_recurring.find('input[type="text"]').val('');
                    $block_number_week_recurring.find('input[type="text"]').val('');
                    $element.find('input.date-end-recurring').prop('disabled', false);
                    $element.find('input.date-start-recurring').val(moment(date_start_recurring).format('YYYY-MM-DD'));
                    $element.find(`input[name="date_start_recurring"]`).val(moment(date_start_recurring).format('YYYY-MM-DD'));
                    $element.find('input.date-end-recurring').val(moment(date_end_recurring).format('YYYY-MM-DD'));
                    $element.find(`input[name="date_end_recurring"]`).val(moment(date_end_recurring).format('YYYY-MM-DD'));
                    $element.find('input.time-start-recurring').val(moment(time_start_recurring,'HH:mm:ss').format('HH:mm'));
                    $element.find('input[name="time_start_recurring"]').val(time_start_recurring);
                    $element.find('input.time-end-recurring').val(moment(time_end_recurring,'HH:mm:ss').format('HH:mm'));
                    $element.find('input[name="time_end_recurring"]').val(time_end_recurring);
                    $element.find('input[name="calendar"]').val('');
                }else if(val === type_recurring && type_recurring === 'weekly') {
                    $(item).prop('checked', true);
                    $day_off_week.slideDown();
                    $block_number_week_recurring.slideDown();
                    $block_number_month_recurring.slideUp();
                    $block_number_month_recurring.find('input[type="text"]').val('');
                    $block_number_week_recurring.find('input[type="text"]').val(number_week_recurring);
                    $element.find('input.date-end-recurring').prop('disabled', true);
                    $element.find('input.date-start-recurring').val(moment(date_start_recurring).format('YYYY-MM-DD'));
                    $element.find(`input[name="date_start_recurring"]`).val(moment(date_start_recurring).format('YYYY-MM-DD'));
                    $element.find('input.date-end-recurring').val(moment(date_end_recurring).format('YYYY-MM-DD'));
                    $element.find(`input[name="date_end_recurring"]`).val(moment(date_end_recurring).format('YYYY-MM-DD'));
                    $element.find('input.time-start-recurring').val(moment(time_start_recurring,'HH:mm:ss').format('HH:mm'));
                    $element.find('input[name="time_start_recurring"]').val(time_start_recurring);
                    $element.find('input.time-end-recurring').val(moment(time_end_recurring,'HH:mm:ss').format('HH:mm'));
                    $element.find('input[name="time_end_recurring"]').val(time_end_recurring);
                    $element.find('input[name="calendar"]').val('');
                } else if(val === type_recurring && type_recurring === 'monthly') {
                    $(item).prop('checked', true);
                    $day_off_week.slideDown();
                    $block_number_week_recurring.slideUp();
                    $block_number_month_recurring.slideDown();
                    $block_number_week_recurring.find('input[type="text"]').val('');
                    $block_number_month_recurring.find('input[type="text"]').val(number_month_recurring);
                    $element.find('input.date-end-recurring').prop('disabled', true);
                    $element.find('input.date-start-recurring').val(moment(date_start_recurring).format('YYYY-MM-DD'));
                    $element.find(`input[name="date_start_recurring"]`).val(moment(date_start_recurring).format('YYYY-MM-DD'));
                    $element.find('input.date-end-recurring').val(moment(date_end_recurring).format('YYYY-MM-DD'));
                    $element.find(`input[name="date_end_recurring"]`).val(moment(date_end_recurring).format('YYYY-MM-DD'));
                    $element.find('input.time-start-recurring').val(moment(time_start_recurring,'HH:mm:ss').format('HH:mm'));
                    $element.find('input[name="time_start_recurring"]').val(time_start_recurring);
                    $element.find('input.time-end-recurring').val(moment(time_end_recurring,'HH:mm:ss').format('HH:mm'));
                    $element.find('input[name="time_end_recurring"]').val(time_end_recurring);
                    $element.find('input[name="calendar"]').val('');
                    $element.find('input[name="allday_or_specificday"]').each(function (index, item) {
                        let val= $(item).val();
                        if(val === all_or_specific) {
                            $(item).prop('checked', true);
                        }
                    });
                    $element.find('.block-select-allday').show();
                    if(all_or_specific === 'specific-day') {
                        $element.find('.block-specific-day-select').show();
                        let arrDayInMonth = plugin.getDayAnDateBetweenToDate(date_start_recurring, date_end_recurring);
                        let block_input = $element.find('.block-specific-day-select').children('.block-input');
                        $(block_input).empty()
                        for(let i = 0; i< order_day_recurring.length; i++) {
                            let block_day = $(`<div class="wrapper-day-specific">
                                            <h6 class="title-specific-day">${order_day_recurring[i]}</h6>
                                        </div>`);
                            let block_date = $('<div class="wrapper-date-specific"></div>');
                            for(let j= 0; j < arrDayInMonth['0'].length; j++) {
                                if(order_day_recurring[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[]"]').each( function (index, item) {
                                let val = $(item).val();
                                if(specific_day.indexOf(val) !== -1) {
                                    $(item).prop('checked', true);
                                } else {
                                    $(item).prop('checked', false);
                                }
                            });
                            $(block_day).append(block_date);
                            $(block_input).append(block_day);
                        }
                    }
                }
            });
        };
        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.get_full_time = function (date) {
            let current_datetime = new Date(date);
            let formatted_date = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " " + current_datetime.getHours() + ":" + current_datetime.getMinutes() + ":" + current_datetime.getSeconds();
            return formatted_date;
        };
        plugin.create_Appointment = function (info) {
            let start = plugin.get_full_time(info.startStr);
            let end = plugin.get_full_time(info.endStr);
            let data = {
                from: start,
                to: end,
                task: "appointment.ajax_get_item"
            };
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: data,
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);
                    if (response.result === "success") {
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.filter_order_by_employee = function (employee_id) {
            let data = {
                id: employee_id,
                task: "calendar.get_order_by_employee_id"
            };
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: data,
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);
                    if (response.result === "success") {
                        let list_service = plugin.settings.list_service;
                        let list_order = response.data;
                        let list_rate = [];
                        let event_render = [];
                        $.each(list_order,function (index, item) {
                            list_rate.push(item.list_rate);
                            if(item.list_rate.type_recurring === 'monthly' && item.list_rate.all_or_specific === 'specific-day') {
                                let rrule = item.list_rate.rrule1 + '\n'+ item.list_rate.rrule2 + '\n'+ item.list_rate.rrule3;
                                event_render.push({
                                    title: item.list_rate.title,
                                    start: item.list_rate.start,
                                    end: item.list_rate.end,
                                    duration: item.list_rate.duration,
                                    list_date_detail: item.list_rate.list_date_detail,
                                    list_time_detail: item.list_rate.list_time_detail,
                                    employee_fullname: item.list_rate.employee_fullname,
                                    editable: item.list_rate.editable,
                                    customer_email: item.list_rate.customer_email,
                                    is_recurring: item.list_rate.is_recurring,
                                    type_recurring: item.list_rate.type_recurring,
                                    order_id: item.list_rate.order_id,
                                    number_month_recurring: item.list_rate.number_month_recurring,
                                    number_week_recurring: item.list_rate.number_week_recurring,
                                    order_day_recurring: item.list_rate.order_day_recurring,
                                    location_address: item.list_rate.location_address,
                                    service_price: item.list_rate.service_price,
                                    service_id: item.list_rate.service_id,
                                    service_image: item.list_rate.service_image,
                                    description: item.list_rate.description,
                                    service_color: item.list_rate.service_color,
                                    employee_cover: item.list_rate.employee_cover,
                                    date_start_recurring: item.list_rate.date_start_recurring,
                                    date_end_recurring: item.list_rate.date_end_recurring,
                                    start_date: item.list_rate.start_date,
                                    time_start_recurring: item.list_rate.time_start_recurring,
                                    time_end_recurring: item.list_rate.time_end_recurring,
                                    employee_id: item.list_rate.employee_id,
                                    order_detail_id: item.list_rate.order_detail_id,
                                    balance_payment: item.list_rate.balance_payment,
                                    specific_day: item.list_rate.specific_day,
                                    all_or_specific: item.list_rate.all_or_specific,
                                    rrule: rrule,
                                })
                            } else {
                                event_render.push({
                                    title: item.list_rate.title,
                                    start: item.list_rate.start,
                                    end: item.list_rate.end,
                                    duration: item.list_rate.duration,
                                    list_date_detail: item.list_rate.list_date_detail,
                                    list_time_detail: item.list_rate.list_time_detail,
                                    employee_fullname: item.list_rate.employee_fullname,
                                    editable: item.list_rate.editable,
                                    customer_email: item.list_rate.customer_email,
                                    is_recurring: item.list_rate.is_recurring,
                                    type_recurring: item.list_rate.type_recurring,
                                    order_id: item.list_rate.order_id,
                                    number_month_recurring: item.list_rate.number_month_recurring,
                                    number_week_recurring: item.list_rate.number_week_recurring,
                                    order_day_recurring: item.list_rate.order_day_recurring,
                                    rrule: item.list_rate.rrule,
                                    location_address: item.list_rate.location_address,
                                    service_id: item.list_rate.service_id,
                                    service_price: item.list_rate.service_price,
                                    service_image: item.list_rate.service_image,
                                    description: item.list_rate.description,
                                    service_color: item.list_rate.service_color,
                                    employee_cover: item.list_rate.employee_cover,
                                    date_start_recurring: item.list_rate.date_start_recurring,
                                    date_end_recurring: item.list_rate.date_end_recurring,
                                    start_date: item.list_rate.start_date,
                                    time_start_recurring: item.list_rate.time_start_recurring,
                                    time_end_recurring: item.list_rate.time_end_recurring,
                                    employee_id: item.list_rate.employee_id,
                                    order_detail_id: item.list_rate.order_detail_id,
                                    balance_payment: item.list_rate.balance_payment,
                                    specific_day: item.list_rate.specific_day,
                                    all_or_specific: item.list_rate.all_or_specific,
                                })
                            }
                        });
                        var calendarEl = document.getElementById('calendar');
                        var calendar = new FullCalendar.Calendar(calendarEl, {
                            plugins: ['interaction', 'dayGrid', 'timeGrid', 'bootstrap', 'interaction', 'moment', 'rrule'],
                            selectable: true,
                            header: {
                                left: 'prev,next today',
                                center: 'title',
                                right: 'dayGridMonth,timeGridWeek,timeGridDay'
                            },
                            select: function (info) {
                                //plugin.create_Appointment(info);
                            },
                            droppable: true,
                            themeSystem: 'bootstrap',
                            events:event_render,
                            color: 'yellow',
                            textColor: 'black',
                            editable: true,
                            eventLimit: true, // for all non-TimeGrid views
                            views: {
                                dayGrid: {
                                    eventLimit: 2 // adjust to 6 only for timeGridWeek/timeGridDay
                                }
                            },
                            eventDrop: function (info, delta, revertFunc) {
                                let id = info.event.id;
                                let start = plugin.get_full_time(info.event.start);
                                let end = plugin.get_full_time(info.event.end);
                                if(info.event._def.extendedProps.is_recurring === '0') {
                                    plugin.up_event(id, start, end);
                                }

                            },
                            eventResize: function (info) {
                                let id = info.event.id;
                                let start = plugin.get_full_time(info.event.start);
                                let end = plugin.get_full_time(info.event.end);
                                if(info.event._def.extendedProps.is_recurring === '0') {
                                    plugin.up_event(id, start, end);
                                }

                            },
                            eventClick: function (info, element) {
                                let service_id = info.event._def.extendedProps.service_id;
                                let employee_id = info.event._def.extendedProps.employee_id;
                                let order_id = info.event._def.extendedProps.order_id;
                                let order_detail_id = info.event._def.extendedProps.order_detail_id;
                                let service_choosen = list_service.find(function (service) {
                                    if(service.id === service_id) {
                                        return  service;
                                    }
                                });
                                plugin.setCustomServiceChoosen(service_choosen, info);

                                $element.find('input[name="service_id"]').val(service_id);
                                $element.find('input[name="employee_id"]').val(employee_id);
                                $element.find('input[name="order_id"]').val(order_id);
                                $element.find('input[name="order_detail_id"]').val(order_detail_id);
                                $element.find('#calendarModal').modal('toggle');
                            },
                            eventRender: function (info) {
                                $(info.el).css('background-color', info.event._def.extendedProps.service_color);
                                $(info.el).find('.fc-title').append('<i class="icon-nb-calendar"></i>');
                                let employee_image_src = wpbookingpro_root_url_plugin + info.event._def.extendedProps.employee_cover;
                                if(plugin.settings.is_demo) {
                                    let checkImageSize = false;
                                    plugin.getBase64FromImageUrl(plugin.settings.url_image_demo + info.event._def.extendedProps.employee_cover,  function (blobImage) {
                                        if(blobImage.size > 0) {
                                            checkImageSize = true;
                                        }
                                    });
                                    if(checkImageSize) {
                                        employee_image_src = plugin.settings.url_image_demo + info.event._def.extendedProps.employee_cover;
                                    } else {
                                        employee_image_src = wpbookingpro_root_url_plugin + info.event._def.extendedProps.employee_cover;
                                    }
                                }
                                $(info.el).find(".fc-content").append(`
                                    <p class="time-booking">${info.event._def.extendedProps.list_time_detail}</p>
                                    <div class="employee">
                                            <div class="img-box">
                                                <div>
                                                    <img src="${employee_image_src}" alt="">
                                                </div>
                                            </div>
                                            <span>${info.event._def.extendedProps.employee_fullname}</span>
                                    </div>
                                `
                                );
                                if(info.event._def.extendedProps.is_recurring === '1') {
                                    if(info.event._def.extendedProps.type_recurring === 'daily') {
                                        $(info.el).find(".fc-content").append('<span class="is-recurring" style="background-color: #a0e4a0">Daily</span>');
                                    } else if(info.event._def.extendedProps.type_recurring === 'weekly') {
                                        $(info.el).find(".fc-content").append('<span class="is-recurring" style="background-color: #fdd07e">Weekly</span>');
                                    } else if(info.event._def.extendedProps.type_recurring === 'monthly') {
                                        $(info.el).find(".fc-content").append('<span class="is-recurring" style="background-color: #e89de8">Monthly</span>');
                                    }
                                }
                                $(info.el).popover({
                                    html: true,
                                    content: function () {
                                        let $html = `
                                            <p class="time-booking"><i class="icon-nb-clock"></i> <span>${info.event._def.extendedProps.list_time_detail}</span></p>
                                            <p class="location-booking"><i class="icon-nb-pin"></i> <span>${info.event._def.extendedProps.location_address}</span></p>
                                            <p class="customer-booking"><i class="icon-nb-email"></i> <span>${info.event._def.extendedProps.customer_email}</span> </p>
                                            <div class="employee-booking">
                                                <div class="img-box">
                                                    <div>
                                                        <img src="${employee_image_src}" alt="">
                                                    </div>
                                                </div>
                                                <span>${info.event._def.extendedProps.employee_fullname}</span>
                                            </div>
                                           
                                        `;
                                        return $html;
                                    },
                                    title: function () {
                                        let $title = `
                                            <span>${info.event.title}</span>
                                            <div class="color" style="background-color: ${info.event._def.extendedProps.service_color}"></div>
                                        `;
                                        return $title;
                                    },
                                    delay: {"show": 500, "hide": 100},
                                    placement: "top",
                                    trigger: 'manual'
                                }).on('mouseenter', function () {
                                    var _this = this;
                                    $(this).popover('show');
                                    $('.popover').on('mouseleave', function () {
                                        $(_this).popover('hide');
                                    });
                                }).on('mouseleave', function () {
                                    var _this = this;
                                    setTimeout(function () {
                                        if (!$('.popover:hover').length) {
                                            $(_this).popover('hide');
                                        }
                                    }, 300);
                                });
                            },
                        });
                        calendar.render();
                    } else {
                        $.alert({
                            title: 'Error',
                            content: response.msg
                        });
                    }
                }
            });
        };
        plugin.validateFormBeforeSubmit = function ($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 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();
            let is_ok = true;
            if(is_repeat === '0') {
                if (time_value === "") {
                    $.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',
                            }
                        }
                    });
                    is_ok = false;
                }
            } else {
                if(date_start_recurring === '' || time_start_recurring === '' || date_end_recurring === '' || time_end_recurring === '') {
                    $.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',
                            }
                        }
                    });
                    is_ok = false;
                }
                if(type_repeat === 'weekly') {
                    if(day_of_week.length === 0) {
                        $.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',
                                }
                            }
                        });
                        is_ok = 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',
                                }
                            }
                        });
                        is_ok = false;
                    }

                } else if (type_repeat === 'monthly') {
                    if(day_of_week.length === 0) {
                        $.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',
                                }
                            }
                        });
                        is_ok = false;
                    }
                    if(number_month_recurring==='' || number_month_recurring===0) {
                        $.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',
                                }
                            }
                        });
                        is_ok = false;
                    }
                    if(allday_or_specificday === 'specific-day') {
                        if(day_specific_in_month.length === 0) {
                            $.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',
                                    }
                                }
                            });
                            is_ok = false;
                        }
                    }
                }
            }
            if (!$form.valid()) {
                is_ok =  false;
            }
            return is_ok;
        };
        plugin.getBase64FromImageUrl = function(url, callback) {
            var img = new Image();
            img.setAttribute('crossOrigin', 'anonymous');
            img.onload = function (a) {
                var canvas = document.createElement("canvas");
                canvas.width = this.width;
                canvas.height = this.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(this, 0, 0);

                var dataURI = canvas.toDataURL("image/jpg");

                // convert base64/URLEncoded data component to raw binary data held in a string
                var byteString;
                if (dataURI.split(',')[0].indexOf('base64') >= 0)
                    byteString = atob(dataURI.split(',')[1]);
                else
                    byteString = unescape(dataURI.split(',')[1]);

                // separate out the mime component
                var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

                // write the bytes of the string to a typed array
                var ia = new Uint8Array(byteString.length);
                for (var i = 0; i < byteString.length; i++) {
                    ia[i] = byteString.charCodeAt(i);
                }

                return callback(new Blob([ia], { type: mimeString }));
            }

            img.src = url;
        }
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            var calendarEl = document.getElementById('calendar');
            let list_order = plugin.settings.list_order;
            let list_service = plugin.settings.list_service;
            let list_rate = [];
            let event_render = [];
            $.each(list_order,function (index, item) {
                list_rate.push(item.list_rate);
                if(item.list_rate.type_recurring === 'monthly' && item.list_rate.all_or_specific === 'specific-day') {
                    let rrule = item.list_rate.rrule1 + '\n'+ item.list_rate.rrule2 + '\n'+ item.list_rate.rrule3;
                    event_render.push({
                        title: item.list_rate.title,
                        start: item.list_rate.start,
                        end: item.list_rate.end,
                        duration: item.list_rate.duration,
                        list_date_detail: item.list_rate.list_date_detail,
                        list_time_detail: item.list_rate.list_time_detail,
                        employee_fullname: item.list_rate.employee_fullname,
                        editable: item.list_rate.editable,
                        customer_email: item.list_rate.customer_email,
                        is_recurring: item.list_rate.is_recurring,
                        type_recurring: item.list_rate.type_recurring,
                        order_id: item.list_rate.order_id,
                        number_month_recurring: item.list_rate.number_month_recurring,
                        number_week_recurring: item.list_rate.number_week_recurring,
                        order_day_recurring: item.list_rate.order_day_recurring,
                        location_address: item.list_rate.location_address,
                        service_price: item.list_rate.service_price,
                        service_id: item.list_rate.service_id,
                        service_image: item.list_rate.service_image,
                        description: item.list_rate.description,
                        service_color: item.list_rate.service_color,
                        employee_cover: item.list_rate.employee_cover,
                        date_start_recurring: item.list_rate.date_start_recurring,
                        date_end_recurring: item.list_rate.date_end_recurring,
                        start_date: item.list_rate.start_date,
                        time_start_recurring: item.list_rate.time_start_recurring,
                        time_end_recurring: item.list_rate.time_end_recurring,
                        employee_id: item.list_rate.employee_id,
                        order_detail_id: item.list_rate.order_detail_id,
                        balance_payment: item.list_rate.balance_payment,
                        specific_day: item.list_rate.specific_day,
                        all_or_specific: item.list_rate.all_or_specific,
                        rrule: rrule,
                    })
                } else {
                    event_render.push({
                        title: item.list_rate.title,
                        start: item.list_rate.start,
                        end: item.list_rate.end,
                        duration: item.list_rate.duration,
                        list_date_detail: item.list_rate.list_date_detail,
                        list_time_detail: item.list_rate.list_time_detail,
                        employee_fullname: item.list_rate.employee_fullname,
                        editable: item.list_rate.editable,
                        customer_email: item.list_rate.customer_email,
                        is_recurring: item.list_rate.is_recurring,
                        type_recurring: item.list_rate.type_recurring,
                        order_id: item.list_rate.order_id,
                        number_month_recurring: item.list_rate.number_month_recurring,
                        number_week_recurring: item.list_rate.number_week_recurring,
                        order_day_recurring: item.list_rate.order_day_recurring,
                        rrule: item.list_rate.rrule,
                        location_address: item.list_rate.location_address,
                        service_id: item.list_rate.service_id,
                        service_price: item.list_rate.service_price,
                        service_image: item.list_rate.service_image,
                        description: item.list_rate.description,
                        service_color: item.list_rate.service_color,
                        employee_cover: item.list_rate.employee_cover,
                        date_start_recurring: item.list_rate.date_start_recurring,
                        date_end_recurring: item.list_rate.date_end_recurring,
                        start_date: item.list_rate.start_date,
                        time_start_recurring: item.list_rate.time_start_recurring,
                        time_end_recurring: item.list_rate.time_end_recurring,
                        employee_id: item.list_rate.employee_id,
                        order_detail_id: item.list_rate.order_detail_id,
                        balance_payment: item.list_rate.balance_payment,
                        specific_day: item.list_rate.specific_day,
                        all_or_specific: item.list_rate.all_or_specific,
                    })
                }

            });

            var calendar = new FullCalendar.Calendar(calendarEl, {
                plugins: ['dayGrid', 'timeGrid', 'bootstrap', 'interaction', 'moment', 'rrule'],
                timeZone: 'UTC',
                selectable: true,
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay'
                },
                select: function (info) {
                    //plugin.create_Appointment(info);
                },
                droppable: true,
                themeSystem: 'bootstrap',
                events:event_render,
                color: 'yellow',
                textColor: 'black',
                editable: true,
                eventLimit: true, // for all non-TimeGrid views
                views: {
                    dayGrid: {
                        eventLimit: 2 // adjust to 6 only for timeGridWeek/timeGridDay
                    }
                },
                eventDrop: function (info, delta, revertFunc) {
                    let id = info.event.id;
                    let start = plugin.get_full_time(info.event.start);
                    let end = plugin.get_full_time(info.event.end);
                    if(info.event._def.extendedProps.is_recurring === '0') {
                        plugin.up_event(id, start, end);
                    }
                },
                eventResize: function (info) {
                    let id = info.event.id;
                    let start = plugin.get_full_time(info.event.start);
                    let end = plugin.get_full_time(info.event.end);
                    if(info.event._def.extendedProps.is_recurring === '0') {
                        plugin.up_event(id, start, end);
                    }
                },
                eventClick: function (info, element) {
                    let service_id = info.event._def.extendedProps.service_id;
                    let employee_id = info.event._def.extendedProps.employee_id;
                    let order_id = info.event._def.extendedProps.order_id;
                    let order_detail_id = info.event._def.extendedProps.order_detail_id;
                    let balance_payment = info.event._def.extendedProps.balance_payment;
                    let service_choosen = list_service.find(function (service) {
                            if(service.id === service_id) {
                                return  service;
                            }
                    });
                    plugin.setCustomServiceChoosen(service_choosen, info);
                    if(balance_payment === '0') {
                        $element.find('button.btn-request-payment').prop('disabled', true);
                    }else {
                        $element.find('button.btn-request-payment').prop('disabled', false);
                    }

                    $element.find('input[name="service_id"]').val(service_id);
                    $element.find('input[name="employee_id"]').val(employee_id);
                    $element.find('input[name="order_id"]').val(order_id);
                    $element.find('input[name="order_detail_id"]').val(order_detail_id);
                    $element.find('#calendarModal').modal('toggle');
                },
                eventRender: function (info) {
                    $(info.el).css('background-color', info.event._def.extendedProps.service_color)
                    $(info.el).find('.fc-title').append('<i class="icon-nb-calendar"></i>');
                    let employee_image_src = wpbookingpro_root_url_plugin + info.event._def.extendedProps.employee_cover;

                    if(plugin.settings.is_demo) {
                        let checkImageSize = false;
                        plugin.getBase64FromImageUrl(plugin.settings.url_image_demo + info.event._def.extendedProps.employee_cover,  function (blobImage) {
                            if(blobImage.size > 0) {
                                checkImageSize = true;
                            }
                        });
                        if(checkImageSize) {
                            employee_image_src = plugin.settings.url_image_demo + info.event._def.extendedProps.employee_cover;
                        } else {
                            employee_image_src = wpbookingpro_root_url_plugin + info.event._def.extendedProps.employee_cover;
                        }

                    }
                    $(info.el).find(".fc-content").append(`
                        <p class="time-booking">${info.event._def.extendedProps.list_time_detail}</p>
                        <div class="employee">
                                <div class="img-box">
                                    <div>
                                        <img src="${employee_image_src}" alt="">
                                    </div>
                                </div>
                                <span>${info.event._def.extendedProps.employee_fullname}</span>
                        </div>
                    `
                    );
                    if(info.event._def.extendedProps.is_recurring === '1') {
                        if(info.event._def.extendedProps.type_recurring === 'daily') {
                            $(info.el).find(".fc-content").append('<span class="is-recurring" style="background-color: #a0e4a0">Daily</span>');
                        } else if(info.event._def.extendedProps.type_recurring === 'weekly') {
                            $(info.el).find(".fc-content").append('<span class="is-recurring" style="background-color: #fdd07e">Weekly</span>');
                        } else if(info.event._def.extendedProps.type_recurring === 'monthly') {
                            $(info.el).find(".fc-content").append('<span class="is-recurring" style="background-color: #e89de8">Monthly</span>');
                        }
                    }

                    $(info.el).tooltip();
                    $(info.el).popover({
                        html: true,
                        content: function () {
                            let $html = `
                                <p class="time-booking"><i class="icon-nb-clock"></i> <span>${info.event._def.extendedProps.list_time_detail}</span></p>
                                <p class="location-booking"><i class="icon-nb-pin"></i> <span>${info.event._def.extendedProps.location_address}</span></p>
                                <p class="customer-booking"><i class="icon-nb-email"></i> <span>${info.event._def.extendedProps.customer_email}</span> </p>
                                <div class="employee-booking">
                                    <div class="img-box">
                                        <div>
                                            <img src="${employee_image_src}" alt="">
                                        </div>
                                    </div>
                                    <span>${info.event._def.extendedProps.employee_fullname}</span>
                                </div>
                               
                            `;
                            return $html;
                        },
                        title: function () {
                            let $title = `
                                <span>${info.event.title}</span>
                                <div class="color" style="background-color: ${info.event._def.extendedProps.service_color}"></div>
                            `;
                            return $title;
                        },
                        delay: {"show": 500, "hide": 500},
                        placement: "top",
                        trigger: 'manual'
                    }).on('mouseenter', function () {
                        var _this = this;
                        $(this).popover('show');
                        $('.popover').on('mouseleave', function () {
                            $(_this).popover('hide');
                        });
                    }).on('mouseleave', function () {
                        var _this = this;
                        setTimeout(function () {
                            if (!$('.popover:hover').length) {
                                $(_this).popover('hide');
                            }
                        }, 300);
                    });
                },
            });
            calendar.render();
            $element.find('li.employee-item').on('click', function () {
                $element.find('li.employee-item').removeClass('active');
                $(this).addClass('active');
                let employee_id = $(this).data('employee_id');
                $element.find('#calendar').empty();
                plugin.filter_order_by_employee(employee_id);

            });
            $element.find('form[name="client-form"]').each(function (e) {
                $(this).validate({
                    ignore: ""
                });
            });
            $element.find('.btn-edit-order').on('click', function () {
                let $form = $(this).closest('form[name="client-form"]');
                $form.find('input[name="task"]').val('order.edit_order_by_order_id');
                let is_ok = plugin.validateFormBeforeSubmit($form);
                if(is_ok) {
                    $form.submit();
                }

            });
            $element.find('.btn-remove-order').on('click', function () {
                let $form = $(this).closest('form[name="client-form"]');
                $form.find('input[name="task"]').val('order.remove_order_by_order_id');
                let is_ok = plugin.validateFormBeforeSubmit($form);
                if(is_ok) {
                    $form.submit();
                }
            });
            $element.find('.btn-request-payment').on('click', function () {
                let $form = $(this).closest('form[name="client-form"]');
                $form.find('input[name="task"]').val('order.send_request_payment');
                let is_ok = plugin.validateFormBeforeSubmit($form);
                if(is_ok) {
                    $form.submit();
                }
            })
        };
        plugin.init();
    };
    $.fn.view_list_calendar = function (options) {
        return this.each(function () {
            if (undefined === $(this).data('view_list_calendar')) {
                let plugin = new $.view_list_calendar(this, options);
                $(this).data('view_list_calendar', plugin);
            }
        });
    }
})(jQuery);