Output.js

294 lines | 19.592 kB Blame History Raw Download
//  Функция выводит данные о поселении в боковую панель из JSON объекта
function PrintInfoAboutSettlement(info)
{
    function makeButton(buttonHTML, type, id) {
        if (buttonHTML === '')
            return '';
        return buttonHTML.replace(/_ID_/g, id).replace(/_TYPE_/g, type);
    }

    Collections.CurrentSettlement = new Object();
    Collections.CurrentSettlement.constInfo = new Object();
    Collections.CurrentSettlement.constInfo.Title = info.Title;
    Collections.CurrentSettlement.constInfo.URL = info.URL;
    Collections.CurrentSettlement.constInfo.Lat = info.Coordinate.Lat;
    Collections.CurrentSettlement.constInfo.Long = info.Coordinate.Long;
    Collections.CurrentSettlement.constInfo.Founder = info.Founder;
    Collections.CurrentSettlement.constInfo.hasBeginning = info.hasBeginning;
    Collections.CurrentSettlement.constInfo.Legend = info.Legend;

    Collections.CurrentSettlement.editInfo = new Array();

    document.getElementById('settlement-title').innerHTML = info.Title;
    document.getElementById('settlement-url').innerHTML = info.URL;

    var text = '<div class="sidebar-left-text-element">';
    text += makeButton(editButtonText, 'constInfo', 'editConstInfoButton');
    text += '<p>' + 'Координаты: ' + info.Coordinate.Lat + ' ' + info.Coordinate.Long + '</p>';
    if (info.Founder !== null)
        text += '<p>' + 'Основатель: ' + info.Founder + '</p>';

    if (info.Legend !== null)
    {
        //text += '<p>' + 'Легенда:</p>';
        //  тут часть текста ("показать") выделяется другим цветом
        text += '<div class="hideLine"><label for="hideLine1">Легенда: <span style="color: #32CD32">[показать]</span></label><input type="checkbox" id="hideLine1"/>';
        text += '<p class="content">' + info.Legend + '</p></div>';
    }
    if (info.hasBeginning !== null)
        text += '<p>' + 'Время основания: ' + info.hasBeginning + '</p>';
    var i = 0;
    text += '</div>'; 
    text += '<hr style="border: none; background-color: #32CD32; color: #32CD32; height: 2px;">';
    if (info.EditedSettlements !== null)
        info.EditedSettlements.forEach(function (element) {
            text += '<div class="sidebar-left-text-element">';
            text += makeButton(editButtonText, 'editInfo', 'editEditInfoButton_' + i++);
            Collections.CurrentSettlement.editInfo.push(new Object(element));

            if (element.PopulationAll !== null)
                text += '<p>' + 'Количество населения: ' + element.PopulationAll + '</p>';
            if (element.PopulationFemales !== null)
                text += '<p>' + 'Количество мужского населения: ' + element.PopulationFemales + '</p>';
            if (element.PopulationMales !== null)
                text += '<p>' + 'Количество женского населения: ' + element.PopulationMales + '</p>';
            if (element.Region !== null)
                text += '<p>' + 'Регион: ' + element.Region.Title + '</p>';
            if (element.Type !== null)
                text += '<p>' + 'Тип поселения: ' + element.Type.Title + '</p>';
            if (element.Title !== null)
                text += '<p>' + 'Название поселения: ' + element.Title + '</p>';

            text += '<p>' + 'Год: ' + element.hasBeginning.Year + '</p>';

            text += '<p>Источник: ' + element.Source.Title + '</p>';
            text += '<p>Доступ: ';
            element.Source.URLs.forEach(function (_url) {
                if (_url.includes("www.") || _url.includes("http"))
                    text += '<a href="' + _url + '" target="_blank">ссылка</a> ';
                else 
                    text += _url + ' ';
            });
            if (element.Source.Auther !== null && element.Source.Auther !== '')
                text += '<p>' + 'Автор источника: ' + element.Source.Auther + '</p>';

            text += '</div>';
        });    

    document.getElementById('sidebar-left-text').innerHTML = text;
}

