var MetaSettingComponent = {
    obj: {},
    show: 0,

    counter: 1,
    setCounter: function(value) {
        this.counter = value;
    },

    party: '',
    setParty: function(value) {
        this.party = value;
    },

    address: '',
    setAddress: function(value) {
        this.address = value;
    },

    bank: '',
    setBank: function(value) {
        this.bank = value;
    },

    tables: '',
    setTables: function(value) {
        this.tables = value;
    },

    settings: '',
    setSettings: function(value) {
        this.settings = value;
        this.obj = value;
    },

    getData: function() {
        let data = new FormData();
        data.append('init', 'getSettings');
        data.append('csrf', csrf);
        m.request({
            method: 'POST',
            url: 'modules/dadata/request.php',
            data: data
        })
        .then(function(result) {
            // console.log(result);
            MetaSettingComponent.setParty(result['party']);
            MetaSettingComponent.setAddress(result['address']);
            MetaSettingComponent.setBank(result['bank']);
            MetaSettingComponent.setTables(result['tables']);
            MetaSettingComponent.setSettings(result['settings'].length == 0 ? {} : result['settings']);
        })
    },

    saveSettings: function() {
        var data = new FormData();
        data.append('csrf', csrf);
        data.append('init', 'saveSettings');
        data.append('settings', JSON.stringify(MetaSettingComponent.obj));
        m.request({
            method: 'POST',
            url: 'modules/dadata/request.php',
            data: data
        })
        .then(function() {
            window.location.reload();
        })
    },

    deleteSettings: function(value) {
        delete(this.obj[value]);
        this.show = 0;
    }
};

function optionTable(tableid = 0) {
    if (MetaSettingComponent.tables == '') return [];
    var arr = [];
    arr.push(m('option', {value: '', selected: tableid == 0 ? 'selected' : ''}, ''));
    for (var i in MetaSettingComponent.tables) {
        arr.push(m('option', {
            value: MetaSettingComponent.tables[i]['table_id'],
            selected: tableid == MetaSettingComponent.tables[i]['table_id'] ? 'selected' : ''
        }, MetaSettingComponent.tables[i]['table_name']));
    }
    return arr;
}

function optionFields(tableid, sel = 0, isSource = false, need = false) {
    const sourceField = Object.values(MetaSettingComponent.obj)[0]['sourceField'];
    let arr = [];

    if (tableid == 0) return [];
    if (typeof tableid == 'undefined') return [];

    arr.push(m('option', {value: '', selected: sel == 0 ? 'selected' : ''}, ''));
    for (let i in MetaSettingComponent.tables[tableid]['fields']) {
        const fieldId = MetaSettingComponent.tables[tableid]['fields'][i]['id'];

        if (!isSource && fieldId == sourceField) continue;
        if (need && MetaSettingComponent.tables[tableid]['fields'][i]['type_field'] != 3) continue;
        arr.push(m('option', {
            value: fieldId,
            selected: sel == fieldId ? 'selected' : ''
        }, MetaSettingComponent.tables[tableid]['fields'][i]['name_field']));
    }
    return arr;
}

