<div class="correlation__row">
    <div class="correlation__key">
        <span>{$base_params['description']}</span></apsn><span class="help_bt" h_id="{$base_params['help']}"></span>:
    </div>
    <div style="text-align: left; padding: 3px;">
        <select class="form-control form-control-160" id="calc_params_{$tpl_num}_{$base_params['name']}_subTable"
                name="calc_params[{$tpl_num}][{$base_params['name']}][subTable]">
            {foreach from=$type_params['subTables'] key=table_id item=table_name}
                {if $table_id == $base_params['set_params']['subTable']}
                    <option data-link="{$table_name.link}" data-id="{$table_name.link|substr:1}" value="{$table_id}" selected>
                        {if isset($table_name.name)}
                            {$table_name.name}
                        {else}
                            {$table_name}
                        {/if}
                    </option>
                {else}
                    <option data-link="{$table_name.link}" data-id="{$table_name.link|substr:1}" value="{$table_id}">
                        {if isset($table_name.name)}
                            {$table_name.name}
                        {else}
                            {$table_name}
                        {/if}
                    </option>
                {/if}
            {foreachelse}
                <option value="0" selected>{$lang.No_subtables_in_table}</option>
            {/foreach}
        </select>
    </div>
</div>
<div class="correlation__row" id="calc_params_{$tpl_num}_{$base_params['name']}_subFieldDiv">
    <div class="correlation__key">
        <span>{$base_params['sub_description']}</span><span class="help_bt" h_id="{$base_params['field_help']}"></span>:
    </div>
    <div style="text-align: left; padding: 3px;">
        <select class="form-control form-control-160 dont_use_chosen" id="calc_params_{$tpl_num}_{$base_params["name"]}_subField"
                name="calc_params[{$tpl_num}][{$base_params['name']}][subField]">
        </select>
        <input type="hidden" id="calc_params_{$tpl_num}_{$base_params["name"]}_link_field_id"
               name="calc_params[{$tpl_num}][{$base_params['name']}][link_field_id]">
    </div>
