Есть ли в этом коде утечки памяти? <script>
import {debounce} from 'lodash';
import Layout from '@/Pages/Iview/Layout'
import Checklist from "@/Pages/Iview/Application/Checklist"
import Remarks from '@/Pages/Iview/Application/Remarks'
import OfferVacancy from "@/Pages/Iview/Application/OfferVacancy";
import DeleteApplication from "@/Pages/Iview/Application/DeleteApplication";

import ServiceCalculation from '@/Pages/Iview/Application/ServiceCalculation'
import ProposeToVessel from '@/Pages/Iview/Application/ProposeToVessel'
import Layouts from "@/Pages/Iview/Application/Layouts";
import ChangeStatus from "@/Pages/Iview/Application/ChangeStatus";
import Files from '@/Pages/Iview/Application/Tabs/Files'
import Bank from '@/Pages/Iview/Application/Tabs/Bank'
import AvatarCropper from 'vue-avatar-cropper'
import {directive as onClickaway} from 'vue-clickaway'
import EditLink from "./EditLink";
import LogHistory from "./LogHistory";
import JoiningDate from "./JoiningDate";
import JoiningPort from "./JoiningPort";
import ModelFiles from '@/Pages/Iview/Helpers/ModelFiles'
import SeafarerTodo from "../Todo/SeafarerTodo";
import FilesForDocument from "@/Pages/Iview/Application/Tabs/FilesForDocument.vue";
import EditVessel from "@/Pages/Iview/Application/EditVessel";