function printExportCollection() {
    var text = '';
    //  т.к. используются формы (class="form-check...")
    //  то объекты в разметке получают стиль позиции relative
    //  данная позиция не корректно взаимодействует со скроллбаром и шапкой формы, которая имеет позицию sticky
    //  я не знаю как это лучше исправить
    //  предполагаю, что можно убрать классы и оставить только label и checkbox, тогда их позиции станут fixed и все станет норм
    Collections.Export.forEach(function (element) {
        text += '<div class="form-check">';//style="position: sticky;"
        text += '	<input class="form-check-input" type="checkbox" value="" id="' + element.url + '" checked onchange="checkBoxChange(this)">';
        text += '   <label class="form-check-label" for="' + element.url + '" data-toggle="tooltip" data-placement="top" title="' + element.url + '">' + element.name + '</label>';
        text += '</div>';
    });
    $("#sidebar-right-text-export")[0].innerHTML = text;
}

function printEditImportForm(what, id) {
    var element;
    if (what === 'constInfo') {
        element = Collections.CurrentSettlement[what];  
        //  вызов создания формы
        printImportAddingForm();
        //  после создания формы, записываем готовые значения в нужные поля

        $("input#import-url").val(element.URL);
        $("input#import-title").val(element.Title);
        $("input#import-lat").val(element.Lat);
        $("input#import-long").val(element.Long);
        $("input#import-founder").val(element.Founder);
        $("input#import-hasBeginning").val(element.hasBeginning);
        $("textarea#import-legend").val(element.Legend);

        importSidebarButton();
    }
    else if (what === 'editInfo') {
        importSidebarButton();
        element = Collections.CurrentSettlement.editInfo[id.split('_')[1]];
        //  вызов создания формы
        printImportEditingForm();
        //  после создания формы, записываем готовые значения в нужные поля

        $("input#import-edited-url").val(element.URL);
        $("input#import-edited-hasBeginning").val(element.hasBeginning.Year);
        $("input#import-edited-source").val(element.Source.Title);

        if (element.PopulationAll !== null)
            $("input#import-edited-populationAll").val(element.PopulationAll);
        if (element.PopulationFemales !== null)
            $("input#import-edited-populationFemale").val(element.PopulationFemales);
        if (element.PopulationMales !== null)
            $("input#import-edited-populationMale").val(element.PopulationMales);
        if (element.Region !== null) {
            //  костыль из-за того, что пытаемся выделить элемент списка, хотя список еще не был наполнен из-за асинхронности работы
            //  ставлю задержку, чтобы при первой загрузке списка выделение произошло чуть позже. при повторных нажатиях список уже загружен и работает мгновенно
            if (Collections.AllRegions.length === 0)
                setTimeout(function () { $("#import-edited-region option[value='" + element.Region.URL + "']").attr("selected", "selected"); }, 1000);
            $("#import-edited-region option[value='" + element.Region.URL + "']").attr("selected", "selected");
        }
        if (element.Type !== null) {
            if (Collections.AllSettlementTypes.length === 0)
                setTimeout(function () { $("#import-edited-type option[value='" + element.Type.URL + "']").attr("selected", "selected"); }, 1000);
            $("#import-edited-type option[value='" + element.Type.URL + "']").attr("selected", "selected");
        }
        if (element.Title !== null)
            $("input#import-edited-title").val(element.Title);       
    }
    else { console.log('printEditImportForm(' + what + ',' + id + ')'); return; }
    //importSidebarButton();
}