let dadataFields = {
    view: function (vnode) {
        if (vnode.attrs.tableid == 0) return [];
        var arr = [];
        if (vnode.attrs.type == 3 || typeof vnode.attrs.dadataFields["data"]["area"] == 'string') {
            MetaSettingComponent.obj[vnode.attrs.num]['unrestricted_value'] = MetaSettingComponent.obj[vnode.attrs.num]['sourceField'];
        }
        for (let i in vnode.attrs.dadataFields) {
            if (vnode.attrs.type == 2) {
                if (i == 'value') {
                    MetaSettingComponent.obj[vnode.attrs.num][i] = MetaSettingComponent.obj[vnode.attrs.num]['sourceField'];
                    continue;
                }
            }

            if (typeof vnode.attrs.dadataFields[i] == 'string') {
                if (typeof vnode.attrs.settings[i] != 'undefined') MetaSettingComponent.obj[vnode.attrs.num][i] = vnode.attrs.settings[i] != 0 ? vnode.attrs.settings[i] : 0;
                arr.push(m('tr', [
                    m('td', {align: 'right', width: '45%'}, vnode.attrs.dadataFields[i]),
                    m('td', m('select', {
                        name: i,
                        class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                        onchange: function(e) {
                            MetaSettingComponent.obj[vnode.attrs.num][e.target.name] = e.target.value;
                        }
                    }, optionFields(vnode.attrs.tableid, (vnode.attrs.settings[i] != 0 ? vnode.attrs.settings[i] : 0))))
                ]));
            } else if(typeof vnode.attrs.dadataFields[i] == 'object') {
                for (var j in vnode.attrs.dadataFields[i]) {
                    if (typeof vnode.attrs.dadataFields[i][j] == 'object') {
                        for (var k in vnode.attrs.dadataFields[i][j]) {
                            if (typeof vnode.attrs.settings[i +'*'+ j +'*'+ k] != 'undefined') {
                                MetaSettingComponent.obj[vnode.attrs.num][i +'*'+ j +'*'+ k] = vnode.attrs.settings[i +'*'+ j +'*'+ k] != 0 ? vnode.attrs.settings[i +'*'+ j +'*'+ k] : 0;
                            }
                            arr.push(m('tr', [
                                m('td', {align: 'right', width: '45%'}, vnode.attrs.dadataFields[i][j][k]),
                                m('td', m('select', {
                                    name: i +'*'+ j +'*'+ k,
                                    class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                                    onchange: function(e) {
                                        MetaSettingComponent.obj[vnode.attrs.num][e.target.name] = e.target.value;
                                    }
                                }, optionFields(vnode.attrs.tableid, (vnode.attrs.settings[i +'*'+ j +'*'+ k] != 0 ? vnode.attrs.settings[i +'*'+ j +'*'+ k] : 0))))
                            ]));
                        }
                    } else {
                        if (vnode.attrs.type == 1) {
                            if (j == 'inn') {
                                MetaSettingComponent.obj[vnode.attrs.num][i +'*'+ j] = MetaSettingComponent.obj[vnode.attrs.num]['sourceField'];
                                continue;
                            }
                        }
                        if (typeof vnode.attrs.settings[i +'*'+ j] != 'undefined') MetaSettingComponent.obj[vnode.attrs.num][i +'*'+ j] = vnode.attrs.settings[i +'*'+ j] != 0 ? vnode.attrs.settings[i +'*'+ j] : 0;
                        arr.push(m('tr', [
                            m('td', {align: 'right', width: '45%'}, vnode.attrs.dadataFields[i][j]),
                            m('td', m('select', {
                                name: i +'*'+ j,
                                class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                                onchange: function(e) {
                                    MetaSettingComponent.obj[vnode.attrs.num][e.target.name] = e.target.value;
                                }
                            }, optionFields(vnode.attrs.tableid, (vnode.attrs.settings[i +'*'+ j] != 0 ? vnode.attrs.settings[i +'*'+ j] : 0))))
                        ]));
                    }
                }
            }
        }
        return arr;
    }
}

function AllTables(vnode) {
    var num = vnode.attrs.num;
    return {
        view: function(vnode) {
            return m('div', {style: {'padding-bottom': '5px'}}, [
                m('div', m('table[width=100%]', m('tr', [
                    m('td[width=40%]'),
                    m('td', [
                        m('a', {
                            onclick: () => MetaSettingComponent.deleteSettings(vnode.attrs.num)
                        }, m('img', { src: 'images/b_drop.png', title: lang['Delete'], style: {'padding-bottom': '1px', 'padding-right': '6px'} })),
                        m('span', {
                            style: {cursor: 'pointer', 'text-decoration': 'underline', 'text-decoration-style': 'dotted', color: 'blue', 'font-size': '13px'},
                            onclick: function() {
                                MetaSettingComponent.show = MetaSettingComponent.show == num ? 0 : num;
                            }
                        }, (MetaSettingComponent.obj[vnode.attrs.num]['table'] != ''
                            ? lang['Table'] + ': "' + MetaSettingComponent.tables[MetaSettingComponent.obj[vnode.attrs.num]['table']]['table_name'] + '"'
                            : lang['Table'] + ':'))
                    ]),
                ])))
            ])
        }
    }
}

