<td colspan="2" align="center">
    <h2 style="font-size: 22px;">{$params_tpl['title']}{$params_tpl['help']}</h2>
    <div style="display: flex; flex-direction: column;">
        <div class="correlation__row">
            <div class="correlation__key">Выберите таблицу-получатель
                <span class="help_bt" h_id="result_table"></span>:
            </div>
            <div class="correlation__val">
                <select class="form-control form-control-160 dont_use_chosen" type="text" name="calc_params[{$tpl_num}][table2]"></select>
                <div class="correlation__settings">
                    <button style="display: none" type="button" class="correlation__settings-btn correlation__settings-btn--add" id="add-template-div"></button>
                </div>
            </div>
        </div>

        <div style="display: none" id="source_row_{$tpl_num}" class="correlation__row">
            <div class="correlation__key">Выберите таблицу-источник
                <span class="help_bt" h_id="source_table"></span>:
            </div>
            <div class="correlation__val">
                <select class="form-control form-control-160 dont_use_chosen" type="text" name="calc_params[{$tpl_num}][table1]"></select>
            </div>
        </div>
    </div>

    <div id="calc_{$tpl_num}_div" style="display: flex; flex-direction: column;">
    </div>

    <div style="display: flex; flex-direction: column; padding-top: 20px;">
        <div class="correlation__row">
            <div class="correlation__key">
                <span>Выберите фильтр</span><span class="help_bt" h_id="tpl_sel_filter"></span>:
            </div>
            <div style="text-align: left; padding: 3px;">
                <select class="form-control form-control-160 construct_select-filter dont_use_chosen" name="calc_params[{$tpl_num}][filter]"></select>
            </div>
        </div>
    </div>
    <div style="display: flex; flex-direction: column;">{$tpl_types['link_field']}</div>
</td>

