import { Controller } from 'stimulus';
import Cookies from 'js-cookie';
import { renderFormAnonym, sendReserve, renderFormBitrix } from "./../components/record";

const helper = require("./../components/helper.js");
const record = require("./../components/record.js");

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="specialistView" attribute will cause
 * this controller to be executed. The name "specialistView" comes from the filename:
 * detailDoctor_controller.js -> "specialistView"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    connect() {
        let currentDate = this.element.dataset.st;
        let bodyModal = document.getElementById('detail-specialist');
        var btnNext = bodyModal.querySelector('.btn-next');   
        var btnPrev = bodyModal.querySelector('.btn-prev');
        
        btnNext.addEventListener('click', function(evn) { 
            if (this.dataset.currentdate) {
               var date = this.dataset.currentdate;
            } else {
                var date = currentDate;
            }

            btnPrev.dataset.currentdate = new Date(date);
            btnPrev.classList.remove('d-none');
            bodyModal.querySelector('.popup-btns').classList.remove('justify-content-end');
            bodyModal.querySelector('.popup-btns').classList.add('justify-content-between');
            date = getNextWeek(date);
            
            this.dataset.currentdate = new Date(date);
            var departmentId = bodyModal.dataset.departmentid;
            var specialistId = bodyModal.dataset.specialistid;
            var filialId = bodyModal.dataset.filialid;
            var onlineMode = bodyModal.dataset.onlinemode;

            pullInterval(specialistId, departmentId, filialId, date, onlineMode);
        });
        

        btnPrev.addEventListener('click', function(evn) { 
            if (this.dataset.currentdate) {
               var date = this.dataset.currentdate;
            } else {
                var date = currentDate;
            }

            var nDate = new Date(currentDate).toLocaleString('ru', {year: 'numeric',month: 'numeric',day: 'numeric'});
            var cDate = new Date(date).toLocaleString('ru', {year: 'numeric',month: 'numeric',day: 'numeric'});
            
            if (nDate == cDate) {
                this.classList.add('d-none');
                bodyModal.querySelector('.popup-btns').classList.add('justify-content-end');
                bodyModal.querySelector('.popup-btns').classList.remove('justify-content-between');
            }

            btnNext.dataset.currentdate = new Date(date);
            
            var departmentId = bodyModal.dataset.departmentid;
            var specialistId = bodyModal.dataset.specialistid;
            var filialId = bodyModal.dataset.filialid;
            var onlineMode = bodyModal.dataset.onlinemode;
            
            pullInterval(specialistId, departmentId, filialId, date, onlineMode);
            
            this.dataset.currentdate = new Date(getPrevWeek(date));
        });

        this.element.querySelectorAll('.show-specialist-detail').forEach(function(btn) {
            btn.addEventListener('click', function(evn) { 
                btnPrev.classList.add('d-none');
                bodyModal.querySelector('.popup-btns').classList.remove('justify-content-between');
                bodyModal.querySelector('.popup-btns').classList.add('justify-content-end');
                
                var departmentId = bodyModal.dataset.departmentid = btn.dataset.departmentid;
                var specialistId = bodyModal.dataset.specialistid = btn.dataset.specialistid;
                bodyModal.dataset.company = btn.dataset.company;
                var filialId = bodyModal.dataset.filialid = btn.dataset.filialid;
                var onlineMode = bodyModal.dataset.onlinemode = btn.dataset.onlinemode;

                pullInterval(specialistId, departmentId, filialId, currentDate, onlineMode);
                pullDoctor(specialistId);
            });
        });

        function pullDoctor(doctor) {
            var modal = bodyModal.querySelector('.popup__content');

            $.ajax({
                dataType: "json",
                method: "GET",
                crossDomain: true,
                url: "/api/doctor",
                data: {
                    'sid': doctor,
                },
                beforeSend() {
                    modal.querySelector('.loading').classList.remove('d-none');
                    var aboutSpecialist = modal.querySelector('.about-specialist')
                        aboutSpecialist.classList.add('d-none'); 
                    
                    aboutSpecialist.querySelector('.popup-staff__img').remove(); 
                },
                success(data) {
                    modal.querySelector('.loading').classList.add('d-none');
                    modal.querySelector('.about-specialist').classList.remove('d-none');
                    var content = modal.querySelector('.about-specialist');
                    
                    var img = document.createElement('div');
                        img.src = data.data.img;
                        img.classList = 'img-vr popup-staff__img';    
                        img.style.background = 'url(' + data.data.img + ') no-repeat';
                        img.style.backgroundSize = 'cover';
                        img.style.backgroundPosition = 'center -5px';
                    
                    content.prepend(img);
                    content.querySelector('.popup-staff__name').innerHTML = data.data.name;
                    content.querySelector('.popup-staff__position').innerHTML = '';

                    if (data.data.speciality) {
                        content.querySelector('.popup-staff__position').innerHTML = data.data.speciality;
                    }

                    content.querySelector('.popup-staff__exp').innerHTML = '';

                    if (data.data.experience) {
                        content.querySelector('.popup-staff__exp').innerHTML = 'Стаж:' + data.data.experience;
                    }
                }
            });
        }

        function pullInterval(doctor, department, filial, date, onlineMode) {
            let wrap = bodyModal.querySelector('.calendar-wrap');
            let calendarBody = bodyModal.querySelector('.calendar-body');

            $.ajax({
                dataType: "json",
                method: "GET",
                crossDomain: true,
                url: "/api/interval",
                data: {
                    'update' : true,
                    'doctor': doctor,
                    'department': department,
                    'filial': filial,
                    'startInterval': getMonday(date),
                    'endInterval': getSunday(date),
                    'onlineMode': onlineMode
                },
                beforeSend() {
                    bodyModal.querySelector('.current-dates').innerHTML = getMonday(date) + ' - ' + getSunday(date);
                    wrap.innerHTML = "Идет загрузка...";
                },
                success(response) {
    
                    var isNotFree = true;

                    wrap.innerHTML = "";
                    response.data.intervalsData.forEach(function(el) {    
                        if (el.isFree == true) {
                            var date = new Date(el.workDate).toLocaleString('ru', {
                                weekday: 'long', 
                                month: 'long',
                                day: 'numeric'
                            });

                            var calBody = document.createElement('div');
                            calBody.classList = 'calendar-body popup-inteval__item';

                            var timeDiv = document.createElement('div');
                            timeDiv.classList = 'popup-inteval__date';
                            timeDiv.innerHTML = date + ' <i>' + el.startInterval + '—'+ el.endInterval + '</i>';
                            calBody.append(timeDiv);


                            var intervalTimeDiv = document.createElement('div');
                                intervalTimeDiv.classList = 'time-intervals';

                            var intervalDiv = document.createElement('div');
                                intervalDiv.classList = 'interval intervals-wrap';

                            intervalTimeDiv.append(intervalDiv);
                            
                            for (let [key, item] of Object.entries(el.intervals)) {
                                if (item.isFree == true) {
                                    isNotFree = false;

                                    var spanInterval = document.createElement('span');

                                    spanInterval.classList = 'time available';
                                    spanInterval.innerText = item.startTime;
                                    spanInterval.dataset.workDate = item.workDate;
                                    spanInterval.dataset.schedident = item.schedident;
                                    spanInterval.dataset.time = item.time;
                                    spanInterval.dataset.onlinemode = item.onlineMode;
                                    spanInterval.dataset.rnum = item.rNum;

                                    spanInterval.dataset.specialistid = doctor;
                                    spanInterval.dataset.filialid = filial;
                                    spanInterval.dataset.department = department;
                                    
                                    spanInterval.addEventListener('click', function (evn) {
                                        var popupWrap = document.getElementById('popup');
                                        evn.target.dataset.onlinemode = item.onlineMode;

                                        if (record.renderFormRecord(response.data.userInfo, evn.target.dataset)) {
                                            if (response.data.userInfo) {
                                                evn.target.innerHTML = '<img width="20" src="/images/eclipse.gif">';
                                                record.sendReserve(popupWrap)
                                            } else {
                                                $(popupWrap).modal('show');
                                            }
                                        }
                                    })

                                    intervalDiv.append(spanInterval);
                                }
                            }

                            if (!isNotFree) {
                                calBody.append(intervalDiv);
                                wrap.append(calBody);
                            }
                        }
                    });

                    if (isNotFree) {
                        wrap.innerHTML = "Всё занято. Выберите другую неделю.";
                    }
                }
            });
        }

        function getMonday(date) {
            date = new Date(date);

            return new Date(date.setDate(date.getDate() - date.getDay() + 1))
                .toLocaleString('ru', {
                    year: 'numeric', 
                    month: 'numeric',
                    day: 'numeric',
                });
        }

        function getSunday(date) {
            date = new Date(date);

            return new Date(date.setDate(date.getDate() - date.getDay() + 7))
                .toLocaleString('ru', {
                    year: 'numeric', 
                    month: 'numeric',
                    day: 'numeric',
                });
        }
        
        function getNextWeek(date) {
            date = new Date(date);

            return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7); 
        }

        function getPrevWeek(date) {
            date = new Date(date);

            return new Date(date.getFullYear(), date.getMonth(), date.getDate() - 7); 
        }
    }
}