</div>
<script>
    (function(){
        var init = false;

        var startField = document.getElementById('corellation-{$tpl_num}');
        var selTable = document.getElementById('calc_params_{$tpl_num}_sub_table_subTable');

        function changeField(startField) {
            if(!init){
                var WhereToinsert = document.getElementById('calc_params_{$tpl_num}_sub_table_subField');
                var sel_table_id = document.getElementById('calc_params_{$tpl_num}_sub_table_subTable').value;
                var table_id;
                if (document.getElementById('calc_form')) {
                    table_id = document.getElementById('calc_form').getAttribute('table-id');
                } else {
                    table_id = document.getElementById('edit_button_form').getAttribute('table-id');
                }
                var field_id = document.getElementsByName('calc_params[{$tpl_num}][res_field]')[0];
                field_id = field_id[field_id.selectedIndex].getAttribute('data-id');


                var url = 'edit_calc.php?ajax=true&action=getCorrelationFields&table=' + sel_table_id + '&sel_field=' + field_id + '&sel_table=' + table_id;

                var request = new XMLHttpRequest();
                request.open('GET', url);
                request.onreadystatechange = function() {
                    if (request.readyState == 4) {
                        if(request.status == 200) {
                            var data = JSON.parse(request.responseText);
                            deleteWrappers(WhereToinsert);
                            for (option in data) {
                                var calc_paramsOption = document.createElement('option');
                                if(data[option].id === 'id' || data[option].id === 'status' || data[option].id === 'user_id' || data[option].id === 'add_time'){
                                    calc_paramsOption.setAttribute('value',data[option].id);
                                } else{
                                    calc_paramsOption.setAttribute('value','f' + data[option].id);
                                }
                                calc_paramsOption.setAttribute('value','f' + data[option].id);
                                calc_paramsOption.setAttribute('data-type',data[option].type_field);
                                calc_paramsOption.setAttribute('data-id',data[option].id);
                                var textNode = document.createTextNode(data[option].name_field);
                                calc_paramsOption.appendChild(textNode);
                                WhereToinsert.appendChild(calc_paramsOption);

                            }
                            for (var i = 0; i < WhereToinsert.length; i++) {
                                if(WhereToinsert[i].value === '{$base_params['set_params']['link_field_id']}') {
                                     WhereToinsert.selectedIndex = i;
                                 }
                             }

                            if (typeof data == "object" && data.length == 0) {
                              const disabled_option = document.createElement('option');
                              disabled_option.setAttribute('disabled', 'disabled');
                              const text_node = document.createTextNode(lang.No_fields_to_match);
                              disabled_option.appendChild(text_node);
                              WhereToinsert.appendChild(disabled_option);
                            }

                            document.getElementById('calc_params_{$tpl_num}_sub_table_link_field_id').value = document.getElementById('calc_params_{$tpl_num}_sub_table_subTable')[document.getElementById('calc_params_{$tpl_num}_sub_table_subTable').selectedIndex].getAttribute('data-link');

                        }
                    }
                };
                request.send(null);
            }else {
                var WhereToinsert = document.getElementById('calc_params_{$tpl_num}_sub_table_subField');
                var sel_table_id = document.getElementById('calc_params_{$tpl_num}_sub_table_subTable').value;
                var table_id;
                if (document.getElementById('calc_form')) {
                    table_id = document.getElementById('calc_form').getAttribute('table-id');
                } else {
                    table_id = document.getElementById('edit_button_form').getAttribute('table-id');
                }
                var field_id = document.getElementsByName('calc_params[{$tpl_num}][res_field]')[0];
                field_id = field_id[field_id.selectedIndex].getAttribute('data-id');
                deleteWrappers(WhereToinsert);


                var url = 'edit_calc.php?ajax=true&action=getCorrelationFields&table=' + sel_table_id + '&sel_field=' + field_id + '&sel_table=' + table_id;
                ajaxReq(url, WhereToinsert);
            }


        };

        function deleteWrappers(WhereToinsert) {
            //общий блок берем из предыдущей функции  =  parentWhere
            //находим количество элементов
            var numberofSlices = WhereToinsert.childElementCount;
            //срезаем всё до первого
            for (var i = 0; i < numberofSlices; i++) {
                //сносим всё кроме первого элемента
                WhereToinsert.lastElementChild.remove()
            }
        }
        function ajaxReq(url, WhereToinsert) {

            var request = new XMLHttpRequest();
            request.open('GET', url);
            request.onreadystatechange = function () {
                if (request.readyState == 4) {
                    if (request.status == 200) {
                        changeLinks(JSON.parse(request.responseText), WhereToinsert)
                    }
                }
            };
            request.send(null);
        };

        function changeLinks(data, WhereToinsert) {
            for (option in data) {
                var calc_paramsOption = document.createElement('option');
                if(data[option].id === 'id' || data[option].id === 'status' || data[option].id === 'user_id' || data[option].id === 'add_time'){
                    calc_paramsOption.setAttribute('value',data[option].id);
                } else{
                    calc_paramsOption.setAttribute('value','f' + data[option].id);
                }

                calc_paramsOption.setAttribute('value', 'f' + data[option].id);
                calc_paramsOption.setAttribute('data-type', data[option].type_field);
                calc_paramsOption.setAttribute('data-id', data[option].id);
                var textNode = document.createTextNode(data[option].name_field);
                calc_paramsOption.appendChild(textNode);
                WhereToinsert.appendChild(calc_paramsOption);

            }

            if (typeof data == "object" && data.length == 0) {
              const disabled_option = document.createElement('option');
              disabled_option.setAttribute('disabled', 'disabled');
              const text_node = document.createTextNode(lang.No_fields_to_match);
              disabled_option.appendChild(text_node);
              WhereToinsert.appendChild(disabled_option);
            }

            document.getElementById('calc_params_{$tpl_num}_sub_table_link_field_id').value = document.getElementById('calc_params_{$tpl_num}_sub_table_subTable')[document.getElementById('calc_params_{$tpl_num}_sub_table_subTable').selectedIndex].getAttribute('data-link');

        }

        $(startField).on('change', function(e) {
            changeField(startField)
        });
        var linkField = document.getElementById('calc_params_{$tpl_num}_sub_table_subField');
        linkField.onchange = function (e) {
            document.getElementById('calc_params_{$tpl_num}_sub_table_link_field_id').value = document.getElementById('calc_params_{$tpl_num}_sub_table_subTable')[document.getElementById('calc_params_{$tpl_num}_sub_table_subTable').selectedIndex].getAttribute('data-link');
        };

        selTable.onchange = function (e) {
            changeField(startField)
        };

        changeField(startField)
        init = true;
    })(); // SubFied.tpl 1
</script>