function createHelpBtn() {
    return {
        view: function(vnode) { return m('span[class=help_bt]', {h_id:vnode.attrs.helpbtn}); },
        oncreate: function() { bind_help_bt('setting-component'); },
        oninit: checkHelpButtonsOnCurrentPage(),
    }
}

let TableComponent = {
    view: function(vnode) {
        return m('div', m('table[width=100%]', [
            m('tr', [                                                           /* ПОЛЕ ВЫБОРА БАЗЫ */
                m('td', {align: 'right', width: '45%'}, [
                    m('span', 'База для поиска'),
                    m('span[class=help_bt]', {
                        oninit: checkHelpButtonsOnCurrentPage(),
                        oncreate: function() { bind_help_bt('setting-component'); },
                        h_id: 'module_dadata_base'
                    }), m('span', ':')
                ]),
                m('td', {width: '55%'}, [
                    m('select', {
                        style: {'margin-right': '5px'},
                        class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                        onchange: function(e) {
                            if (e.target.value == 0) MetaSettingComponent.obj[vnode.attrs.num] = { base: 0, table: 0, type: 0, sourceField: 0 };
                            else MetaSettingComponent.obj[vnode.attrs.num] = {
                                base: e.target.value,
                                table: MetaSettingComponent.obj[vnode.attrs.num]['table'],
                                type: e.target.value == 3 ? 4 : 0,
                                sourceField: MetaSettingComponent.obj[vnode.attrs.num]['sourceField']
                            };
                        }
                    }, [
                        m('option', { selected: MetaSettingComponent.obj[vnode.attrs.num]['base'] == 0 ? 'selected' : '' }, ''),
                        m('option', { value: 1, selected: MetaSettingComponent.obj[vnode.attrs.num]['base'] == 1 ? 'selected' : '' }, 'Компании'),
                        m('option', { value: 2, selected: MetaSettingComponent.obj[vnode.attrs.num]['base'] == 2 ? 'selected' : '' }, 'Адреса'),
                        m('option', { value: 3, selected: MetaSettingComponent.obj[vnode.attrs.num]['base'] == 3 ? 'selected' : '' }, 'Банки'),
                    ]),
                ])
            ]),
            (MetaSettingComponent.obj[vnode.attrs.num]['base'] == 0 ? '' : m('tr', [            /* ПОЛЕ ВЫБОРА ТАБЛИЦЫ */
                m('td', {align: 'right', width: '45%'}, [
                    m('span', lang['Sync_select_table']),
                    m('span[class=help_bt]', {
                        oninit: checkHelpButtonsOnCurrentPage(),
                        oncreate: function() { bind_help_bt('setting-component'); },
                        h_id: 'module_dadata_table'
                    }), m('span', ':')
                ]),
                m('td', {width: '55%'}, [
                    m('select', {
                        style: {'margin-right': '5px'},
                        class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                        onchange: function(e) {
                            if (e.target.value == 0) MetaSettingComponent.obj[vnode.attrs.num] = {
                                base: MetaSettingComponent.obj[vnode.attrs.num]['base'], table: 0, type: 0, sourceField: 0 };
                            else MetaSettingComponent.obj[vnode.attrs.num]['table'] = e.target.value;
                        }
                    }, optionTable(MetaSettingComponent.obj[vnode.attrs.num]['table'] != 0 ? MetaSettingComponent.obj[vnode.attrs.num]['table'] : 0)),
                ])
            ])),
            (MetaSettingComponent.obj[vnode.attrs.num]['table'] == 0 ? '' : m('tr', [               /* ПОЛЕ ПОИСКА */
                m('td', {align: 'right'}, [
                    m('span', 'Поле поиска'),
                    m('span[class=help_bt]', {
                        oninit: checkHelpButtonsOnCurrentPage(),
                        oncreate: function() { bind_help_bt('setting-component'); },
                        h_id: 'module_dadata_field_search'
                    }), m('span', ':')
                ]),
                m('td', [
                    m('select', {
                        class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                        onchange: function(e) {
                            if (e.target.value == 0) {
                                MetaSettingComponent.obj[vnode.attrs.num] = {
                                    base: MetaSettingComponent.obj[vnode.attrs.num]['base'],
                                    table: MetaSettingComponent.obj[vnode.attrs.num]['table'],
                                    type: MetaSettingComponent.obj[vnode.attrs.num]['base'] == 3 ? 4 : 0,
                                    sourceField: 0
                                };
                                console.log(MetaSettingComponent.obj[vnode.attrs.num]);
                            }
                            else MetaSettingComponent.obj[vnode.attrs.num]['sourceField'] = e.target.value;
                        }
                    }, optionFields(MetaSettingComponent.obj[vnode.attrs.num]['table'] != 0 ? MetaSettingComponent.obj[vnode.attrs.num]['table'] : 0,
                        (MetaSettingComponent.obj[vnode.attrs.num]['sourceField'] != 0 ? MetaSettingComponent.obj[vnode.attrs.num]['sourceField'] : 0), true, true))
                ])
            ])),
            (MetaSettingComponent.obj[vnode.attrs.num]['sourceField'] == 0 ? '' : m('tr', [        /* ЧТО СОХРАНЯТЬ В ПОЛЕ ПОИСКА */
                m('td', {align: 'right'}, [
                    m('span', 'Что сохранять в поле поиска'),
                    m('span[class=help_bt]', {
                        oninit: checkHelpButtonsOnCurrentPage(),
                        oncreate: function() { bind_help_bt('setting-component'); },
                        h_id: 'module_dadata_type'
                    }), m('span', ':')
                ]),
                m('td', [
                    m('select', {
                        class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                        onchange: function(e) {
                            MetaSettingComponent.obj[vnode.attrs.num] = {
                                base: MetaSettingComponent.obj[vnode.attrs.num]['base'],
                                table: MetaSettingComponent.obj[vnode.attrs.num]['table'],
                                type: e.target.value == 0 ? 0 : e.target.value,
                                sourceField: MetaSettingComponent.obj[vnode.attrs.num]['sourceField']
                            }
                        }
                    }, [
                        m('option', { selected: MetaSettingComponent.obj[vnode.attrs.num]['type'] == 0 ? 'selected' : '' }, ''),
                        (MetaSettingComponent.obj[vnode.attrs.num]['base'] == 1 ? [
                            m('option', { value: 1, selected: MetaSettingComponent.obj[vnode.attrs.num]['type'] == 1 ? 'selected' : '' }, 'ИНН'),
                            m('option', { value: 2, selected: MetaSettingComponent.obj[vnode.attrs.num]['type'] == 2 ? 'selected' : '' }, 'Название'),
                        ] : ''),
                        (MetaSettingComponent.obj[vnode.attrs.num]['base'] == 2 ? [
                            m('option', { value: 3, selected: MetaSettingComponent.obj[vnode.attrs.num]['type'] == 3 ? 'selected' : '' }, 'Адрес')
                        ] : ''),
                        (MetaSettingComponent.obj[vnode.attrs.num]['base'] == 3 ? [
                            m('option', { value: 4, selected: MetaSettingComponent.obj[vnode.attrs.num]['type'] == 4 ? 'selected' : '' }, 'Название'),
                            m('option', { value: 5, selected: MetaSettingComponent.obj[vnode.attrs.num]['type'] == 5 ? 'selected' : '' }, 'БИК'),
                        ] : ''),
                    ])
                ])
            ])),
            (MetaSettingComponent.obj[vnode.attrs.num]['sourceField'] == 0 ? '' : m('tr',
                m('td[colspan=2]', {width: '100%'}, m('div', [
                    m('table', {width:'100%', cellpadding: "0", cellspacing: "0", border: "0"},
                        m(dadataFields, {                                                               /*** ОСТАЛЬНЫЕ ПОЛЯ ДЛЯ СОПОСТАВЛЕНИЯ ДАДАТЫ С КБ ***/
                            type: MetaSettingComponent.obj[vnode.attrs.num]['type'],
                            num: vnode.attrs.num,
                            tableid: MetaSettingComponent.obj[vnode.attrs.num]['table'],
                            settings: vnode.attrs.settings != {} ? vnode.attrs.settings : {},

                            dadataFields: MetaSettingComponent.obj[vnode.attrs.num]['base'] == 1        // если выбрано "Компании"
                                ? MetaSettingComponent.party
                                : (
                                    MetaSettingComponent.obj[vnode.attrs.num]['base'] == 2              // если "Адреса"
                                        ? MetaSettingComponent.address
                                        : (
                                            MetaSettingComponent.obj[vnode.attrs.num]['base'] == 3      // если "Банки"
                                            ? MetaSettingComponent.bank
                                            : {}                                                        // иначе пустой объект
                                        )
                                )
                        })
                    )
                ]))
            ))
        ]));
    }
}