<script type="text/javascript" src="themes/clientbase/libs/mithril.min.js?{$revision}"></script>
<script>
    (function () {
        $('select[name="calc_params[{$tpl_num}][link_field]"]').html('<option value=""></option>' + $('select[name="calc_params[{$tpl_num}][link_field]"]').html());

        let selectTable1 = $('select[name="calc_params[{$tpl_num}][table1]"]');
        let selectTable2 = $('select[name="calc_params[{$tpl_num}][table2]"]');
        let inc = 1;

        const calcId = getCalcId();
        if (Number(calcId) !== -1) {
            let calculate = new XMLHttpRequest();
            calculate.open('GET', 'edit_calc.php?calc-ajax-action=1&action=getCalculate&calcId=0&buttonId=' + calcId);
            calculate.send();
            calculate.onload = function () {
                if (calculate.response.toString() !== "[]") {
                    let calc_params = JSON.parse(calculate.response);

                    if (calc_params[{$tpl_num}]['construct_params'] !== "") {
                        calc_params = JSON.parse(calc_params[{$tpl_num}]['construct_params']);
                        
                        let params_{$tpl_num} = calc_params['params'] == null ? {} : calc_params['params'][{$tpl_num}];

                        if (params_{$tpl_num}['table1'] != '') {
                            document.getElementById("source_row_{$tpl_num}").style.display = '';
                        }
                        getTable(params_{$tpl_num});
                        document.getElementById("add-template-div").style.display = '';

                        for (let k in params_{$tpl_num}['f1']) {
                            let el = templateDiv(k);
                            $("#calc_{$tpl_num}_div").append(el);
                            document.getElementById("btn_" + k).innerHTML = '<button onclick="document.getElementById(\'div-added-'+ k +'\').remove()" type="button" class="correlation__settings-btn correlation__settings-btn--remove"></button>';

                            if (params_{$tpl_num}['f1']) {
                                getFieldsForTable(params_{$tpl_num}['table1'], 'f1', k, params_{$tpl_num}['f1'][k]);
                            } else {
                                getFieldsForTable($('select[name="calc_params[{$tpl_num}][table1]"]').val(), 'f1', k);
                            }

                            if (params_{$tpl_num}['f2']) {
                                getFieldsForTable(params_{$tpl_num}['table2'], 'f2', k, params_{$tpl_num}['f2'][k]);
                            } else {
                                getFieldsForTable($('select[name="calc_params[{$tpl_num}][table2]"]').val(), 'f2', k);
                            }

                            if (params_{$tpl_num}['f3']) {
                                $('input[name="calc_params[{$tpl_num}][f3][' + k + ']"]').val(params_{$tpl_num}['f3'][k]);
                            }
                            inc++;
                        }

                        if (params_{$tpl_num}['filter']) {
                            getFilters(params_{$tpl_num}['table1'], params_{$tpl_num}['filter']);
                        } else {
                            getFilters(params_{$tpl_num}['table1']);
                        }
                    }
                }
            };
        } else {
            getTable();
        }

        function getSalk(val) {
            let div = document.createElement('div');
            document.getElementById("add-template-div").style.display = '';
            div.id = val;
            div.innerHTML = templateDiv(val);
            return div;
        }

        $(selectTable2).change(function() {
            document.getElementById("source_row_{$tpl_num}").style.display = '';
            init_chosen();
        });

        $(selectTable1).change(function() {
            let a = document.getElementById("calc_{$tpl_num}_div");
            a.innerHTML = "";
            let val = inc;
            let o = getSalk(val);
            a.append(o);
            document.getElementById("btn_" + val).innerHTML = '<button onclick="document.getElementById(\'div-added-'+ val +'\').remove()" type="button" class="correlation__settings-btn correlation__settings-btn--remove"></button>';
            getFieldsForTable(selectTable1.val(), 'f1', val);
            getFieldsForTable(selectTable2.val(), 'f2', val);
            inc++;

            getFilters(selectTable1.val());
            init_chosen();
        });

        $('#add-template-div').click(function () {
            let id = inc;
            let el = templateDiv(id);
            $("#calc_{$tpl_num}_div").append(el);
            document.getElementById("btn_" + id).innerHTML = '<button onclick="document.getElementById(\'div-added-'+ id +'\').remove()" type="button" class="correlation__settings-btn correlation__settings-btn--remove"></button>';
            getFieldsForTable(id);
            getFieldsForTable(selectTable1.val(), 'f1', id);
            getFieldsForTable(selectTable2.val(), 'f2', id);
            inc++;
        });

        function templateDiv(val) {
            return (val ? '<div id="div-added-' + val + '">' : '')
                + '<hr>' +
                '<div class="row"">\n' +
                '  <div class="correlation__row">\n' +
                '  <div class="correlation__key">Выберите поле-источник:</div>\n' +
                '    <div class="correlation__val">\n' +
                '      <select id="f1_'+ val + '" class="form-control form-control-160 dont_use_chosen" type="text" name="calc_params[{$tpl_num}][f1][' + val + ']"></select>\n' +
                '      <div class="correlation__settings" id="btn_' + val + '">' +
                '      </div>' +
                '    </div>\n' +
                '  </div>\n' +
                '  <div class="correlation__row">\n' +
                '  <div class="correlation__key">Выберите поле-получатель:</div>\n' +
                '    <div class="correlation__val">\n' +
                '      <select id="f2_'+ val + '" class="form-control form-control-160 dont_use_chosen" type="text" name="calc_params[{$tpl_num}][f2][' + val + ']"></select>\n' +
                '    </div>\n' +
                '  </div>\n' +
                '  <div class="correlation__row">\n' +
                '  <div class="correlation__key">Значение по умолчанию:</div>\n' +
                '    <div class="correlation__val">\n' +
                '      <input class="form-control form-control-160" style="width: 170px;" type="text" name="calc_params[{$tpl_num}][f3][' + val + ']">\n' +
                '    </div>\n' +
                '  </div>\n' +
                '</div>' +
                (val ? '</div>' : '');
        }

        function getTable(val = 'undefined') {
            // получаю таблицу-источник
            let tbl1 = new XMLHttpRequest();
            tbl1.open('GET', 'edit_calc.php?calc-ajax-action=1&action=getTable');
            tbl1.send();
            tbl1.onload = function () {
                if (tbl1.response.toString() !== "[]") {
                    let tb1 = JSON.parse(tbl1.response);

                    for (let i of tb1) {
                        $(selectTable1).prepend('<option value="'+ i.id +'" ' + (
                            typeof val === 'undefined' ? '' : val['table1'] == i.id ? 'selected' : ''
                        ) + '>'+ i.name_table +'</option>');
                    }
                    $(selectTable1).prepend('<option value="" '+( typeof val === 'undefined' ? '' : val['table1'] ? '' : 'selected' )+'></option>');
                } else {
                    $('select[name="calc_params[{$tpl_num}][table1]"]').prepend('<option selected disabled>Подходящих таблиц не найдено</option>');
                }
            };

            // получаю подтаблицу-получатель
            let table2 = new XMLHttpRequest();
            table2.open('GET', 'edit_calc.php?calc-ajax-action=1&action=getSubTable&table=' + tableId);
            table2.send();
            table2.onload = function () {
                if (table2.response.toString() !== "[]") {
                    let tb2 = JSON.parse(table2.response);

                    for (let i of tb2) {
                        $(selectTable2).prepend('<option value="'+ i.link_table_id +'" ' + (
                            typeof val === 'undefined' ? '' : val['table2'] == i.link_table_id ? 'selected' : ''
                        ) + '>'+ i.name +'</option>');
                    }
                    $(selectTable2).prepend('<option value=""  ' + ( typeof val === 'undefined' ? '' : val['table2'] ? '' : 'selected' ) + '></option>');
                } else {
                    $('select[name="calc_params[{$tpl_num}][table2]"]').prepend('<option selected disabled>Подходящих таблиц не найдено</option>');
                }
            };
        }

        function getFilters(tableId, filterId) {
            var filter = new XMLHttpRequest();
            filter.open('GET', 'edit_calc.php?calc-ajax-action=1&action=getFilter&table=' + tableId);
            filter.send();
            filter.onload = function () {
                document.getElementsByName("calc_params[0][filter]")[{$tpl_num}].innerHTML = "";
                if (filter.response.toString() !== "[]") {
                    let data = JSON.parse(filter.response);
                    for (let i of data) {
                        $('select[name="calc_params[{$tpl_num}][filter]"]').prepend('<option value="'+ i.id +'" '+(filterId == i.id ? 'selected' : '')+'>'+ i.parent + i.name +'</option>');
                    }

                    $('select[name="calc_params[{$tpl_num}][filter]"]').prepend('<option value="" '+(filterId ? '' : 'selected')+'></option>');
                    init_chosen();
                } else {
                    $('select[name="calc_params[{$tpl_num}][filter]"]').prepend('<option selected disabled>Нет подходящих фильтров</option>');
                }
            };
        }

        // поле-источник и поле-получатель
        function getFieldsForTable(table, prefix, val, selected) {
            var field = new XMLHttpRequest();
            field.open('GET', 'edit_calc.php?calc-ajax-action=1&action=getField&table=' + table + '&field=1,2,3,4,5,7,14');//,11,12
            field.send();
            field.onload = function () {
                if (field.response.toString() !== "[]") {
                    let data = JSON.parse(field.response);
                    for (let i of data) {
                        $('select[name="calc_params[{$tpl_num}][' + prefix + '][' + val + ']"]').prepend('<option value="'+ i.id +'" '+(selected == i.id ? 'selected' : '')+' data-type="'
                            + i.type_field+'">' + i.name_field + '</option>');
                    }

                    $('select[name="calc_params[{$tpl_num}][' + prefix + '][' + val + ']"]').prepend('<option value="" '+(selected ? '' : 'selected')+'></option>');

                    $('select[name="calc_params[{$tpl_num}][' + prefix + '][' + val + ']"]').change(function () {
                        let option = $('select[name="calc_params[{$tpl_num}][' + prefix + '][' + val + ']"] option:selected').attr('data-type');

                        if ($('select[name="calc_params[{$tpl_num}][' + (prefix == 'f1' ? 'f2' : 'f1') + '][' + val + ']"] option:selected').attr('data-type') !== option ||
                            option === undefined) {
                            $('select[name="calc_params[{$tpl_num}][' + (prefix == 'f1' ? 'f2' : 'f1') + '][' + val + ']"] option').removeAttr("selected");

                            $('select[name="calc_params[{$tpl_num}][' + (prefix == 'f1' ? 'f2' : 'f1') + '][' + val + ']"] option').each(function() {
                                if ($( this ).attr('data-type') === undefined) {
                                } else if ($( this ).attr('data-type') != option) {
                                    $( this ).css("display", "none");
                                }
                                if ($( this ).attr('data-type') == option) {
                                    $( this ).css("display", "");
                                }
                                if (option === undefined) $( this ).css("display", "");
                            });
                        }

                        if ($('select[name="calc_params[{$tpl_num}][' + prefix + '][' + val + ']"] option:selected').val() == "" &&
                            $('select[name="calc_params[{$tpl_num}][' + (prefix == 'f1' ? 'f2' : 'f1') + '][' + val + ']"] option:selected').val() == "") {
                            $('select[name="calc_params[{$tpl_num}][' + prefix + '][' + val + ']"] option').each(function() {
                                $( this ).css("display", "");
                            });
                            $('select[name="calc_params[{$tpl_num}][' + (prefix == 'f1' ? 'f2' : 'f1') + '][' + val + ']"] option').each(function() {
                                $( this ).css("display", "");
                            });
                        }
                    });
                } else {
                    $('select[name="calc_params[{$tpl_num}][' + prefix + '][' + val + ']"]').prepend('<option selected disabled>Нет подходящих полей</option>');
                }
            };
        }

        function getCalcId() {
            var search = window.location.search.substr(1), keys = {};
            search.split('&').forEach(function(item) {
                item = item.split('=');
                keys[item[0]] = item[1];
            });
            return keys.button ? keys.button : false;
        }
    })();
</script>