$(document).ready(function(){

    let history = $('.history .step'); // блок с данными истории
    let table = $('.history-wrap'); // блок построенной таблицы
    let currentStepIndex = 0;

    let historyBtnAll = $('.history-all');
    let historyBtnSteps = $('.history-steps');

    historyBtnAll.click(function () {
        historyBtnAll.removeClass('btn-gray').addClass('btn-green');
        historyBtnSteps.removeClass('btn-green').addClass('btn-gray');
        buildTableAll();
    });

    historyBtnSteps.click(function () {
        historyBtnSteps.removeClass('btn-gray').addClass('btn-green');
        historyBtnAll.removeClass('btn-green').addClass('btn-gray');
        buildTableSteps(currentStepIndex);
    });

    // построение таблицы с указанным шагом ревизии
    function buildTableSteps(step) {

        let html = ''; // обнуление html для таблицы
        let currentStep = history.eq(step).find('.step-single');
        let leftDisable = (step === 0) ? 'disable' : ''; // класс для неактивной кнопки влево
        let rightDisable = (step === history.length - 1) ? 'disable' : ''; // класс для неактивной кнопки вправо

        // построение шапки таблицы
        html +='<div class="hw-inner">' +
            '<div class="hw-header">' +
            '<div class="hw-left ' + leftDisable + '"></div>' +
            '<div class="hw-indent"></div>' +
            '<div class="hw-date">';

        // получение даты ревизии
        let firstStepDate = currentStep.eq(0).find('.value').text();

        // построение тела таблицы
        html += firstStepDate + '</div>' +
            '<div class="empty"></div>' +
            '<div class="hw-right ' + rightDisable + '"></div>' +
            '</div>' +
            '<div class="hw-body">'

        // построение каждого параметра ревизии
        currentStep.each(function (index) {
            // первое поле пропускается, т.к. оно в шапке (дата ревизии)
            if(index !== 0) {
                let field = $(this).find('.field').html(); // текст названия поля
                let value = $(this).find('.value').html(); // текст значения поля
                // если текущая ревизия не первая и значение текущей ревизии отличается от предыдущей
                // добавляется класс с подсветкой фона
                let updatedField = '';
                if(step !== 0 && currentStep.eq(index).find('.value').html() !== history.eq(step - 1).find('.step-single').eq(index).find('.value').html()) updatedField = 'updated-field';
                if(value.length === 0) value = '-'; // если поле пустое - то писать прочерк
                html += '<div class="hw-single ' + updatedField + '">' +
                    '<div class="hw-field">' + field + '</div>' +
                    '<div class="hw-value">' + value + '</div>' +
                    '</div>'
            }
        });

        // конец тела таблицы
        html += '</div></div>';

        // применение построенного html
        table.html(html);

        // добавление клика на левую стрелку, если это не первая ревизия
        if(step !== 0) {
            $('.hw-left').click(function () {
                buildTableSteps(step - 1);
            });
        }

        // добавление клика на правую стрелку, если это не последняя ревизия
        if (step !== history.length - 1) {
            $('.hw-right').click(function () {
                buildTableSteps(step + 1);
            });
        }

    }

    // построение таблицы со всеми ревизиями
    function buildTableAll() {

        let html = ''; // обнуление html для таблицы
        html +='<div class="hw-inner hw-inner-all">'

        history.each(function (indexMain) {

            let revisionDate = history.eq(indexMain).find('.step-single').eq(0).find('.value').text();

            console.log(revisionDate)

            // построение части с датой ревизии
            html += '<div class="hw-header">' +
                '<div class="hw-date">' + revisionDate + '</div>' +
                '</div>' +
                '<div class="hw-body">';

            // построение остальной части ревизии
            history.eq(indexMain).find('.step-single').each(function (index) {
                // первое поле пропускается, т.к. оно в шапке (дата ревизии)
                if(index !== 0) {
                    let field = $(this).find('.field').html(); // текст названия поля
                    let value = $(this).find('.value').html(); // текст значения поля
                    // если текущая ревизия не первая и значение текущей ревизии отличается от предыдущей
                    // добавляется класс с подсветкой фона
                    let updatedField = '';
                    if(indexMain !== 0 && history.eq(indexMain).find('.step-single').eq(index).find('.value').html() !== history.eq(indexMain - 1).find('.step-single').eq(index).find('.value').html()) updatedField = 'updated-field';
                    if(value.length === 0) value = '-'; // если поле пустое - то писать прочерк
                    html += '<div class="hw-single ' + updatedField + '">' +
                        '<div class="hw-field">' + field + '</div>' +
                        '<div class="hw-value">' + value + '</div>' +
                        '</div>'
                }
            });

            html += '</div>'; // hw-body

        });

        // конец тела таблицы
        html += '</div>';

        // применение построенного html
        table.html(html);

    }

    // по умолчанию строится таблица со всеми ревизиями
    buildTableAll();

});