var SettingComponent = function() {
    return {
        oninit: MetaSettingComponent.getData,

        view: function() {
            var arr = [];
            if (Object.keys(MetaSettingComponent.obj).length != 0) {
                for (var i in MetaSettingComponent.obj) {
                    arr.push(m('div', m(AllTables, { num: i })));
                    MetaSettingComponent.counter = i;
                }
            }

            return [
                MetaKeyComponent.apikey && MetaKeyComponent.xsecret
                ? m('div', m('table', {width: '100%'}, [
                    m('tr', m('td[colspan=3]', m('div', arr))),
                    m('tr', [
                        m('td[width=40%]'),
                        m('td', m('div', m('span', {
                            style: {
                                cursor: 'pointer', 'text-decoration': 'underline', 'text-decoration-style': 'dotted',
                                color: 'blue', 'font-size': '13px', 'padding-left': '22px'
                            },
                            onclick: function() {
                                Object.keys(MetaSettingComponent.obj).length == 0
                                    ? MetaSettingComponent.setCounter(1)
                                    : MetaSettingComponent.setCounter(++MetaSettingComponent.counter);
                                MetaSettingComponent.obj[MetaSettingComponent.counter] = {};
                                MetaSettingComponent.obj[MetaSettingComponent.counter] = { base: 0, table: 0, type: 0, sourceField: 0 };
                                MetaSettingComponent.show = MetaSettingComponent.counter;
                            }
                        }, lang['Add_table']))),
                        m('td')
                    ]),
                    m('tr', m('td[colspan=3]',
                        (MetaSettingComponent.show == 0 ? m('div') : m(TableComponent, {
                            num: MetaSettingComponent.show,
                            settings: MetaSettingComponent.settings[MetaSettingComponent.show]
                        }))
                    )),
                    m('tr', m('td[colspan=3][align=center]', m('div', m('input[type=button]', {
                        class: 'btn btn-default btn-sm',
                        value: lang['Save'],
                        onclick: function() { MetaSettingComponent.saveSettings(); }
                    }))))
                ]))
                : ''
            ];
        }
    }
}

m.mount(document.getElementById('setting-component'), SettingComponent);
