import { Controller } from 'stimulus';
import Cookies from 'js-cookie';
const loader = require("./../components/loader.js");
const helper = require("./../components/helper.js");
const misSession = require("./../components/misSession.js");

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="caseHistory" attribute will cause
 * this controller to be executed. The name "caseHistory" comes from the filename:
 * caseHistory_controller.js -> "caseHistory"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    async cashBack(evn) {
        loader.btnLoader(evn.target, true)

        var popup = document.getElementById('popup');
        popup.querySelector('.modal-title').innerHTML = 'Возврат средств';
        popup.querySelector('.modal-dialog').classList = 'modal-dialog modal-md';
        
        try {
            const response = await fetch('/refund?filial=' + evn.target.dataset.filial);

             if (response.ok) {
                const text = await response.text();
                
                popup.querySelector('.modal-body').innerHTML = text;
                loader.btnLoader(evn.target, false);
                $(popup).modal('show');

                popup.querySelector('#refund_address').value = window.webSDK.data.user.address;
                popup.querySelector('#refund_phone').value = window.webSDK.data.user.phone;
                popup.querySelector('#refund_email').value = window.webSDK.data.user.email;
                popup.querySelector('#refund_schedident').value = evn.target.dataset.schedident;
                popup.querySelector('#refund_time').value = evn.target.dataset.time;
                popup.querySelector('#refund_doc_name').value = evn.target.dataset.docName;

                document.getElementById('refund-form').querySelector('button').addEventListener('click', function() {
                    if ($('#refund-form')[0].checkValidity()) {
                        $(popup).modal('hide');
                    }
                })
            }

        }  catch (error) {
            console.error('Error:', error);
            loader.btnLoader(evn.target, false);
        }
    }

    connect() {
        loader.loadSDK('caseHistory').then(function(webSDK) {
            webSDK.on('init', function() {
                if (this.data.user.authenticated) {
                    runWebSDK(webSDK);           
                } else {
                    window.location.pathname = '/logout'
                }
            });
        })

        var securityRecord = this.element;
        var popup = document.getElementById('popup');

        let runWebSDK = function (webSDK) {
            scheduleRecordList(webSDK, securityRecord);
        }

        var securityTabs = document.getElementById('security-tabs');
        var tabsDecktop = securityTabs.querySelectorAll('a');
        var alertInfo = document.getElementById('alert-case-history-info');
        
        if (tabsDecktop.length > 0) {
            tabsDecktop.forEach(function (el) {
                el.addEventListener('click', function (evn) {
                    evn.target.classList = 'tab-item tab-item--active';
                    
                    if (evn.target.dataset.alert === 'true') alertInfo.classList.remove('d-none');

                    securityTabs.querySelectorAll('a').forEach(function (a) {
                        if (evn.target.dataset.allowRemove != a.dataset.allowRemove) {
                            a.classList.remove('tab-item--active');
                        }      
                    });
                    
                    var history = (evn.target.dataset.allowRemove == 'true');
                    filter(history, securityRecord);
                });
            });
        } else {
            securityTabs.addEventListener('change', function(evn) {
                if (evn.target.alert === 'true') alertInfo.classList.remove('d-none');

                var history = (evn.target.value == 'true');
                filter(history, securityRecord);
            });
        }

        function filter(history, securityRecord) {
            var items = securityRecord.querySelectorAll('.item-record');
            if (items) {
                var count = 0;
                items.forEach(function (item) {
                    if (history == true) {
                        item.classList.add('d-none');
                        if (item.dataset.workDate >= window.dateFormat(new Date())) {
                            item.classList.remove('d-none');
                            count++;
                        }
                    } else {
                        item.classList.add('d-none');
                        
                        if (item.dataset.workDate < window.dateFormat(new Date())) {
                            if (item.dataset.onlinemode == '1') {
                                item.querySelector('.btn-conference').classList.remove('d-inline');
                                item.querySelector('.btn-conference').classList.add('d-none');
                                item.querySelector('.online-warning').classList.remove('d-none');
                                console.log(item.querySelector('.online-warning'));

                                var refundBtn = item.querySelector('.btn-cash-back')
                                refundBtn.classList.add('d-inline');
                                refundBtn.dataset.schedident = item.dataset.schedident
                                refundBtn.dataset.filial = item.dataset.filial
                                refundBtn.dataset.time = item.dataset.time
                                refundBtn.dataset.docName = item.dataset.docName
                            }

                            item.classList.remove('d-none');
                            count++;
                        }
                    }

                    notItems(count);
                });
            }
        }

        function notItems(count) {
            var load = securityRecord.querySelector('.load');
                load.classList.add('d-none');
            
            if (count == 0) {
                load.innerHTML = 'Записей не найдено';
                load.classList.remove('d-none');
            }
        }

        var renderItems = function(items, securityWrap) {
            var count = 0;
            
            items.forEach(function(data, i) {
                var blockItem = securityRecord.querySelector('.item-record').cloneNode(true);
                blockItem.dataset.workDate = data.workDate;
                blockItem.dataset.onlinemode = data.onlineType ?? 0;
                blockItem.dataset.docName = data.docName;
                blockItem.dataset.time = data.startTime+ ' '+ data.endTime;
                blockItem.dataset.schedident = data.schedident;
                blockItem.dataset.filial = data.filial;
                blockItem.dataset.dcode = data.dcode;

                if (blockItem.dataset.dcode) {
                    helper.sendRequest({
                        'sid': blockItem.dataset.dcode,
                        'onlineMode': blockItem.dataset.onlineType ?? 0
                    }, "/api/doctor", "GET").then(function (response) {
                        if (response.data) {
                            blockItem.querySelector('.img-vr').style.background = 'url(' + response.data.img + ') center -5px / cover';
                            blockItem.querySelector('.position').innerHTML = response.data.speciality;
                            
                            if (response.data.kinder != null) {
                                var kinder = blockItem.querySelector('.kinder');
                                kinder.classList.remove('d-none');
                                kinder.querySelector('.val').innerHTML = response.data.kinder;
                            }

                            if (response.data.expirience != null) {
                                var kinder = blockItem.querySelector('.expirience');
                                kinder.classList.remove('d-none');
                                kinder.querySelector('.val').innerHTML = response.data.expirience;
                            }

                            blockItem.querySelectorAll('.link-specialist').forEach(function (el) {
                                el.href = '/specialist/' + response.data.alias;
                            });
                        } else {
                            blockItem.querySelector('.img-vr').style.background = 'url(/images/no_img.png) center -5px / cover';
                            blockItem.querySelector('.position').innerHTML = '';
                        }
                    });
                }
                
                var date = window.newDate(data.workDate);
                
                if (Cookies.get('region') == 91) {
                    var timeZona  = '<br>время саратовское';
                } else {
                    var timeZona  = '<br>время московское';
                }

                blockItem.querySelector('.month').innerHTML = getWeekDay(date);
                blockItem.querySelector('.date').innerHTML = window.dateFormat(date, 'd-m-Y') + ' '
                    + data.startTime + timeZona;
                blockItem.querySelector('.address').innerHTML = (data.filialName == 'Онлайн клиника') ? 'Онлайн-консультация' : data.filialName;
                blockItem.querySelector('.section-favorite').dataset.sid = data.dcode;
                blockItem.querySelector('.specialist').innerHTML = data.docName;                            
                
                var btnClose = blockItem.querySelector('.btn-close');
                    btnClose.classList.add('d-none');
                
                if (data.allowRemove) {    
                    btnClose.classList.remove('d-none');
                    btnClose.dataset.id = data.id;
                    btnClose.dataset.filial = data.filial;
                    btnClose.addEventListener('click', function () {
                        if (confirm("Подтвердите удаление")) {
                            webSDK.scheduleRecRemove({
                                'reserveId': btnClose.dataset.id,
                                'filialId': btnClose.dataset.filial
                            }).then(function (resolve) {
                                document.location.reload();
                            }).catch(function (error) {
                                helper.sendRequest({
                                    data: {'error': error, method: 'scheduleRecRemove'}
                                }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                            })
                        }
                    });
                }

                var btnConfirence = blockItem.querySelector('.btn-conference');
                var accept = blockItem.querySelector('.accept');
                var licenseLink = helper.getLicenseLink(Cookies.get('region'));
                var license = document.createElement('p');

                if (data.onlineType && data?.payment?.status?.id != 0) {
                    license.innerHTML = `Пожалуйста, не забудете за 5 минут до начала консультации войти в личный кабинет и потом нажать кнопку «Онлайн прием» для начала консультации.`;
                    accept.append(license);
                    
                    var warning = document.createElement('p');
                    warning.innerHTML=`<b>Внимание!</b> В начале онлайн-консультации вам будет необходимо подтвердить своё согласие с информированным добровольным согласием на медицинское вмешательство (ИДС).`;
                    accept.append(warning);

                    btnConfirence.classList.remove('d-none')
                    btnConfirence.classList.add('d-inline')
                    btnConfirence.setAttribute('data-id' , data.id)
                    btnConfirence.setAttribute('data-filial' , data.filial)
                    btnConfirence.addEventListener('click', function () {
                        popup.querySelector('#popup-body').innerHTML = '';

                        misSession.ensureAuthenticated(webSDK).then(function() {
                            return webSDK.openConference({
                                schedid: btnConfirence.dataset.id
                            });
                        }).then(function () {
                            if (!misSession.mountConferenceInPopup(popup)) {
                                throw { data: { message: 'Не удалось открыть окно онлайн-консультации.' } };
                            }
                        }).catch(function (e) {
                            if (misSession.handleMisSessionFailure(popup, e)) {
                                helper.sendRequest({
                                    data: {'error': e, method: 'openConference', reason: 'mis_session_expired'}
                                }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                                return;
                            }

                            if (typeof e.data?.message !== 'undefined') {
                                var msg = e.data.message.replace('UTC+3', 'UTC+3 (московское время)');
                                popup.querySelector('#popup-body').innerHTML = msg;
                                popup.querySelector('.modal-dialog').classList = 'modal-dialog';
                                popup.querySelector('.modal-content').classList = 'modal-content';
                                popup.querySelector('.modal-title').innerHTML = 'Уведомление';
                                $(popup).modal('show');
                            }

                            helper.sendRequest({
                                data: {'error': e, method: 'openConference'}
                            }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                        });
                    });

                } else {
                    btnConfirence.classList.add('d-none')
                }

                var btnPayment = blockItem.querySelector('.btn-pay');

                if (data.payment && data.payment.status.id == 0 && data.allowRemove) {
                    license.innerHTML = `Для получения возможности провести оплату консультации - подтвердите согласие на присоединение к договору оферты:`;
                    accept.append(license);
                    blockItem.querySelector('.online-warning').classList.remove('d-none');
                    console.log(blockItem.querySelector('.online-warning'));
                    
                    var politics = document.createElement('div');
                    politics.classList = "form-check";
                    
                    var politicsInput = document.createElement('input');
                    politicsInput.type="checkbox";
                    politicsInput.classList="form-check-input";
                    politicsInput.id="accept-btn";
                    politics.append(politicsInput);
                    
                    var politicsLabel = document.createElement('label');
                    politicsLabel.classList = "form-check-label";
                    politicsLabel.htmlFor="accept-btn";
                    politics.append(politicsLabel);

                    politicsLabel.innerHTML = `Согласен с <a href="${licenseLink}" target="_blank">политикой в отношении обработки персональных данных</a>`;
                    politics.addEventListener('click', function () {
                        console.log('politics', politicsInput.checked, personalInput.checked, ofertaInput.checked);
                        btnPayment.classList.add('disabled');
                        btnPayment.disabled = true;

                        if (politicsInput.checked && personalInput.checked && ofertaInput.checked) {
                            btnPayment.classList.remove('disabled');
                            btnPayment.disabled = false;   
                        }
                    });
                    accept.append(politics);

                    var personal = document.createElement('div');
                    personal.classList = "form-check";
                    
                    var personalInput = document.createElement('input');
                    personalInput.type="checkbox";
                    personalInput.classList="form-check-input";
                    personalInput.id="accept-personal";
                    personal.append(personalInput);
                    
                    var personalLabel = document.createElement('label');
                    personalLabel.classList = "form-check-label";
                    personalLabel.htmlFor="accept-personal";
                    personal.append(personalLabel);

                    personalLabel.innerHTML = `Согласен с <a href="${licenseLink}" target="_blank">обработкой персональных данных</a>.`;
                    personal.addEventListener('click', function () {
                        btnPayment.classList.add('disabled');
                        btnPayment.disabled = true;

                        if (politicsInput.checked && personalInput.checked && ofertaInput.checked) {
                            btnPayment.classList.remove('disabled');
                            btnPayment.disabled = false;   
                        }
                    });
                    accept.append(personal);

                    var oferta = document.createElement('div');
                    oferta.classList = "form-check";
                    
                    var ofertaInput = document.createElement('input');
                    ofertaInput.type="checkbox";
                    ofertaInput.classList="form-check-input";
                    ofertaInput.id="accept-oferta";
                    oferta.append(ofertaInput);
                    
                    var ofertaLabel = document.createElement('label');
                    ofertaLabel.classList = "form-check-label";
                    ofertaLabel.htmlFor="accept-oferta";
                    oferta.append(ofertaLabel);

                    ofertaLabel.innerHTML = `Присоединяюсь к договору <a href="/docs/oferta.pdf" target="_blank">оферты</a>`;
                    oferta.addEventListener('click', function () {
                        btnPayment.classList.add('disabled');
                        btnPayment.disabled = true;

                        if (politicsInput.checked && personalInput.checked && ofertaInput.checked) {
                            btnPayment.classList.remove('disabled');
                            btnPayment.disabled = false;   
                        }
                    });
                    accept.append(oferta);

                    btnPayment.classList.remove('d-none');
                    btnPayment.classList.add('d-inline');
                    btnPayment.querySelector('.amt').innerHTML = data.payment.amt;
                    btnPayment.setAttribute('data-id' , data.payment.id);
                    btnPayment.setAttribute('data-filial' , data.filial);
                    btnPayment.setAttribute('data-amt' , data.payment.amt);
                    btnPayment.setAttribute('data-payprofileid' , data.payment.magazineId);
                    btnPayment.addEventListener('click', function () {
                        var params = {
                            'orderid': Number(btnPayment.dataset.id) ,
                            'payprofileid': btnPayment.dataset.payprofileid,
                            'payamount': btnPayment.dataset.amt,
                            'paymethod': 'AC',
                            'filial': Number(btnPayment.dataset.filial),
                            'pcode': webSDK.data.user.id,
                            'successurl': document.location.origin + '/case-history#pay-success',
                            'errorurl': document.location.origin + '/case-history#error',
                            'containerId': 'popup-body',
                        };

                        misSession.ensureAuthenticated(webSDK).then(function() {
                            webSDK.loadPaymentView(params);
                            popup.querySelector('#popup-body').innerHTML = '';
                            popup.querySelector('.modal-title').innerHTML = 'Оплата';
                            $(popup).modal('show');
                        }).catch(function(e) {
                            if (misSession.handleMisSessionFailure(popup, e)) {
                                helper.sendRequest({
                                    data: {'error': e, method: 'loadPaymentView', reason: 'mis_session_expired'}
                                }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                                return;
                            }

                            helper.sendRequest({
                                data: {'error': e, method: 'loadPaymentView'}
                            }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                        });
                    });
                } else {
                    btnPayment.classList.add('d-none');
                }

                if (data.workDate >= window.dateFormat(new Date())) {
                    blockItem.classList.remove('d-none');
                    count++;
                }
 
                securityWrap.append(blockItem);
            });

            notItems(count);
        }

        function scheduleRecordList(webSDK, securityRecord) {
            // Если страница загружена после создания записи, добавляем небольшую задержку
            // чтобы дать серверу время обработать новую запись
            var delay = (location.hash === '#doctor-success' || location.hash === '#online') ? 500 : 0;
            
            setTimeout(function() {
                webSDK.loadScheduleRecList({
                    st: 20170101,
                    en: window.dateFormat(new Date((new Date()).getFullYear(), (new Date()).getMonth() + 6, 0)),
                    start: 0,
                    length: 500
                }).then(function (resolve) {
                    renderItems(resolve.data, securityRecord.querySelector('.section-wrap'));
                }).catch(function(e) {
                    helper.sendRequest({
                        data: {'error': e, method: 'loadScheduleRecList'}
                    }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                    securityRecord.querySelector('.load').innerHTML = 'Записей не найдено';
                });
            }, delay);
        }
    }
}