import JSEncrypt from 'jsencrypt';
// import Echo from 'laravel-echo'

    export default {
        name: "Index",
        components: {
            EditVessel,
            DeleteApplication,
            Checklist,
            FilesForDocument,
            ModelFiles,
            JoiningDate,
            JoiningPort,
            EditLink,
            LogHistory,
            offerVacancy:OfferVacancy,
            ChangeStatus:ChangeStatus,
            avatar:AvatarCropper,
            Remarks:Remarks,
            Propose:ProposeToVessel,
            Service:ServiceCalculation,
            Files:Files,
            bank:Bank,
            SeafarerTodo,
            Layouts
        },
        props: [
            'remarks',
            'bank_accounts',
            'seafarer_',
            'documents_',
            'experience_',
            'ranks',
            'countries',
            'nationalities',
            'ranks_nc',
            'vessel_types_nc',
            'vessel_types',
            'vessel_engines',
            'certificates_categories',
            'documents_category',
            'table_th_widths',
            'vessel_list_',
        ],
        data() {
            return {
                deleteApplicationTrigger:false,
                editMainData: false,
                loadingNewVessel:false,
                hasError: false,
                ws: null,
                pingInterval: null,
                reconnectTimeoutId: null,
                message: '',
                isComponentAlive: true, // флаг состояния компонента
                echo: null,
                debounceTimeout: null,
                disabled:false,
                active_tab: window.activeTab,
                tableThWidth:this.table_th_widths,
                onlyOneTime:null,
                showCropper:false,
                maritals: [],
                seafarer:this.seafarer_,
                schools: [],
                genders: [],
                englishLevel:[],
                switchSeafarerEditable:this.seafarer_.editable_status === 1,
                avatarLoading:false,
                userAvatar: undefined,
                condition:false,
                loading:false,
                vessel_list:this.vessel_list_,
                documents: this.documents_,
                experience: this.experience_,
                vessel_editor: null,
                document_editor: null,
                selectedSeafarers:null,
                showBack:true,
                showForward:true,
                tab1: (h) => {
                return h('strong',this.__('Main') )
                },
                tab2: (h) => {
                    return h('strong',this.__('Sea service') )
                },
                tab3: (h) => {
                    return h('strong',this.__('Documents') )
                },
                tab4: (h) => {
                    return h('strong',this.__('Files') )
                },
                tab5: (h) => {
                    return h('strong',this.__('Banking') )
                },
                tab6: (h) => {
                    return h('strong',this.__('Performance') )
                },


                options1: {
                    shortcuts: [
                        {
                            text: 'Today',
                            value () {
                                return new Date();
                            },
                            onClick: (picker) => {
                               // this.$Message.info('Click today');
                            }
                        },
                        {
                            text: 'Yesterday',
                            value () {
                                const date = new Date();
                                date.setTime(date.getTime() - 3600 * 1000 * 24);
                                return date;
                            }
                        }
                    ]
                }

            }
        },
        // watch: {
        //     experience: function (val) {
        //         console.log(1)
        //         let table = document.getElementById('expT');
        //         this.tableResize(table);
        //     },
        // },
        remember: {
            data: ['seafarer','documents','experience','vessel_list','bank_accounts'],
        },

        computed: {

            applicationFilesCount() {
                return (doc) => {
                    if (doc && doc.application_files) {
                        return doc.application_files.length;
                    }
                    return '-';
                };
            },

            debouncedGoToSeafarer() {
                return this.debounce(this.goToSeafarer);
            },

            headers: function() {
                let xsrf = this.getCookie('XSRF-TOKEN');
                return {'X-XSRF-TOKEN':xsrf,'X-Requested-With':'XMLHttpRequest'}
            },
            getAge: function() {
                    let dob = moment_(this.seafarer.dob, "DD-MM-YYYY");
                    return dob.diff(moment_(), 'years')*(-1);
            },
            getEngine:function() {
                return this.vessel_engines.reduce((acc,item) => {
                    acc[item.id] = item.text;
                    return acc;
                },{});
            },
            getTypes:function() {
                return this.vessel_types_nc.reduce((acc,item) => {
                    acc[item.id] = item.text;
                    return acc;
                },{});
            },
            getRank:function() {
                return this.ranks_nc.reduce((acc,item) => {
                    acc[item.id] = item.text;
                    return acc;
                },{});
            },
            getCountries:function() {
                return this.countries.reduce((acc,item) => {
                    acc[item.id] = item.alpha_3.toUpperCase();
                    return acc;
                },{});
            },
            getNationalities:function() {
                return this.nationalities.reduce((acc,item) => {
                    acc[item.id] = item.code.toUpperCase();
                    return acc;
                },{});
            },

            getGender:function() {
                return this.genders.reduce((acc,item) => {
                    acc[item.id] = item.text;
                    return acc;
                },{});
            },
            getEnglish:function() {
                return this.englishLevel.reduce((acc,item) => {
                    acc[item.id] = item.text;
                    return acc;
                },{});
            },


            getSchool:function() {
                return this.schools.reduce((acc,item) => {
                    acc[item.id] = item.text;
                    return acc;
                },{});
            },
            getMarital:function() {
                return this.maritals.reduce((acc,item) => {
                    acc[item.id] = item.text;
                    return acc;
                },{});
            },
            isExpiredDocument:function() {
                return this.documents.reduce((acc,item) => {
                    if(item.till){
                        if(moment_(item.till, "DD-MM-YYYY").isBefore(moment_().add(8,'months'))){
                            acc[item.id] = 'orange';
                        }
                        if(moment_(item.till, "DD-MM-YYYY").isBefore(moment_())){
                            acc[item.id] = 'red';
                        }
                    }
                    return acc;
                },{});
            },
            dateDiff: function() {
                return this.experience.reduce((acc, item) => {
                    if (item.from && item.till) {
                        const startDate = moment_(item.from, 'DD-MM-YYYY');
                        const endDate = moment_(item.till, 'DD-MM-YYYY');
                        const duration = moment_.duration(endDate.diff(startDate));
                        const months = duration.months() + duration.years() * 12;
                        acc[item.id] = `${months}/${duration.days()}`;
                    } else {
                        acc[item.id] = '';
                    }
                    return acc;
                }, {});
            },

            // геттер вычисляемого значения
            reversedMessage: function () {
                if (this.switchSeafarerEditable) {
                    return this.__('Seaman can edit')
                } else {
                    return this.__('Seaman cant edit')
                }
            },
            onBoardTill: function () {
                    function getTimePeriod(i) {
                        let t;
                        switch (i) {
                            case 1:
                                t = 'd';
                                break;
                            case 2:
                                t = 'M';
                                break;
                            case 3:
                                t = 'w';
                                break;
                            case 4:
                                t = 'y';
                                break;
                        }
                        return t;
                    }

                    let from_ = moment_(this.vessel_list.contract_start_date,'YYYY-MM-DD');
                    let duration = this.vessel_list.contract_duration;
                    let duration_option = getTimePeriod(this.vessel_list.time_period_id);
                    let contractLength = from_.add(duration, duration_option);
                    if(this.vessel_list.contract_extension) {
                        let extension_option = getTimePeriod(this.vessel_list.time_period_id_extension);
                        contractLength = contractLength.add(this.vessel_list.contract_extension,extension_option);
                    }
                    return contractLength.format('DD-MM-YYYY');
            }

            },
        created() {
            this.connectWebSocket();
        },

        mounted() {


            this.documents_category.forEach(dc => this.$set(dc, 'loading', false));
            this.$root.$on('refreshSeafarerDocuments', this.loadDocuments_)
            this.mouseLeaveHandler = event => {
                const activeElement = document.activeElement;
                if (activeElement && activeElement.tagName === 'INPUT') {
                    // Создаем событие change
                    var e = new Event('change', {
                        'bubbles': true, // Позволяет событию всплывать вверх по DOM
                        'cancelable': true // Позволяет отменить событие
                    });
                    // Отправляем событие на активный элемент
                    activeElement.dispatchEvent(e);
                }
            };
            document.body.addEventListener('mouseleave', this.mouseLeaveHandler);

            this.loadStaticData();
            if(this.seafarer.avatar){
                this.userAvatar = `/storage/${this.$page.env}/seaman/${this.seafarer.avatar}`
            } else{
                this.userAvatar ='/img/user_no_pic.jpg'
            }
            let table = document.getElementById('expT');
                this.tableResize(table);
            this.selectedSeafarers = JSON.parse(sessionStorage.getItem('seafarers_selected_ids'));
            if(this.selectedSeafarers && this.selectedSeafarers.length > 1) {
                if(this.selectedSeafarers.indexOf(this.seafarer.id) === 0){
                    this.showBack = false;
                    this.showForward = true;
                }
                if(this.selectedSeafarers.indexOf(this.seafarer.id) === this.selectedSeafarers.length - 1){
                    this.showBack = true;
                    this.showForward = false;
                }
            } else {
                this.showBack = false;
                this.showForward = false;
            }
        },

        beforeDestroy() {
            this.userAvatar = undefined;
            this.isComponentAlive = false; // обновляем флаг при уничтожении компонента
            document.body.removeEventListener('mouseleave', this.mouseLeaveHandler)
            this.$root.$off("refreshSeafarerDocuments",this.loadDocuments_);


            this.cleanup();
            if (this.reconnectTimeoutId) {
                clearTimeout(this.reconnectTimeoutId); // Отменить планируемое переподключение
            }
            if (this.$refs.editVessel) {
                this.$refs.editVessel = null;
            }

        },
        directives: {
            onClickaway: onClickaway,
        },

        methods: {
            saveExperience (data) {
                axios.post(this.route('save_experience').url(), {
                    experience: data
                }).then(response => {
                    this.loadExperience(this.seafarer.id);

                }).catch(error => {
                    error.response.data && this.showError(error)
                })
            },

            deleteApplicationShow () {
                this.deleteApplicationTrigger = !this.deleteApplicationTrigger;
            },

            reloadSeafarerData() {
                axios.post(this.route('reload_application_data').url(), {
                    application: this.seafarer.id
                }).then(response => {
                    this.seafarer = response.data.seafarer;
                    this.experience = response.data.experience;
                    this.documents = response.data.documents;
                    this.vessel_list = response.data.vessel_list;
                }).catch(error => {
                    error.response.data && this.showError(error)
                })
            },
            mainDataEditSwitch() {
                this.editMainData = this.editMainData === false;
            },


            getTime(val) {
                if(val>0) {
                    return  this.convertDateFormat(val.toLocaleDateString('en-US'))
                } else {
                    return this.convertDateFormat(val);
                }
            },
            convertDateFormat(dateString) {
                // Разбить исходную строку по символу '/'
                const parts = dateString.split('/');

                // Проверить, достаточно ли частей для даты
                if (parts.length === 3) {
                    const [month, day, year] = parts;

                    // Формировать новую строку в формате DD-MM-YYYY
                    // Убедиться, что месяц и день имеют ведущий ноль, если они состоят из одной цифры
                    return `${day.padStart(2, '0')}-${month.padStart(2, '0')}-${year}`;
                } else {
                    // Возвращать исходную строку, если формат не соответствует ожидаемому
                    return dateString;
                }
            },


            handleImageError(event) {
                if (!this.hasError) {
                    this.hasError = true;
                    event.target.src = '/img/user_no_pic.png';
                }
            },

            createWsData(message) {
                return {
                    channel: this.$page.env + '-' + this.seafarer.id,
                    msg: `Пользователь ${this.$page.auth.user.name} ${message}`,
                    user: this.$page.auth.user.id
                };
            },
            sendWsData(message) {
                const data = this.createWsData(message);
                if (this.ws) {
                    this.ws.send(JSON.stringify(data));
                }
            },

            connectWebSocket() {
                const encrypt = new JSEncrypt();
                encrypt.setPublicKey(`-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAzDVwPSTXVEjHshnQawppITeXfUqc1VpwFXn25fCHjWgJ8xodx87l
awjQaZ25TGOaVLeCQydhzz9UabM7cwMBLHGOcqCuNRLf3n856bVyeobC5Ikk7h2Q
BuMN6pYta4qOjOD22IfKt3gBD1Ft2lplAVh7mVcQNkfMo/GZoBAnNYUXZG1ke+d1
MgMFt+nyzNYlhg0N+XPs51owF7mNbYmRp998jGdvWQbF+hzqmDutCJqOU5+k6/1z
0aYYEPVRFTj3HYduXbCXbXU8yZXbr5BbYAxiuRR3EcOKctZI03/cjXWJej/Bfeyk
wkbqlT6CZL8dbyA4RJFLJ09CfxZx+rzB5wIDAQAB
-----END RSA PUBLIC KEY-----`); // Установите ваш публичный ключ

                const key = this.seafarer.id.toString()+this.$page.auth.user.id.toString();
                const encrypted = encrypt.encrypt(key); // Шифрование данных
                const encodedEncryptedData = encodeURIComponent(encrypted);

                const wsUrl = `wss://ws.crewadmin.ru?profile_id=${this.$page.env+'-'+this.seafarer.id}&seafarer_id=${this.seafarer.id}&user_id=${this.$page.auth.user.id}&user_token=${encodedEncryptedData}`;
                // Подключение к WebSocket серверу с параметром в URL
                this.ws = new WebSocket(wsUrl);
                // Обработчик события при открытии соединения
                this.ws.onopen = () => {
                    this.setupPing();
                };
                this.ws.onmessage = (event) => {
                    try {
                        // Декодирование JSON строки в объект JavaScript
                        const messageData = JSON.parse(event.data);
                        // Проверка наличия необходимых полей в сообщении
                        if (messageData.message && messageData.user) {
                          if(Number(messageData.user) !== Number(this.$page.auth.user.id)) {
                              const content = messageData.message;
                              this.$Message.info({
                                  content: content,
                                  duration: 10,
                                  closable: true
                              });
                          }
                        }
                    } catch (e) {
                       // console.error("Ошибка при обработке сообщения: ", e);
                    }
                };

                // Обработчик события при закрытии соединения
                this.ws.onclose = (event) => {
                  // console.log('WebSocket соединение закрыто', event);
                    if (this.isComponentAlive) {
                    this.reconnectTimeoutId = setTimeout(() => {
                        this.connectWebSocket();
                    }, 1000);
                }
                }

                // Обработчик события при ошибке соединения
                this.ws.onerror = (error) => {
                   // console.error('WebSocket ошибка:', error);
                };
            },

            setupPing() {
                this.pingInterval = setInterval(() => {
                    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                        this.ws.send(JSON.stringify({ type: 'ping' }));
                    }
                }, 10000);
            },
            cleanup() {
                if (this.pingInterval) {
                    clearInterval(this.pingInterval);
                    this.pingInterval = null;
                }
                if (this.ws) {
                    this.ws.close();
                    this.ws = null;
                }
            },
            handleBeforeUnload(event) {
                event.preventDefault();
            },
            ttClose () {
                this.disabled = true;
               // alert(1);
            },
            deleteOtherRank() {
                this.$Modal.confirm({
                    title: 'Delete other rank',
                    loading: true,
                    content: 'Want to delete?',
                    onOk: () => {
                        this.seafarer.other_rank_id = null;
                        this.$Modal.remove();
                    },
                    onCancel: () => {}
                });
            },
            loadStaticData () {
                this.maritals = [{ id: 1, text: 'married' },{ id: 2, text: 'single' },{ id: 3, text: 'divorced' }];
                this.schools = [{ id: 1, text: 'higher education' },{ id: 2, text: 'secondary education' }];
                this.genders = [{ id: 1, text: 'male' },{ id: 2, text: 'female' }];
                this.englishLevel = [
                    {id:1,text:'Beginner'},
                    {id:2,text:'Elementary'},
                    {id:3,text:'Lower Intermediate'},
                    {id:4,text:'Intermediate'},
                    {id:5,text:'Upper Intermediate'},
                    {id:6,text:'Advanced'}
                ]
            },



            nextSeafarer() {
                let i = this.selectedSeafarers.indexOf(this.seafarer.id);
                this.goToSeafarer(this.selectedSeafarers[i+1]);
                //this.debouncedGoToSeafarer(this.selectedSeafarers[i+1]);
            },



            debounce(func, delay = 100) {
                return (...args) => {
                    clearTimeout(this.debounceTimeout);
                    this.debounceTimeout = setTimeout(() => {
                        func(...args);
                    }, delay);
                };
            },

            previousSeafarer() {
                let i = this.selectedSeafarers.indexOf(this.seafarer.id);
                //this.debouncedGoToSeafarer(this.selectedSeafarers[i-1]);
                this.goToSeafarer(this.selectedSeafarers[i-1]);
            },
            goToSeafarer(id){
                this.$inertia.get(this.route('show_one_application'), {application: id})
            },
            refreshApplicationStatus (e) {
                if(e.vessel_list){
                    this.vessel_list = e.vessel_list;
                }
                if(e.seafarer){
                    this.seafarer.status = e.seafarer;
                }
            },
            goToVessel(id) {
                this.$inertia.get(this.route('show_one_vessel'), {vessel: id})
            },
            changeSeafarerEditableStatus () {
                let audio = new Audio('sound/mixkit-lighter-wheel-spin-2641.wav');
                audio.play();
                let value = null;
                if(this.switchSeafarerEditable) {
                    value = 1
                }
                this.applicationSetValue(value,this.seafarer.id,'editable_status');
            },
            focusOnInput (event) {
                if(!this.onlyOneTime) {
                    event.target.focus();
                    this.onlyOneTime = true;
                }
            },
            hideDocumentEdit(){
                this.document_editor = null;
            },
            hideEdit() {
                this.vessel_editor = null;
            },
            alt (vessel_id) {
                if(this.vessel_editor !== vessel_id) {
                    this.vessel_editor = vessel_id;
                    this.onlyOneTime = null;
                }
            },
            editDocumentClickAction (document_id) {
                this.document_editor = document_id;
                this.onlyOneTime = null;
            },
            setTabActive(value) {
                window.activeTab  = value;
            },

            handleUploaded(resp) {
                this.userAvatar = '/storage/'+this.$page.env+'/seaman/'+resp;
                this.avatarLoading = false;
            },
            handleUploading(form, xhr) {
                this.avatarLoading = true;
               // form.append("_token", document.querySelector('meta[name="csrf-token"]').getAttribute('content'));
                form.append("seaman_id", this.seafarer.id);

            },
            handlerError(message, type, xhr) {

            },

            wsNotificationStatusUpdated() {
                this.sendWsData('редактирует анкету и обновил(а) статус моряка.');
            },

            applicationSetValue(value,application_id,column) {

                axios.post(this.route('application_update_data').url(), {
                    application_id: application_id,
                    column: column,
                    data: value
                }).then(response => {

                    this.sendWsData('редактирует общую информацию анкеты');

                }).catch(error => {
                    error.response.data && this.showError(error)
                })
            },

            experienceSetValue: debounce(function(value,experience,column) {


                    // if(column === 'till') {
                    //     setTimeout(() => {
                    //         this.experience.sort(function(a,b){
                    //             return moment_(b.till,'DD-MM-YYYY') - moment_(a.till,'DD-MM-YYYY');
                    //         });
                    //     }, 1000);
                    // }
                    // if(experience.vessel_list_id !== null && experience.vessel_list_id !== undefined) {
                    //     this.$Modal.confirm({
                    //         title: this.__('Confirmation'),
                    //         content: this.__('Do you really want to change Company service records?'),
                    //         okText:this.__('Save'),
                    //         cancelText:this.__('Cancel'),
                    //         onOk: () => {
                    //             axios.post(this.route('experience_set_vessel').url(), {
                    //                 experience_id: experience.id,
                    //                 column: column,
                    //                 data: value
                    //             }).catch(error => {
                    //                 error.response.data && this.showError(error)
                    //                 this.loadExperience(this.seafarer.id);
                    //             })
                    //         },
                    //         onCancel: () => {
                    //             this.loadExperience(this.seafarer.id);
                    //         }
                    //     });
                    // }
                    // else {

                    axios.post(this.route('experience_set_vessel').url(), {
                        experience_id: experience.id,
                        column: column,
                        data: value
                    }).then(response => {
                        this.sendWsData('редактирует опыт работы');
                    }).catch(error => {
                        error.response.data && this.showError(error)
                      /// this.loadExperience(this.seafarer.id);
                    })

               // }


            }, 100),

            documentSetValue(value,doc_id,column,category_id) {
                axios.post(this.route('documents_set_document').url(), {
                    application_id: this.seafarer.id,
                    doc_id: doc_id,
                    column: column,
                    data: value
                }).then(response => {
                    if (category_id) {
                        this.updateDocumentText(doc_id, category_id, value);
                        this.$refs.checklistComponent.getCertificates();
                    }
                    this.sendWsData('редактирует документы');
                }).catch(error => {
                    error.response.data && this.showError(error)
                })
            },
            updateDocumentText(doc_id, category_id, value) {
                // Find the document by its ID
                let document = this.documents.find(x => x.id === doc_id);

                if (document) {
                    // Find the corresponding category and its child based on the given IDs
                    let category = this.documents_category.find(x => x.id === category_id);
                    let child = category && category.children.find(x => x.id === value);

                    if (child) {
                        document.certificate.text = child.text;
                    }
                }
            },


            selectVesselAction(value, vessel_id, vessel_name, vessel) {
                if (value === 'close_edit') {
                    this.vessel_editor = null;
                }
                if (value === 'delete') {
                    this.seamanExperienceDelete(vessel_id, vessel_name);
                }
                if (value === 'copy') {
                    this.seamanExperienceCopy(vessel_id);
                }
                if (value === 'edit') {
                    this.$refs.editVessel.fetchVesselData(vessel);
                }

            },
            selectDocumentAction(value,document_id) {
                if (value === 'edit') {
                    this.document_editor = document_id;
                }
                if (value === 'close_edit') {
                    this.document_editor = null;
                }
                if (value === 'delete') {
                    this.seamanDocumentDelete(document_id);
                }
            },
            seamanDocumentAddNew(category_id, seafarer_id, index) {
                this.documents_category[index].loading = true;
                axios.post(this.route('documents_add_document').url(), {
                    application_id: seafarer_id,
                    category_id: category_id
                }).then(response => {
                    let document = response.data;
                    document.application_files = []
                    this.documents.unshift(document);
                    this.document_editor = document.id;
                    this.sendWsData('добавил документ');
                }).catch(error => {
                    error.response.data && this.showError(error)
                }).finally(()=>{
                    this.documents_category[index].loading = false;
                })
            },
            seamanExperienceAddNew(application_id) {
                this.loadingNewVessel = true;
                axios.post(this.route('experience_add_vessel').url(), {application_id: application_id}).then(response => {
                    this.experience.unshift(response.data);
                    this.sendWsData('добавил опыт работы');
                  //  this.vessel_editor = response.data.id;
                }).catch(error => {
                    error.response.data && this.showError(error);
                }).finally(()=>{
                    this.loadingNewVessel = false;
                })
            },
            seamanExperienceDelete(experience_id, vessel_name) {
                this.$Modal.confirm({
                    title: 'Delete vessel',
                    loading: true,
                    content: 'Want to delete m/v '+vessel_name+'?',
                    onOk: () => {
                        axios.post(this.route('experience_delete_vessel').url(), {experience_id: experience_id}).then(() => {
                            this.experience = this.experience.filter(function (obj) {
                                return obj.id !== experience_id;
                            });
                            this.$Modal.remove();
                            this.sendWsData('удалил опыт работы');

                        }).catch(error => {
                            this.$Modal.remove();
                            error.response.data && this.showError(error)
                        })
                    },
                    onCancel: () => {
                    }
                });
            },
            seamanDocumentDelete(certificate_id) {
                this.$Modal.confirm({
                    title: 'Delete document',
                    loading: true,
                    content: 'Want to delete?',
                    onOk: () => {
                        axios.post(this.route('documents_delete_certificate').url(), {certificate_id: certificate_id}).then(() => {
                            this.documents = this.documents.filter(function (obj) {
                                return obj.id !== certificate_id;
                            });
                            this.$Modal.remove();
                            this.$root.$emit('refreshSeafarerFiles');
                            this.$refs.checklistComponent.getCertificates();
                            this.sendWsData('удалил документ');

                        }).catch(error => {
                            error.response.data && this.showError(error)
                        })
                    },
                    onCancel: () => {}
                });
            },
            seamanExperienceCopy(experience_id) {
                axios.post(this.route('experience_copy_vessel').url(), {experience_id: experience_id}).then(response => {
                    this.experience.push(response.data);
                    this.sendWsData('копирует опыт работы');

                }).catch(error => {
                    error.response.data && this.showError(error)
                })
            },
            loadExperience(seafarer_id) {
                axios.post(this.route('load_seafarer_experience').url(), {application_id: seafarer_id}).then(response => {
                    this.experience = response.data;
                })
            },

            loadDocuments_() {
                axios.post(this.route('load_seafarer_documents').url(), {application_id: this.seafarer.id}).then(response => {
                    this.documents = response.data;
                })
            },

            tableResize(table){
                let row = table.getElementsByTagName('tr')[0],
                    cols = row ? row.children : undefined;
                if (!cols) return;
                table.style.overflow = 'hidden';
                let tableHeight = row.offsetHeight;

                for (let i=0;i<cols.length-2;i++){
                    let div = createDiv(tableHeight);
                    cols[i].appendChild(div);
                    cols[i].style.position = 'relative';
                    setListeners(div,this);
                }

                function setListeners(div,this_){
                    let pageX,curCol,nxtCol,curColWidth,nxtColWidth,cW,diffX;
                    div.addEventListener('mousedown', function (e) {
                        curCol = e.target.parentElement;
                        nxtCol = curCol.nextElementSibling;
                        pageX = e.pageX;

                        let padding = paddingDiff(curCol);
                        curColWidth = curCol.offsetWidth - padding;
                        if (nxtCol)
                            nxtColWidth = nxtCol.offsetWidth - padding;
                    });

                    div.addEventListener('mouseover', function (e) {
                        e.target.style.borderRight = '3px solid #747474';

                    })

                    div.addEventListener('mouseout', function (e) {
                        e.target.style.borderRight = '';

                    })

                    table.childNodes[0].addEventListener('mousemove', function (e) {
                        if (curCol) {

                             diffX = e.pageX - pageX;

                            if (nxtCol)
                                nxtCol.style.width = (nxtColWidth - (diffX))+'px';
                            curCol.style.width = (curColWidth + diffX)+'px';
                            cW = curColWidth + diffX;

                            if((nxtColWidth - (diffX)) <= parseInt(nxtCol.style.minWidth, 10))
                            {
                                pageX = undefined;
                            }
                        }
                    });

                    table.childNodes[0].addEventListener('mouseup',  function (e) {
                        let atw = {};
                        if(cW) {
                            let th = row.getElementsByTagName('th');
                            for(let k=0;k<th.length;k++) {
                                atw[th[k].dataset.cnm]=th[k].offsetWidth;
                            }
                            axios.post(this_.route('set_application_table_widths').url(), {application_table_width: atw}).then((response) => {})
                            this_.tableThWidth = atw;
                        }
                        curCol = undefined;
                        nxtCol = undefined;
                        pageX = undefined;
                        nxtColWidth = undefined;
                        curColWidth = undefined;
                        cW = undefined;
                    });
                }

                function createDiv(height){
                    let div = document.createElement('div');
                    div.style.top = 0;
                    div.style.right = 0;
                    div.style.width = '9px';
                    div.style.position = 'absolute';
                    div.style.cursor = 'col-resize';
                    div.style.userSelect = 'none';
                    div.style.height = height + 'px';
                    return div;
                }
                // function paddingDiff(col){
                //     if (getStyleVal(col,'box-sizing') === 'border-box'){
                //         return 0;
                //     }
                //     let padLeft = getStyleVal(col,'padding-left');
                //     let padRight = getStyleVal(col,'padding-right');
                //     return (parseInt(padLeft) + parseInt(padRight));
                // }

                function paddingDiff(col){
                    if (getStyleVal(col,'box-sizing') === 'border-box'){
                        return 0;
                    }
                    let paddingLeft = getStyleVal(col,'padding-left');
                    let paddingRight = getStyleVal(col,'padding-right');
                    return (parseInt(paddingLeft) + parseInt(paddingRight));
                }


                function getStyleVal(elm,css){
                    return (window.getComputedStyle(elm, null).getPropertyValue(css))
                }
            },
        },

        layout: [Layout],
    }
</script>