function printImportAddingForm() {
    //  здесь создание формы для добавления нового поселения
    //  вызывается при нажатии на кнопку "редактировать" у осн инф или при нажатии на кнопку на веб-странице (Импорт)
    
    var text = '';
    text += '<div class="form-group"><div class="form-row"><div class="col"><label for="import-url">Url</label></div><div class="col"><div class="form-check"><input class="form-check-input position-static" type="checkbox" id="checkBoxEditUrl" value="">';
    text += '</div></div></div><input type="text" class="form-control" id="import-url" placeholder="Идентификатор поселения" readonly value=""><div class="invalid-feedback">Ошибка в наименовании URL поселения.</div></div>';
    text += '<div class="form-group"><label for="import-title">Название поселения</label><input type="text" class="form-control" id="import-title" placeholder="Отображается на карте" required value=""><div class="invalid-feedback">';
    text += 'Ошибка в названии поселения.</div></div><div class="form-row"><div class="col"><label for="import-lat">Широта</label><input type="text" class="form-control" id="import-lat" placeholder="51.000000" required value="">';
    text += '<div id="lat-error" class="invalid-feedback">Неверное значение.</div></div><div class="col"><label for="import-long">Долгота</label><input type="text" class="form-control" id="import-long" placeholder="45.000000" required value="">';
    text += '<div id="long-error" class="invalid-feedback">Неверное значение.</div></div></div><div class="form-group mt-3"><label for="import-founder">Основатель поселения</label><input type="text" class="form-control" id="import-founder" placeholder="Имя или URL">';
    text += '</div><div class="form-group"><label for="import-hasBeginning">Дата основания</label><div class="input-group"><input type="text" class="form-control" id="import-hasBeginning" placeholder="Год основания"><div class="input-group-append"><span class="input-group-text">н. э.</span></div>';
    text += '<div id="hasBeginning-error" class="invalid-feedback">Не верный год.</div></div></div><div class="form-group"><label for="exampleFormControlTextarea1">История основания</label><textarea class="form-control" id="import-legend" rows="2"></textarea></div>';

    //  т.к. форма общая и submit тоже, нужно знать, какой тип поселений изменяется
    $('#import-form, #content').addClass('origin-import');
    $('#import-form, #content').removeClass('edited-import');

    //  записать html
    $("#import-form")[0].innerHTML = text;

    // чек-бокс выделения url-поля
    $('#checkBoxEditUrl').change(function () {
        $('#import-url').prop('required', ($(this)[0].checked));
        $('#import-url')[0].readOnly = !($(this)[0].checked);
    });    
}

function printImportEditingForm() {
    //  здесь создание формы для добавления нового ИЗМЕНЕННОГО поселения
    //  вызывается при нажатии на кнопку "редактировать" у измененной инф или при нажатии на кнопку на левой бок панели для добавления новой информации      

    var text = '';
    text += '<input type="text" class="form-control" id="import-edited-url" required="" hidden value="default"><div class="form-group"><label for="import-before-url">Основное поселение</label><input type="text" class="form-control" id="import-before-title"';
    text += ' placeholder="Название поселения" readonly="" value=""><input type="text" class="form-control" id="import-before-url" placeholder="Идентификатор поселения" hidden required="" value=""></div><div class="form-group">';
    text += '<label for="import-edited-hasBeginning">Дата сведений</label><div class="input-group"><input type="text" class="form-control" id="import-edited-hasBeginning" placeholder="Год относящейся информации" required=""><div class="input-group-append">';
    text += '<span class="input-group-text">н. э.</span></div><div id="edited-hasBeginning-error" class="invalid-feedback">Не верный год.</div></div></div><div class="form-group"><label for="import-edited-source">Источник сведений</label>';
    text += '<input type="text" class="form-control" id="import-edited-source" placeholder="URL или другой идентификатор" value="" required=""><div class="invalid-feedback">Ошибка в источнике сведений.</div></div><div class="form-group">';
    text += '<label for="import-edited-title">Название поселения</label><input type="text" class="form-control" id="import-edited-title" placeholder="Дополнительное название" value=""><div class="invalid-feedback">Ошибка в названии поселения.</div></div>';
    text += '<div class="form-group"><label for="import-edited-type">Тип поселения</label><select id="import-edited-type" class="form-control form-control-sm" size="3"></select><button id="btn-type-off" type="button" class="mt-2 btn btn-outline-light';
    text += ' btn-sm">Снять выделение</button></div><div class="form-group"><label for="import-edited-region">В составе административной единицы</label><select id="import-edited-region" class="form-control form-control-sm" size="3"></select><button';
    text += ' id="btn-region-off" type="button" class="mt-2 btn btn-outline-light btn-sm">Снять выделение</button></div><div class="form-group"><label for="import-edited-populationAll">Общее количество населения</label><input type="text" class="form-control" ';
    text += 'id="import-edited-populationAll" placeholder="0" value=""><div class="invalid-feedback">Неверное число.</div></div><div class="form-group"><label for="import-edited-populationFemale">Количество женского населения</label><input type="text" ';
    text += 'class="form-control" id="import-edited-populationFemale" placeholder="0" value=""><div class="invalid-feedback">Неверное число.</div></div><div class="form-group"><label for="import-edited-populationMale">Количество мужского населения</label>';
    text += '<input type="text" class="form-control" id="import-edited-populationMale" placeholder="0" value=""><div class="invalid-feedback">Неверное число.</div></div>';

    //  т.к. форма общая и submit тоже, нужно знать, какой тип поселений изменяется
    $('#import-form, #content').addClass('edited-import');
    $('#import-form, #content').removeClass('origin-import');

    $("#import-form")[0].innerHTML = text;  
    $("#import-before-url").val(Collections.CurrentSettlement.constInfo.URL);
    $("#import-before-title").val(Collections.CurrentSettlement.constInfo.Title);

    $('#btn-type-off').click(function () {
        $('#import-edited-type option').prop('selected', false);
    });

    $('#btn-region-off').click(function () {
        $('#import-edited-region option').prop('selected', false);
    });  

    function loadSelect(from, what) {
        var text = '';
        from.forEach(function (e) {
            text += '<option value="' + e.URL + '">' + e.Title + '</option>';
        });
        $('#' + what)[0].innerHTML = text;
    }

    //  нужно выполнить загрузку ВСЕХ тиов поселений за все периоды и ВСЕХ регионов
    if (Collections.AllSettlementTypes.length === 0) {
        $.when(GetAllOfType('type')).done(function (data) {
            Collections.AllSettlementTypes = data;   
            loadSelect(Collections.AllSettlementTypes, 'import-edited-type');
        });
    }
    else {
        loadSelect(Collections.AllSettlementTypes, 'import-edited-type');
    }

    if (Collections.AllRegions.length === 0) {
        $.when(GetAllOfType('region')).done(function (data) {
            Collections.AllRegions = data;
            loadSelect(Collections.AllRegions, 'import-edited-region');
        });
    }
    else {
        loadSelect(Collections.AllRegions, 'import-edited-region');
    }
}

