let _scenarioData = [];
let _scenarioTabs = null;
let _tabNameData  = [];
const commonUri   = '/api/vms/monitoring/edit/scenario/scenario';

$(() =>{
    creatBtn($(".close-btn"), "close", "닫기", "닫기", "outlined", () => window.close());

    _scenarioTabs = $('.scenario-tabs').width('100%').height('100%').dxTabPanel({
        dataSource       : null,
        selectIndex      : 0,
        loop             : false,
        animationEnabled : true,
        swipeEnabled     : false,
        noDataText       : '표출할 정보가 없습니다.',
        itemTitleTemplate: function(e){
        return $('<div style="height:29px; line-height:29px;">'+e.name+'</div>')
        },
        itemTemplate: function(e){
            const div = $(`<div class="padding-box"></div>`);
            e.table.width('100%');
            e.table.height('100%');
            div.append(e.table);
            return div;
        },
        onSelectionChanged(e){
            const selectedTab = e.addedItems[0] 
            if(selectedTab){
                let table = selectedTab.table.dxDataGrid('instance');
                table.clearSelection();
                table.option('focusedRowIndex', -1);
            }
        },
    }).dxTabPanel('instance');

    creatBtn($('.scenario-popup-btn'), 'edit', '화면관리', null, 'outlined', scenarioPopupEvent);
    creatBtn($('.search-btn'), 'refresh', '조회', null, 'outlined', searchEvent);
    fetchBaseData();
})

function fetchBaseData(){
    getDataAsync('/api/vms/monitoring/edit/scenario/scenario/list', fetchTabs)
}

function fetchTabs(jsonData){

    let dataSource   = [];
    let tableDataArr = [];
    let phaseArr     = [];
    let data = [];
    getData('/api/vms/common/vms-form/dspl-prst/all', data);
    if(data[0].length > 0)data = data[0];
    jsonData.forEach((obj)=>{
        let tableData = [];
        dataSource.push({
            id : obj.monitoring_nm,
            name : obj.monitoring_nm,
            table : null,
        });

        let scenarioData = [];
        getData( commonUri + '/' + obj.monitoring_nm, scenarioData);
        let phaseLength = 0;
        
        data.map((item)=>{
            scenarioData[0].map((scenario)=>{
                if ( scenario.vms_ctlr_nmbr === item.vms_ctlr_nmbr ){
                    if ( phaseLength < item.msgs.length ) phaseLength = item.msgs.length;
                    tableData.push(item);
                } 
            })
        })
        console.log(phaseLength);
        phaseArr.push(phaseLength);
        tableDataArr.push(tableData);
    });

    for(let idx in tableDataArr){
        let tableData = tableDataArr[idx];
        console.log(tableData);
        columns = [];
        columns.push({
            dataField    : "VMS",
            caption      : "VMS",
            alignment    : "center",
            width        : 250,
            cellTemplate(c,e){
                c.css('text-align', 'left');
                if (e.data.svc_yn === 'Y'){
                    for (let msg of e.data.msgs){
                        if(msg.dnld_yn === 'N'){
                            c.css('color', 'red');        
                            break;
                        }
                    }
                } 
                else {
                    c.css('color', 'red');
                }
                c.html(e.data.vms_ctlr_nmbr+' ['+ e.data.vms_ctlr_id + ']<br>' + e.data.vms_nm + '<br>' + e.data.dspl_dt + '<br>' + e.data.oper_mode_desc)
            }
        });
        for( let ii = 0; ii < phaseArr[idx]; ii ++){
            columns.push({
                dataField    : "Phase" + (ii+1),
                caption      : "Phase" + (ii+1),
                width        : 320,
                alignment    : "center",
                cellTemplate(c,e){
                    c.css('padding','3px');
                    c.css('width', tableData.vms_wdth);
                    c.css('height', tableData.vms_hght);
                    if(e.data.msgs[ii]){
                        const imgSrc = 'data:image/png;base64,' + e.data.msgs[ii].vms_dspl_msg_imag;
                        return c.append($('<img src="'+imgSrc+'">'));
                    }
                }
            })
        }

        let table = $("<div>").dxDataGrid({
            dataSource              : tableData,
            allowColumnReordering   : true,
            showColumnLines         : true,
            allowColumnResizing     : true,
            showBorders             : true,
            rowAlternationEnabled   : true,
            focusedRowEnabled       : true,
            columnAutoWidth         : true,
            keyExpr                 : 'vms_ctlr_nmbr',
            noDataText              : '표출할 정보가 없습니다.',
            selection               : {
                mode : 'single',
            },
            paging                  : {
                pageSize : 1000,
            },
            sorting: {
                mode : 'none',
            },
            columns : columns,
        });
 
        dataSource[idx].table = table;
    }
    _scenarioTabs.option('dataSource', dataSource);

};


function searchEvent(){
    fetchBaseData();
}

function scenarioPopupEvent(){
    window.open('./scenario-popup-manager.html', 'VMS 모니터링 화면 관리', 'width = 1200, height = 650, top = 150, left = 300, resizable=yes, scrollbars=no');
}