import { Controller } from 'stimulus';

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

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

        var securityCard = this.element;
        var date = new Date();
        var lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);

        let runWebSDK = function (webSDK) {
            if (document.location.search == '?tab=allTest') {
                securityCard.querySelector('.load').innerHTML = 'Загрузка данных';

                securityTabs.querySelectorAll('a').forEach(function (el) {
                    if ('allTest' == el.dataset.allowTarget) {
                        el.classList.add('tab-item--active');
                    } else {      
                        el.classList.remove('tab-item--active');
                    } 
                });
                // allTest
                treatPlaceList(webSDK, lastDate, securityCard, 'all');
            } else {
                treatPlaceList(webSDK, lastDate, securityCard, 'all');
            }
        }.bind(this)

        var securityTabs = document.getElementById('security-tabs');
    
        if (securityTabs) {
            var tabsDecktop = securityTabs.querySelectorAll('a');

            if (tabsDecktop.length > 0) {
                tabsDecktop.forEach(function (el) {
                    el.addEventListener('click', function (evn) {
                        evn.target.classList = 'tab-item tab-item--active';
                        securityCard.querySelector('.section-wrap').innerHTML = '';
                        securityCard.querySelector('.load').innerHTML = 'Загрузка данных';

                        securityTabs.querySelectorAll('a').forEach(function (a) {
                            if (evn.target.dataset.allowTarget != a.dataset.allowTarget) {
                                a.classList.remove('tab-item--active');
                            }   
                        });
                        
                        if (evn.target.dataset.allowTarget == 'allTest') {
                            document.title = 'Результаты анализов';
                            document.getElementById('page-title').innerHTML = 'Результаты анализов'; 
                        } else {
                            document.title = 'Медицинская карта';
                            document.getElementById('page-title').innerHTML = 'Медицинская карта'; 
                        }

                        treatPlaceList(window.webSDK, lastDate, securityCard, evn.target.dataset.allowTarget);
                    });
                });
            } else {
                securityTabs.addEventListener('change', function(evn) {
                    securityCard.querySelector('.section-wrap').innerHTML = '';
                    treatPlaceList(window.webSDK, lastDate, securityCard, evn.target.value);
                });
            }
        }

        function treatPlaceList(webSDK, lastDate, securityCard, allowTarget) {
            var sectionWrap = securityCard.querySelector('.section-wrap');
            var load = securityCard.querySelector('.load');

            if (allowTarget == 'referrals') {
                webSDK.loadReferralList({
                    start: 0,
                    length: 50 
                }).then(function (refferals) {

                    if (refferals.length == 0) {
                        securityCard.querySelector('.load').innerHTML = 'Записей не найдено';
                    }

                    refferals.forEach(function (item) {
                        var row = document.createElement('div');
                        row.classList = 'row';
                        
                        var col6 = document.createElement('div');
                        col6.classList = 'col-md-6';

                        var dateTag = document.createElement('p');
                        dateTag.innerHTML = '<p><b><span class="month"></span>, <span class="date"></span></b></p><p class="refname"></p><p class="fromfname"></p>';
                        col6.append(dateTag);                
                        row.append(col6);

                        var col6 = document.createElement('div');
                        col6.classList = 'col-md-6';
                        col6.innerHTML = '<p class="refcomment"></p><p>Специалист: <br><span class="fromdname"></span></p><p class="refstatusname"></p>';
                        row.append(col6);

                        var refferalsItem = document.createElement('div');
                        refferalsItem.classList = 'block-item p-2 mt-1';
                        refferalsItem.append(row);

                        refferalsItem.classList.remove('d-none');
                        refferalsItem.querySelector('.refname').innerHTML = item.refname;
                        refferalsItem.querySelector('.refcomment').innerHTML = item.refcomment;
                        refferalsItem.querySelector('.fromfname').innerHTML = item.fromfname;
                        refferalsItem.querySelector('.fromdname').innerHTML = item.fromdname;
                        refferalsItem.querySelector('.refstatusname').innerHTML = item.refstatusname;
                        
                        var date = window.newDate(item.refdate);
                        refferalsItem.querySelector('.month').innerHTML = getWeekDay(date);
                        refferalsItem.querySelector('.date').innerHTML = window.dateFormat(date, 'd-m-Y')
                        
                        sectionWrap.append(refferalsItem);
                    });
                }).catch(function (e) {
                    helper.sendRequest({
                            data: {'error': e, method: 'loadReferralList'}
                        }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                });
            } else {
                webSDK.loadTreatPlaceList({
                    st: 20150101,
                    en: window.dateFormat(lastDate),
                    start: 0,
                    length: 100
                }).then(function (resolve) {
                    console.log("loadTreatPlaceList")
  
                    if (resolve.data.length > 0) {
                        var count = 0;
                        load.classList.remove('d-none');
                       
                        for (var i = 0; i < resolve.data.length; i++) {
                            if (allowTarget == 'allTest') {
                                if (analysis(resolve.data[i].protocolName)) {
                                    count++;
                                    sectionWrap.classList.remove('d-none');    

                                    addItem(resolve.data[i], sectionWrap, webSDK);
                                }
                            } else if (allowTarget == 'all') {
                                count = resolve.data.length
                                sectionWrap.classList.remove('d-none');    
                                
                                addItem(resolve.data[i], sectionWrap, webSDK);
                            }
                        }

                        load.classList.add('d-none');

                        if (count == 0) {
                            load.classList.remove('d-none');    
                        }

                    } else {
                        securityCard.querySelector('.load').innerHTML = 'Записей не найдено';
                        load.classList.remove('d-none');
                    }
                }).catch(function (e) {
                    helper.sendRequest({
                            data: {'error': e, method: 'loadTreatPlaceList'}
                        }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                });
            }
        }

        function analysis(protocolName) {
            const regex = /анализ/gm;
            let m;
            var result = false;

            while ((m = regex.exec(protocolName)) !== null) {
                if (m.index === regex.lastIndex) {
                    regex.lastIndex++;
                }
                
                m.some(function(match, groupIndex) {
                    result = true;
                });

            }
            
            return result;
        }

        function addItem(item, wrap, webSDK) {
          wrap.insertAdjacentHTML('beforeend', `
            <div class="col-md-12 mt-3 px-0">
              <div class="block-title">${getWeekDay(window.newDate(item.date))} ${window.dateFormat(window.newDate(item.date), 'd-m-Y')}</div>
              <div class="block-content py-3 col-md-12"> 
                <div class="row">
                  <div class="col-md-10 col-sm-12">
                    <b>${item.protocolName}</b>
                    <p class="pt-2">Специалист: <br> ${item.doctorName}</p>
                  </div>
                  <div class="col-md-2 col-sm-12">
                    <button type="button" 
                        class="card-item__btn button ${helper.isMobile() ? 'w-100' : ''}" 
                        data-protocol-id="${item.protocolId}" 
                        data-treatcode="${item.treatcode}">
                      ${helper.isMobile() ? 'Скачать' : 'Просмотр'}
                    </button>
                  </div>
                  <div class="col-12">
                    ${item.attachments.length > 0 ? `
                      <div class="card-item__doc mt-2">
                        <p>Список изображений (файлов):</p>
                        ${item.attachments.map(attachment => `
                          <div class="row">
                            <div class="col-md-8 d-none d-md-block">
                              ${attachment.attachmentName}
                            </div>

                            <div class="col-md-2 col-sm-6">
                              <button type="button" class="button ${helper.isMobile() ? 'w-100' : ''}"
                                data-attachment-type="download"
                                data-attachment-id="${attachment.attachmentId}" 
                                data-treatcode="${item.treatcode}" 
                                data-protocol-id="${item.protocolId}">
                                  Скачать
                              </button></br>
                            </div>

                            <div class="col-md-2 d-none d-md-block">
                              <button type="button" class="button ${helper.isMobile() ? 'w-100' : ''}"
                                data-attachment-type="raw"
                                data-attachment-id="${attachment.attachmentId}" 
                                data-treatcode="${item.treatcode}" 
                                data-protocol-id="${item.protocolId}">
                                  Просмотр
                              </button></br>
                            </div>
                          </div>
                        `).join('')}    
                      </div>
                    ` : ''}
                  </div>
                </div>
              </div>
            </div>
          `);
          
          const cardItem = wrap.lastElementChild;

          if (item.attachments.length > 0) {
              const attachmentLinks = cardItem.querySelectorAll('button[data-attachment-id]');
              attachmentLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const popup = document.getElementById('popup');
                    const modalBody = popup.querySelector('.modal-body');
                    modalBody.dataset.attachmentType = this.dataset.attachmentType;
                    modalBody.innerHTML = `
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Загрузка...</span>
                            </div>
                            <p class="mt-2">Загрузка файла...</p>
                        </div>
                    `;  
                    
                    webSDK.downloadTreatPlaceAttachment({
                        protocolId: this.dataset.protocolId,
                        treatcode: this.dataset.treatcode,
                        attachmentId: this.dataset.attachmentId,
                        download: this.dataset.attachmentType
                    }).then(function(blob) {
                        if (modalBody.dataset.attachmentType === 'download') {
                            return false;
                        }

                        modalBody.innerHTML = '';

                        const objectURL = URL.createObjectURL(blob.result);
                            
                        if (blob.result.type === 'application/pdf' || 
                            blob.result.type === 'application/x-pdf') {
                            
                            // Для PDF создаем iframe
                            const iframe = document.createElement('iframe');
                            iframe.src = objectURL;
                            iframe.style.width = "100%";
                            iframe.style.height = "500px";
                            iframe.style.border = "none";
                            iframe.title = "PDF документ";
                            iframe.type = 'application/pdf';
                            
                            popup.querySelector('.modal-body').appendChild(iframe);
                            
                        } else if (blob.result.type.startsWith('image/')) {
                            // Для изображений создаем img
                            const image = document.createElement('img');
                            image.src = objectURL;
                            image.style.width = "100%";
                            image.style.maxHeight = "80vh";
                            image.style.objectFit = "contain";
                            image.alt = "Изображение";
                            
                            popup.querySelector('.modal-body').appendChild(image);
                            
                        } else {
                            // Для других типов файлов - кнопка скачивания
                            const downloadLink = document.createElement('a');
                            downloadLink.href = objectURL;
                            downloadLink.download = 'document';
                            downloadLink.className = 'btn btn-primary';
                            downloadLink.textContent = 'Скачать файл';
                            downloadLink.style.margin = '20px auto';
                            downloadLink.style.display = 'block';
                            downloadLink.style.width = '200px';
                            
                            popup.querySelector('.modal-body').appendChild(downloadLink);
                            
                            // Также показываем информацию о типе файла
                            const info = document.createElement('p');
                            info.textContent = `Тип файла: ${blob.result.type}`;
                            info.style.textAlign = 'center';
                            popup.querySelector('.modal-body').appendChild(info);
                        }
                        
                        $(popup).modal('show');
                        
                        // Очистка памяти при закрытии модального окна
                        $(popup).on('hidden.bs.modal', function() {
                            URL.revokeObjectURL(objectURL);
                            $(popup).off('hidden.bs.modal');
                        });
                        
                    }).catch(function (e) {
                        console.error('Error downloading file:', e);
                        helper.sendRequest({
                          data: {'error': e, method: 'TreatPlaceAttachment'}
                        }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
                        
                        popup.querySelector('.modal-body').innerHTML = `
                            <div class="alert alert-danger">
                                <h5>Ошибка загрузки файла</h5>
                                <p>${e.message || 'Неизвестная ошибка'}</p>
                                <button class="btn btn-secondary" onclick="$(popup).modal('hide')">Закрыть</button>
                            </div>
                        `;
                        $(popup).modal('show');
                    });
                });
              });
          }
          
          const btnInfo = cardItem.querySelector('.card-item__btn');
          btnInfo.addEventListener('click', function () {
              const popup = document.getElementById('popup');
              popup.querySelector('.modal-body').innerHTML = '';
              webSDK.loadTreatPlaceView({
                  protocolId: this.dataset.protocolId,
                  treatcode: this.dataset.treatcode,
                  container: popup.querySelector('.modal-body')
              });
              
              if (!helper.isMobile()) {
                  $(popup).modal('show');
              }
          });
        }
    }

}