function deleteElement(what, id) {
    var element;
    if (what === 'constInfo') {
        element = Collections.CurrentSettlement[what];
        $('#modal-delete-text').html('Подтвердите удаление основной информации [<a href="' + element.URL + '" target="_blank">url</a>]' + ' об основном поселении "' + element.Title + '". <h6 class="bg-warning text-dark">Вы уверены?</h6>');
        $('#buttonConfirmDelete').data('type', what);
        $('#buttonConfirmDelete').data('url', element.URL);
        $('#buttonConfirmDelete').data('title', element.Title);
        $('#confirmDeleteModal').modal();
    }
    else if (what === 'editInfo') {
        element = Collections.CurrentSettlement.editInfo[id.split('_')[1]];        
        var beforeName = Collections.AllGeoObjects.search('options.URL = "' + element.before + '"').get(0).options.get('Name');
        $('#modal-delete-text').html('Подтвердите удаление дополнительной информации [<a href="' + element.URL + '" target="_blank">url</a>]' + ' об основном поселении "' + beforeName + '". <h6 class="bg-warning text-dark">Вы уверены?</h6>');
        $('#buttonConfirmDelete').data('type', what);
        $('#buttonConfirmDelete').data('url', element.URL);
        $('#buttonConfirmDelete').data('title', beforeName);
        $('#confirmDeleteModal').modal();
    }
    else { console.log('printEditImportForm(' + what + ',' + id + ')'); return; }
}

function startDelete(sender) {
    var url = $(sender).data('url');
    var type = $(sender).data('type');
    var title = $(sender).data('title');

    var text = '';
    if (type === 'constInfo') {
        text = 'Основное поселение [<a href="' + url + '" target="_blank">url</a>] "';
    }
    else {
        text = 'Дополнительная информация [<a href="' + url + '" target="_blank">url</a>] об основном поселении "';
    }
    text += title + '" удалено ';

    $.when(DeleteSettlement(type, url)).done(function (data) {
        if (new RegExp("^Success", "i").test(data)) {
            text += '<span class="bg-success text-dark">успешно</span>.';
        }
        else {
            var error = data.split('|')[1];
            text += '<span class="bg-danger text-white">с ошибкой</span>.<p class="bg-warning text-dark">' + error + '</p>';
        }
        $('#modal-result-text').html(text);
        $('#resultDeleteModal').modal();
    });
    
    
}