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

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="default" attribute will cause
 * this controller to be executed. The name "default" comes from the filename:
 * default_controller.js -> "default"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    connect() {
        var referenceWrapper = this.element;

        window.addEventListener("mousemove",(e) => {
            window.parent.postMessage({ type: "user_mousemove" }, "*");
        });

        window.addEventListener("input",(e) => {
            window.parent.postMessage({ type: "user_typing" }, "*");
        });

        let evnRender = function (responsibleUser, countFilial) {
            this.renderResponsibleUser(responsibleUser, countFilial);
        }.bind(this)

        var changeResponsible = function (countFilial, value) {
            var responsibleFilial = referenceWrapper.querySelector('.responsible_filial_' + countFilial);
            var responsibleUser = responsibleFilial.querySelector('.responsible_user');
            
            if (value == 1) {
                responsibleUser.innerHTML = '';
            } else {
                evnRender(responsibleUser, countFilial)
            }
        } 

        referenceWrapper.querySelector('.reference-responsible').addEventListener('change', function() {
            changeResponsible(this.dataset.count, this.value);
        })

        let evnRenderSending = function (referenceSending) {
            this.renderSending(referenceSending);
        }.bind(this)
        
        const addFilial = referenceWrapper.querySelector('button.add-filial');
        const referenceFilial = referenceWrapper.querySelector('#reference_filial');
        const referenceFilialSending = referenceWrapper.querySelector('#reference_filialSending');
        const referenceSending = referenceWrapper.querySelector('#reference_sending');
        const filialSendingWrapper = referenceWrapper.querySelector('.filial-sending');

        const syncSendingUi = () => {
            if (!referenceSending || !filialSendingWrapper) return;

            // Разрешённые варианты:
            // 1 = "Лично в клинике"
            // 2 = "Отправка в налоговую инспекцию"
            // Любое другое/невалидное значение считаем "1".
            const sendingSafe = (referenceSending.value === '2' || referenceSending.value === 2) ? '2' : '1';

            // "Лично в клинике" => 1 => показываем выбор клиники получения справки
            filialSendingWrapper.classList.toggle('d-none', sendingSafe !== '1');

            // При "Лично" синхронизируем филиал получения.
            // Если filialSending ещё не выбран (пустой) — НЕ блокируем, чтобы можно было выбрать вручную.
            if (sendingSafe === '1') {
                if (referenceFilial.selectedIndex > 0) {
                    referenceFilialSending.selectedIndex = referenceFilial.selectedIndex;
                }

                referenceFilialSending.disabled = Boolean(referenceFilialSending.value);
            } else {
                referenceFilialSending.disabled = false;
            }
        };

        if (referenceSending) {
            referenceSending.addEventListener('change', syncSendingUi);
        }
        syncSendingUi();

        referenceFilial.addEventListener('change', function(evn) {
            // Если выдача "Лично в клинике" — синхронизируем филиал получения
            const sendingSafe = (referenceSending && (referenceSending.value === '2' || referenceSending.value === 2)) ? '2' : '1';
            if (sendingSafe === '1') {
                if (referenceFilial.selectedIndex > 0) {
                    referenceFilialSending.selectedIndex = referenceFilial.selectedIndex;
                }
                referenceFilialSending.disabled = Boolean(referenceFilialSending.value);
            } else {
                referenceFilialSending.selectedIndex = 0;
                referenceFilialSending.disabled = false;
            }
            addFilial.classList.remove('d-none');
        });

        addFilial.addEventListener('click', function() {
            var countFilial = parseInt(this.dataset.count, 10);
            var responsibleFilial = referenceWrapper.querySelector('.responsible_filial_' + countFilial)           
            var newFilialCount = countFilial + 1
            this.dataset.count = newFilialCount;
            var newFilial = referenceWrapper.querySelector('.responsible_filial_' + countFilial).cloneNode(true);
            newFilial.classList = 'responsible_filials responsible_filial_' + newFilialCount;
            newFilial.querySelector('.reference-filial').id = 'reference_filial_' + newFilialCount;
            newFilial.querySelector('.reference-filial').classList = 'reference-filial form-control';
            newFilial.querySelector('.valid-reference_filial').innerHTML = '';
            newFilial.querySelector('.responsible_user').innerHTML = '';
            newFilial.querySelector('.reference-responsible').id = 'reference_responsible_' + newFilialCount;
            
            newFilial.querySelector('.reference-period-first').id = 'reference_periodFirst_' + newFilialCount;
            newFilial.querySelector('.reference-period-first').classList = 'reference-period-first form-control';

            newFilial.querySelector('.reference-period-last').id = 'reference_periodLast_' + newFilialCount;
            newFilial.querySelector('.reference-period-last').classList = 'reference-period-last form-control';

            newFilial.querySelector('.reference-responsible').addEventListener('change', function() {
                changeResponsible(newFilialCount, this.value);
            })
            
            responsibleFilial.parentNode.insertBefore(newFilial, responsibleFilial.nextSibling);
        })
        var crmFields = {};

        helper.sendRequest(
            [], 
            'https://sovamed.bitrix24.ru/rest/10998/3hrv38rzo3khchj3/crm.lead.fields.json', 
            'GET', 
            'json', 
            false,
            'application/json'
        ).then(function(response) {
            crmFields = response;
        });

        var submit = referenceWrapper.querySelector('button.submit'); 
        
        submit.addEventListener('click', function() {
            evnClick(referenceWrapper, crmFields);
        })

        let evnClick = function (wrapper, crmFields) {
            var result = this.submit(wrapper);
            var params = { 
                'fields' : {
                    'TITLE': 'Получение документов для налогового вычета',
                    'NAME': result.options.autorName,
                    'PHONE': [{
                        'VALUE': result.options.phone, 
                        'VALUE_TYPE': 'WORK' 
                    }],
                    'ASSIGNED_BY_ID' : 506,
                    'UF_CRM_1539951158': helper.getCityId(result.options.filials[0].filial),
                    'UF_CRM_1565783329': result.options.inn,
                    'UF_CRM_1658495790': '',
                    'UF_CRM_1565783428': result.options.filials[0].periodFirst + " - " + result.options.filials[0].periodLast,
                    'UF_CRM_1565783258': result.options.birthDate,
                }
            };

            const normalizeFilialValue = (value) => {
                if (typeof value !== 'string') return '';
                return value
                    .replaceAll('\u00A0', ' ') // NBSP -> space
                    .replaceAll('.', '') // "г.Саратов" == "г. Саратов", "д. 33" == "д 33"
                    .replace(/\s+/g, ' ')
                    .replace(/\s*,\s*/g, ', ')
                    .trim()
                    .toLowerCase();
            };

            const filialValue = result.options.filials?.[0]?.filial ?? '';
            const filialValueNormalized = normalizeFilialValue(filialValue);

            // 1) точное совпадение после нормализации
            crmFields.result.UF_CRM_1658495790.items.forEach(function (el) {
                if (params.fields['UF_CRM_1658495790']) return;
                if (filialValueNormalized && filialValueNormalized === normalizeFilialValue(el.VALUE)) {
                    params.fields['UF_CRM_1658495790'] = el.ID;
                }
            });

            // 2) запасной вариант: если Bitrix хранит VALUE без доп. суффикса "(...)" и т.п.
            if (!params.fields['UF_CRM_1658495790'] && filialValueNormalized) {
                const filialValueNoParens = filialValueNormalized.replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim();
                crmFields.result.UF_CRM_1658495790.items.forEach(function (el) {
                    if (params.fields['UF_CRM_1658495790']) return;
                    const bitrixValue = normalizeFilialValue(el.VALUE);
                    if (!bitrixValue) return;
                    if (bitrixValue === filialValueNoParens || filialValueNoParens.includes(bitrixValue) || bitrixValue.includes(filialValueNoParens)) {
                        params.fields['UF_CRM_1658495790'] = el.ID;
                    }
                });
            }

            if (result.options.filials[0].responsible == 0) {
                params.fields['UF_CRM_1565784083'] = 400 //[{"ID": "400","VALUE": "за другого пациента"}];  
                params.fields['UF_CRM_1654588779'] = result.options.filials[0].relation;
                params.fields['UF_CRM_1565784170'] = result.options.filials[0].birthDate;
                params.fields['UF_CRM_1565784142'] = result.options.filials[0].fio;
            } else {
                params.fields['UF_CRM_1565784083'] = 398 //[{"ID": "398","VALUE": "себя"}];  
                params.fields['UF_CRM_1654588779'] = 'за себя';

                params.fields['UF_CRM_1565784170'] = result.options.birthDate;
                params.fields['UF_CRM_1565784142'] = result.options.autorName;
            }

            const sendingSafe = (result.options.sending == 2 || result.options.sending === '2') ? 2 : 1;

            if (sendingSafe == 1) {
                params.fields['UF_CRM_1658499141'] = 2494 //[{"ID": "2494","VALUE": "на руки"}]
                
                const filialSendingValue = result.options.filialSending ?? '';
                const filialSendingValueNormalized = normalizeFilialValue(filialSendingValue);

                // 1) точное совпадение после нормализации
                crmFields.result.UF_CRM_1658497553.items.forEach(function (el) {
                    if (params.fields['UF_CRM_1658497553']) return;
                    if (filialSendingValueNormalized && filialSendingValueNormalized === normalizeFilialValue(el.VALUE)) {
                        params.fields['UF_CRM_1658497553'] = el.ID;
                    }
                });

                // 2) запасной вариант: совпадение без суффикса "(...)" и т.п.
                if (!params.fields['UF_CRM_1658497553'] && filialSendingValueNormalized) {
                    const filialSendingValueNoParens = filialSendingValueNormalized
                        .replace(/\s*\([^)]*\)\s*/g, ' ')
                        .replace(/\s+/g, ' ')
                        .trim();

                    crmFields.result.UF_CRM_1658497553.items.forEach(function (el) {
                        if (params.fields['UF_CRM_1658497553']) return;
                        const bitrixValue = normalizeFilialValue(el.VALUE);
                        if (!bitrixValue) return;
                        if (bitrixValue === filialSendingValueNoParens || filialSendingValueNoParens.includes(bitrixValue) || bitrixValue.includes(filialSendingValueNoParens)) {
                            params.fields['UF_CRM_1658497553'] = el.ID;
                        }
                    });
                }
            } else if (sendingSafe == 2) {
                params.fields['UF_CRM_1658499141'] = 4680 //[{"ID": "4680","VALUE": "отправка в налоговую инспекцию"}]
            }

            if (Object.keys(result.options.filials).length > 1) {
                var comment = "";

                for (var index = 0; index < Object.keys(result.options.filials).length; index++) {
                    if (index !== 0) {
                        comment += "Дополнительно:\n\t"
                        if (result.options.filials[index].responsible == 0) {
                            comment += 'Степень родства: ' + result.options.filials[index].relation + "\n\t";
                            comment += 'ФИО: ' + result.options.filials[index].fio + "\n\t";
                            comment += 'Дата рождения: ' + result.options.filials[index].birthDate + "\n\t";
                        } else {
                            comment += "За себя\n\t";
                            comment += 'ФИО: ' + result.options.autorName + "\n\t";
                            comment += 'Дата рождения: ' + result.options.birthDate + "\n\t";
                        }

                        comment += 'Филиал: ' + result.options.filials[index].filial + "\n\t";
                        comment += 'За период: ' + result.options.filials[index].periodFirst; 
                        comment += ' - ' + result.options.filials[index].periodLast + "\n\t";
                    }
                }

                params.fields['UF_CRM_1545895397'] = comment;
            }

            if (result.invalid) {
                return false;
            }

            loader.btnLoader(submit, true);

            helper.sendRequest(
                params, 
                'https://sovamed.bitrix24.ru/rest/10998/3hrv38rzo3khchj3/crm.lead.add.json', 
                'POST', 
                'json', 
                false,
                'application/json'
            ).then(function(response) {
                loader.btnLoader(submit, false);
                
                if (referenceWrapper.dataset.ref == '/') {
                    helper.sendRequest({'reference' : 1, 'phone' : result.options.phone}, '/api/msg');
                    var successAlert = document.createElement('div');
                    successAlert.classList = 'alert alert-success alert-dismissible fade show';
                    successAlert.setAttribute('role', 'alert');

                    var divMsg = document.createElement('div');
                    divMsg.classList = 'alert-msg';
                    divMsg.innerHTML = '<p>Заявка успешно подана.</p>';
                    successAlert.append(divMsg);

                    var buttonClose = document.createElement('button');
                    buttonClose.classList = 'close';
                    buttonClose.dataset.dismiss ='alert';
                    buttonClose.setAttribute('aria-label', 'Close');
                    buttonClose.innerHTML = '<span aria-hidden="true">&times;</span>';
                    successAlert.append(buttonClose);
                    document.getElementById('alert-system').prepend(successAlert);

                    $(popup).modal('hide');
                    $('html, body').animate({scrollTop:0}, '300');
                } else {
                    window.parent.postMessage({'message': 'hide.modal', 'phone' : result.options.phone}, atob(referenceWrapper.dataset.ref));
                }

            });

        }.bind(this)
    }

    renderSending(referenceSending) {
        var div = document.createElement('div');
        div.classList = 'form-group mb-2';

        var label = document.createElement('label');
        label.innerHTML = 'Почтовый адрес:';
        label.classList = 'mb-0';
        label.setAttribute('for', 'reference_address')
        div.append(label);

        var input = document.createElement('input');
        input.id = 'reference_address';
        input.name = 'reference_address';
        input.classList = 'form-control';
        div.append(input);

        var msg = document.createElement('div')
        msg.classList = 'msg-valid valid-reference_address';
        div.append(msg);
        referenceSending.append(div);
        
        var div = document.createElement('div');
        div.classList = 'form-group mb-2';

        var label = document.createElement('label');
        label.innerHTML = 'Индекс:';
        label.classList = 'mb-0';
        label.setAttribute('for', 'reference_index')
        div.append(label);

        var input = document.createElement('input');
        input.id = 'reference_index'
        input.name = 'reference_index'
        input.classList = 'form-control';
        div.append(input);

        var msg = document.createElement('div')
        msg.classList = 'msg-valid valid-reference_index';
        div.append(msg);

        referenceSending.append(div);
    }

    renderResponsibleUser(responsibleUser, countFilial) {
        var div = document.createElement('div');
        div.classList = 'form-group mb-2';

        var label = document.createElement('label');
        label.innerHTML = 'ФИО пациента:';
        label.classList = 'mb-0';
        label.setAttribute('for', 'reference_patientName_' + countFilial)
        div.append(label);

        var input = document.createElement('input');
        input.id = 'reference_patientName_' + countFilial
        input.name = 'reference_patientName[' + countFilial + ']'
        input.classList = 'form-control';
        div.append(input);

        var msg = document.createElement('div')
        msg.classList = 'msg-valid valid-reference_patientName';
        div.append(msg);
        responsibleUser.append(div);
        
        var div = document.createElement('div');
        div.classList = 'form-group mb-2';

        var label = document.createElement('label');
        label.innerHTML = 'Дата рождения пациента:';
        label.classList = 'mb-0';
        label.setAttribute('for', 'reference_patientBirthDate_' + countFilial)
        div.append(label);

        var input = document.createElement('input');
        input.id = 'reference_patientBirthDate_' + countFilial;
        input.name = 'reference_patientBirthDate[' + countFilial + ']'
        input.classList = 'form-control';
        input.dataset.controller = 'datePicker';
        input.setAttribute('range', false);
        div.append(input);
        responsibleUser.append(div);

        var msg = document.createElement('div')
        msg.classList = 'msg-valid valid-reference_patientBirthDate';
        div.append(msg);

        var div = document.createElement('div');
        div.classList = 'form-group mb-2';

        var label = document.createElement('label');
        label.innerHTML = 'Степень родства:';
        label.classList = 'mb-0';
        label.setAttribute('for', 'reference_relation_' + countFilial)
        div.append(label);

        var select = document.createElement('select');
        select.id = 'reference_relation_' + countFilial;
        select.name = 'reference_relation_[' + countFilial + ']'
        select.classList = 'form-control';
        div.append(select);
        
        var option = document.createElement('option');
        option.innerHTML = 'супруг';
        option.value = 'супруг';
        select.append(option);

        var option = document.createElement('option');
        option.innerHTML = 'супруга';
        option.value = 'супруга';
        select.append(option);

        var option = document.createElement('option');
        option.innerHTML = 'мать';
        option.value = 'мать';
        select.append(option);

        var option = document.createElement('option');
        option.innerHTML = 'отец';
        option.value = 'отeц';
        select.append(option);

        var option = document.createElement('option');
        option.innerHTML = 'сын';
        option.value = 'сын';
        select.append(option);

        var option = document.createElement('option');
        option.innerHTML = 'дочь';
        option.value = 'дочь';
        select.append(option);

        var msg = document.createElement('div')
        msg.classList = 'msg-valid valid-reference_relation';
        div.append(msg);

        responsibleUser.append(div);
    }

    submit(wrapper) {
        var valid, invalid = false;
        var options = {};
        options.autorName = wrapper.querySelector('#reference_autorName').value;

        valid = validator.checkTextRu(
            wrapper.querySelector('#reference_autorName'), 
            wrapper.querySelector(`.valid-reference_autorName`)
        );

        if (valid) {
            invalid = valid
        }

        options.phone = wrapper.querySelector('#reference_phone').value;

        valid = validator.checkPhone(
            wrapper.querySelector('#reference_phone'), 
            wrapper.querySelector(`.valid-reference_phone`)
        );

        if (valid) {
            invalid = valid
        }

        options.birthDate = wrapper.querySelector('#reference_birthDate').value;

        valid = validator.checkDate(
            wrapper.querySelector('#reference_birthDate'), 
            wrapper.querySelector(`.valid-reference_birthDate`)
        );

        if (valid) {
            invalid = valid
        }

        options.inn = wrapper.querySelector('#reference_inn').value;

        valid = validator.checkInn(
            wrapper.querySelector('#reference_inn'), 
            wrapper.querySelector(`.valid-reference_inn`)
        );

        if (valid) {
            invalid = valid
        }

        options.filials = {};

        wrapper.querySelectorAll('.responsible_filials').forEach(function(el, index) {
            options.filials[index] = {};

            if (index == 0) {
                options.filials[index]['filial'] = el.querySelector('#reference_filial').value;

                valid = validator.checkNotEmpty(
                    el.querySelector('#reference_filial'), 
                    el.querySelector('.valid-reference_filial')
                );

                if (valid) {
                    invalid = valid
                }

                options.filials[index]['periodFirst'] = el.querySelector('#reference_periodFirst').value;
                options.filials[index]['periodLast'] = el.querySelector('#reference_periodLast').value;
            
                if (valid) {
                    invalid = valid
                }

                var reference_responsible = '#reference_responsible';
            } else {
                options.filials[index]['filial'] = el.querySelector('#reference_filial_'+ index).value;
                options.filials[index]['periodFirst'] = document.querySelector('#reference_periodFirst_'+ index).value
                options.filials[index]['periodLast'] = document.querySelector('#reference_periodLast_'+ index).value
                
                valid = validator.checkNotEmpty(
                    el.querySelector('#reference_filial_' + index), 
                    el.querySelector('.valid-reference_filial')
                );

                if (valid) {
                    invalid = valid
                }

                var reference_responsible = '#reference_responsible_'+ index
            }

            options.filials[index]['responsible'] = el.querySelector(reference_responsible).value;
            
            if (el.querySelector(reference_responsible).value == 0) {

                options.filials[index]['fio'] = el.querySelector('#reference_patientName_'+ index).value;

                valid = validator.checkTextRu(
                    el.querySelector('#reference_patientName_'+ index), 
                    el.querySelector(`.valid-reference_patientName`)
                );

                if (valid) {
                    invalid = valid
                }

                options.filials[index]['birthDate'] = el.querySelector('#reference_patientBirthDate_'+ index).value;

                valid = validator.checkDate(
                    el.querySelector('#reference_patientBirthDate_'+ index), 
                    el.querySelector(`.valid-reference_patientBirthDate`)
                );
                
                if (valid) {
                    invalid = valid
                }

                options.filials[index]['relation'] = el.querySelector('#reference_relation_'+ index).value;
            }
        })

        options.sending = wrapper.querySelector('#reference_sending')?.value ?? '1';

        // Разрешённые варианты: 1 и 2. Всё остальное считаем "1".
        const sendingInt = parseInt(options.sending, 10);
        if (sendingInt !== 1 && sendingInt !== 2) {
            options.sending = '1';
        }

        if (options.sending == 1 || options.sending === '1') {
            options.filialSending = wrapper.querySelector('#reference_filialSending').value
            
            valid = validator.checkNotEmpty(
                wrapper.querySelector('#reference_filialSending'), 
                wrapper.querySelector('.valid-reference_filialSending')
            );

            if (valid) {
                invalid = valid
            }
        }
        
        return {'options': options, 'invalid': invalid};
    }
}
