'use strict';

export function SettingsBlock(metadata) {
    // console.log(metadata);
    let settings = {
        api_key: metadata?.settings?.api_key || "",
        x_secret: metadata?.settings?.api_key || "",
        request_count: metadata?.settings?.request_count || {},
        set: metadata?.settings?.set || []
    };
    let tables = metadata?.tables || {};
    let dadata_fields = metadata?.dadata_fields;
    let show = 0;

    const DADATA_BASE = {
        0: "", 1: "Компании", 2: "Адреса", 3: "Банки",
    };

    function createHelpBtn(str_id) {
        return m('span[class=help_bt]', {
            oninit: checkHelpButtonsOnCurrentPage(),
            oncreate: function() { bind_help_bt('dadata_demo'); },
            h_id: str_id
        });
    }

    function genid() {
        var dt = new Date().getTime();
        var mask = 'ixxxyxxx';  //'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
        return mask.replace(/[xy]/g, function(c) {
            var r = (dt + Math.random()*16)%16 | 0;
            dt = Math.floor(dt/16);
            return (c=='x' ? r :(r&0x3|0x8)).toString(36);
        });
    }

    function getDadataType(base, type) {
        let d_type = {};
        switch (base) {
            case "1":
                d_type = {0: "", 1: "ИНН", 2: "Название"};
                return [...Object.keys(d_type)].map(key => m('option',{value:key,selected:type == key},d_type[key]));
            case "2":
                d_type = {0: "", 3: "Адрес"};
                return [...Object.keys(d_type)].map(key => m('option',{value:key,selected:type == key},d_type[key]));
            case "3":
                d_type = {0: "", 4: "Название", 5: "БИК"};
                return [...Object.keys(d_type)].map(key => m('option',{value:key,selected:type == key},d_type[key]));
        }
    }

    function baseElementForShowTable() {
        return {
            view: function(vnode) {
                return m('tr', [
                    m('td', {align: 'right', width: '45%'}, [
                        m('span', vnode.attrs.name),
                        createHelpBtn(vnode.attrs.h_id),
                        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: vnode.attrs.onchange instanceof Function ? vnode.attrs.onchange : function() {}
                        }, vnode.attrs.options),
                    ])
                ])
            }
        }
    }

    function allOtherFields() {
        return {
            view: function(vnode) {
                // console.log(vnode.attrs);
                let el = vnode.attrs.el;
                let base_fields = vnode.attrs.base_fields;
                let arr = new Array();
                let e_fields = tables[el.table]['fields'];

                // если тип="адрес", то докину параметр по умолчанию в настройки
                if (el.type == 3) el.unrestricted_value = el.sourceField;

                for (let item in base_fields) {
                    if (el.type == 2 && i == "value") { el.value = el.sourceField; continue; }


                    if (typeof base_fields[item] == 'string') {
                        if (typeof el[item] != 'undefined') el[item] = el[item] != 0 ? el[item] : 0;

                        arr.push(m('tr', [
                            m('td', {align: 'right', width: '45%'}, base_fields[item]),
                            m('td', m('select', {
                                class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                                onchange: function(e) {
                                    el[item] = e.target.value;
                                }
                            }, [0, ...Object.keys(e_fields)].map(key => m("option",{
                                value: key == 0 ? 0 : e_fields[key]['id'],
                                selected: key == 0 ? (el[item] == key) : (el[item] == e_fields[key]['id'])
                            }, (key == 0 ? "" : e_fields[key]['name_field'])))))
                        ]));
                    } else if(typeof base_fields[item] == 'object') {
                        for (let item2 in base_fields[item]) {
                            if (typeof base_fields[item][item2] == 'object') {
                                for (let item3 in base_fields[item][item2]) {
                                    if (typeof el[item +'*'+ item2 +'*'+ item3] != 'undefined') {
                                        el[item +'*'+ item2 +'*'+ item3] = el[item +'*'+ item2 +'*'+ item3] != 0 ? el[item +'*'+ item2 +'*'+ item3] : 0;
                                    }

                                    arr.push(m('tr', [
                                        m('td', {align: 'right', width: '45%'}, base_fields[item][item2][item3]),
                                        m('td', m('select', {
                                            class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                                            onchange: function(e) {
                                                el[item +'*'+ item2 +'*'+ item3] = e.target.value;
                                            }
                                        }, [0, ...Object.keys(e_fields)].map(key => m("option",{
                                            value: key == 0 ? 0 : e_fields[key]['id'],
                                            selected: key == 0 ? (el[item] == key) : (el[item +'*'+ item2 +'*'+ item3] == e_fields[key]['id'])
                                        }, (key == 0 ? "" : e_fields[key]['name_field'])))))
                                    ]));
                                }
                            } else {
                                if (el.type == 1 && item2 == "inn") { el[item +'*'+ item2] = el.sourceField; continue; }
                                if (typeof el[item +'*'+ item2] != 'undefined') {
                                    el[item +'*'+ item2] = el[item +'*'+ item2] != 0 ? el[item +'*'+ item2] : 0;
                                }

                                arr.push(m('tr', [
                                    m('td', {align: 'right', width: '45%'}, base_fields[item][item2]),
                                    m('td', m('select', {
                                        class: 'form-control select-cat acc_sel_item conf_navigation_gray_text',
                                        onchange: function(e) {
                                            el[item +'*'+ item2] = e.target.value;
                                        }
                                    }, [0, ...Object.keys(e_fields)].map(key => m("option",{
                                        value: key == 0 ? 0 : e_fields[key]['id'],
                                        selected: key == 0 ? (el[item] == key) : (el[item +'*'+ item2] == e_fields[key]['id'])
                                    }, (key == 0 ? "" : e_fields[key]['name_field'])))))
                                ]));
                            }
                        }
                    }
                }

                return arr;
            }
        }
    }

    function show_table() {
        return {
            view: function(vnode) {
                // console.log(vnode.attrs);
                let el = vnode.attrs.item;

                return m('div', m('table[width=100%]', [

                    m(baseElementForShowTable, {                                            /* base - ПОЛЕ ВЫБОРА БАЗЫ */
                        name: 'База для поиска',
                        h_id: 'module_dadata_base',
                        onchange: function(e) {
                            settings.set = settings.set.map(function(item) {
                                if (item.id != show) return item;
                                if (e.target.value == 0) return { id: item.id, base: 0}
                                return {
                                    id: item.id || '',
                                    base: e.target.value,
                                    type: 0,
                                    table: item?.table || 0,
                                    sourceField: item?.sourceField || 0
                                };
                            });
                        },
                        options: [...Object.keys(DADATA_BASE)].map(key => m('option',{value: key, selected: key == el.base}, DADATA_BASE[key]))
                    }),


                    !el.base ? null : m(baseElementForShowTable, {                          /* type - ЧТО СОХРАНЯТЬ В ПОЛЕ ПОИСКА */
                        name: 'Что сохранять в поле поиска',
                        h_id: 'module_dadata_base',
                        onchange: function(e) {
                            settings.set = settings.set.map(function(item) {
                                if (item.id != show) return item;
                                return {
                                    id: item.id || '',
                                    base: item.base,
                                    type: e.target.value,
                                    table: item?.table || 0,
                                    sourceField: item?.sourceField || 0
                                };
                            });
                        },
                        options: getDadataType(el.base, el.type)
                    }),


                    !el.base ? null : m(baseElementForShowTable, {                          /* table - ПОЛЕ ВЫБОРА ТАБЛИЦЫ */
                        name: lang['Sync_select_table'],
                        h_id: 'module_dadata_table',
                        onchange: function(e) {
                            settings.set = settings.set.map(function(item) {
                                if (item.id != show) return item;
                                return {
                                    id: item.id || '',
                                    base: item.base,
                                    type: item.type,
                                    table: e.target.value,
                                    sourceField: 0
                                };
                            });
                        },
                        options: [0, ...Object.keys(tables)].map(function(item) {
                            return m('option', {
                                value: item == 0 ? 0 : tables[item]['table_id'],
                                selected: item == 0 ? true : (tables[item]['table_id'] == el.table)
                            }, item == 0 ? "" : tables[item]['table_name'])
                        })
                    }),

                    (!el.table || el.table == "0") ? null : m(baseElementForShowTable, {    /* sourceField - ПОЛЕ ПОИСКА */
                        name: "Поле поиска",
                        h_id: 'module_dadata_field_search',
                        onchange: function(e) {
                            settings.set = settings.set.map(function(item) {
                                if (item.id != show) return item;

                                item.sourceField = e.target.value;
                                return item;
                            });
                        },
                        options: [0, ...Object.keys(tables[el.table]['fields'])].map(function(key) {
                            let fields = tables[el.table]['fields'];
                            return m('option', {
                                value: key == 0 ? 0 : fields[key]['id'],
                                selected: key == 0 ? true : (fields[key]['id'] == el.sourceField)
                            }, key == 0 ? "" : fields[key]['name_field'])
                        })
                    }),

                    (!el.sourceField || el.sourceField == "0") ? null : m('tr',             /* ОСТАЛЬНЫЕ ПОЛЯ ДЛЯ СОПОСТАВЛЕНИЯ ДАДАТЫ С КБ */
                        m('td[colspan=2]', {width: '100%'}, m('div', [
                            m('table', {width:'100%', cellpadding: "0", cellspacing: "0", border: "0"}, m(allOtherFields, {
                                el, base_fields: el.base == 1 ? (dadata_fields?.party || {}) : (
                                    el.base == 2 ? (dadata_fields?.address || {}) : (dadata_fields?.bank || {})
                                )
                            }))
                        ]))
                    )
                ]));
            }
        }
    }

    return {
        view: function() {
            return [
                m('div', m('table', {width: '100%'}, [
                    m('tr', m('td[colspan=3][align=center]', {style:'padding:0'}, [     /* СТАТИСТИКА */
                        m('p', {style:'margin:0;padding:0;'}, 'За сегодня выполнено запросов: ' + (settings?.request_count?.count || 1))
                    ])),
                    m('tr', m('td[colspan=3]', m('hr'))),

                    m('tr', m('td[colspan=3]', settings.set.map(function(item) {        /* СПИСОК НАСТРОЕННЫХ ТАБЛИЦ */
                        return m('div', {style: {'padding-bottom': '5px'}}, [
                            m('div', m('table[width=100%]', m('tr', [
                                m('td[width=40%]'),
                                m('td', [
                                    m('a', {
                                        onclick: function() {
                                            settings.set = settings.set.filter(el => el.id != item.id); show = 0;
                                        }
                                    }, 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() { show = show == item.id ? 0 : item.id; }
                                    }, ((!item.table || item.table == "0") ? lang['Table'] + ':' : (lang['Table'] + ': "' + tables[item.table]['table_name'] + '"')))
                                ]),
                            ])))
                        ]);
                    }))),

                    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() {
                                show = genid();
                                settings.set.push({ id: show });
                            }
                        }, lang['Add_table']))),
                        m('td')
                    ]),

                    show == 0 ? null : m('tr', m('td[colspan=3]', m(show_table, {       /* НАСТРОЙКА */
                        item: settings.set.filter((item) => item.id == show)[0]
                    }))),

                    m('tr', m('td[colspan=3][align=center]', m('input[type=button]', {  /* СОХРАНИТЬ */
                        style: 'margin-top:20px',
                        class: 'btn btn-default btn-sm',
                        value: lang['Save'],
                        onclick: function() {
                            var data = new FormData();
                            data.append('csrf', csrf);
                            data.append('save_dadata_demo', true);
                            data.append('settings', JSON.stringify(settings));
                            m.request({
                                method: 'POST',
                                url: 'modules/dadata_demo/request.php',
                                data: data
                            })
                            .then(function() {
                                displayNotification(lang['Done'], 1);
                                window.location.reload();
                            })
                        }
                    })))
                ]))
            ];
        }
    }
}
