let _scenarioData     = [];
let _scenarioTabs     = null;
let _tabNameData      = [];
const commonUri       = '/api/vms/monitoring/edit/scenario/scenario';
let _intervalMap      = new Map();
let _magnigication    = 1.0;
let _imageMap         = new Map();
let _divMap           = new Map();
const _dataMap        = new Map();
let _selectedBox      = null;
let _deselectInterval = [];
let _selectedInterval = [];
const _userId         = window.opener.$userId;
let _tempColumnArr    = ['brgh_val', 'cbox_tmpr'];

$(() =>{
    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, idx, c){
            c.css('display', 'flex');
            const deselect = $(`<div class='deselect-div-box b0 dx-theme-border-color'></div>`);
            const selected = $(`<div class='selected-div-box b0 dx-theme-border-color'></div>`);
            let deselectHeight = 0;
            let selecedtHeight = 0;
            let count = 5;
            let deselctDiv = null;
            let selectDiv  = null;

            //한줄 5개짜리 모니터링 화면 생성
            for(let idx in e.text){
                
                //idx가 5의 배수일때
                if(idx % count === 0){
                    
                    //기존 div가 있다면 append 실행
                    if(deselctDiv){
                        deselect.append(deselctDiv);
                    }
                    
                    //div 새로 만들기
                    deselctDiv = $('<div class="flex">');
                    
                    //5개 중 높이는 가장 높이가 큰 것으로 설정
                    for(let ii = 0; ii < count; ii++){
                        if(deselectHeight <= e.height[ii]) deselectHeight = e.height[ii];
                    }
                    deselctDiv.css('height', deselectHeight);
                }
                deselctDiv.append(e.text[idx]);

                //마지막 순번이면 append
                if( idx == e.text.length - 1){
                    deselect.append(deselctDiv);
                }
            };

            //edit 모드를 위한 한줄 4개짜리 모니터링 화면 생성
            for(let idx in e.text){

                //count가 4의 배수 일때
                if(idx % 4 === 0){

                    //기존 div가 있다면 append 실행
                    if(selectDiv){
                        selected.append(selectDiv);
                    }

                    //div 새로 만들기
                    selectDiv = $('<div class="flex">');

                    //4개중 가장 높은 높이로 설정
                    for(let ii = 0; ii < 4; ii++){
                        if(selecedtHeight <= e.height[ii]) selecedtHeight = e.height[ii];
                    }
                    selectDiv.css('height', selecedtHeight);
                }
                
                // 기존하고 동일한 요소로 하면 안되므로 새로운 요소를 만들어야 함(요소 복사);
                let cloneDiv = e.text[idx].clone();
                
                //클릭시 edit 모드를 실행할 click 이벤트 설정
                titleClickEvent(cloneDiv, e, idx);
                
                selectDiv.append(cloneDiv);
                
                //마지막 순번이면 append
                if( idx == e.text.length - 1){
                    selected.append(selectDiv);
                }
            };
            selected.css('display', 'none');
            deselect.css('display', 'flex');
            c.append(deselect, selected, e.editBox);
            return c;
        },
        onSelectionChanged(e){
            //화면 초기화
            clickCss('flex','none', 'none', '100%', 'calc(100% / 5)');
            //셀렉트 된 박스 초기화
            if(_selectedBox){
                _selectedBox[0].children().eq(0).removeClass('dx-theme-accent-as-background-color');
                _selectedBox[1].children().eq(0).removeClass('dx-theme-accent-as-background-color');
                _selectedBox = null;
            }
        },
    }).dxTabPanel('instance');
    
    fetchBaseData();
})

function titleClickEvent(clone, e, idx){
    
    clone.children().eq(0).on('click',function(){
        if (_selectedBox) {
            _selectedBox[0].children().eq(0).removeClass('dx-theme-accent-as-background-color');
            _selectedBox[1].children().eq(0).removeClass('dx-theme-accent-as-background-color');
        }
        if (_selectedBox && _selectedBox[1] === clone && $('.deselect-div-box').css('display') === 'none') {
            clickCss('flex', 'none', 'none', '100%', 'calc(100% / 5)');
        }
        else {
            clickCommon(e, idx, clone, $(this));
        }
    });

    e.text[idx].children().eq(0).on('click', function(){
        clickCommon(e, idx, clone, $(this));
    });
}

function clickCommon(e, idx, clone, title) {
    //css 설정
    clickCss('none', 'flex', 'flex', 'calc(100% / 5 * 4)', 'calc(100% / 4)');
    let key = title.text().substring(1, title.text().length);
    let obj = _dataMap.get(e.id).get(key);

    $(title).addClass('dx-theme-accent-as-background-color');
    $(clone).children().eq(0).addClass('dx-theme-accent-as-background-color');
    _selectedBox = [e.text[idx], clone];

    let data = [];
    getData('/api/vms/common/vms-form/dspl-prst', data, {id:obj.vms_ctlr_nmbr});

    if(data.length > 0){
        data = data[0];

        e.textColumns.map((item)=>{
            console.log('item.column' + data[0][item.column])
            if (_tempColumnArr.includes(item.column) && data[0][item.column] === 255) {
                setValue(item.box, '-');
            }
            else {
                setValue(item.box, data[0][item.column]);
            }
        });
        const dsplDt = $('.dspl_dt');
        dsplDt.text(getParseDateTime(data[0]['dspl_dt']));

        let color = data[0].cmnc_stts_desc === '통신두절'? 'red' : '#fff';
        dsplDt.css('color', color);

        e.table.option('dataSource', data[0].msgs);
    }
}

function clickCss(deselectVal, selectVal, editVal, paddingVal, phaseVal){
    $('.deselect-div-box').css('display', deselectVal);
    $('.selected-div-box').css('display', selectVal);
    $('.edit-box').css('display', editVal);
    $('.padding-box').css('width', paddingVal);
    $('.phase-box').css('width', phaseVal);
}


let _listTimer = null;
async function fetchBaseData(){
    // 전체 표출 메시지 조회
    getDataAsync('/api/vms/monitoring/edit/scenario/module/list', fetchTabs);
    if (_listTimer) {
        window.clearInterval(_listTimer);
    }
    _listTimer = setInterval(() => {
        getDataAsync('/api/vms/monitoring/edit/scenario/module/list', fetchTabs);
    }, 60000);
}


function fetchTabs(jsonData){
    let dataSource   = [];
    let tableDataArr = [];
    
    // 전체 모니터링 화면 목록
    let data = [];
    let dataMap = new Map();
    getData('/api/vms/monitoring/stts', data);
    if (data[0].length > 0) {
        data = data[0];
        data.forEach((obj) => {
            dataMap.set(obj.vms_ctlr_nmbr, obj);
        });
    }
    // 모니터링 화면 목록을 이용해 모니터링 이름별 탭을 생성
    jsonData.forEach((obj)=>{
        dataSource.push({
            id           : obj.monitoring_nm,
            name         : obj.monitoring_nm,
            text         : [],
            msgs         : [],
            height       : [],
            position     : [],
            phase        : [],
            title        : [],
            editBox      : null,
            textColumns  : null,
            checkColumns : null,
            btn          : null,
            table        : null,
            select       : null,
            deselect     : null,
        });
        _dataMap.set(obj.monitoring_nm, new Map());
        // 모니터링 화면에 속한 VMS 제어기 목록 조회
        let scenarioData = [];
        getData('/api/vms/monitoring/edit/scenario/module/' + obj.monitoring_nm, scenarioData);
        // 제어기 목록을 순회하면서 전체 표출 메시지에서 해당 제어기의 내용을 추출
        let tableData = [];
        scenarioData[0].forEach((scenario) => {
            tableData.push(dataMap.get(scenario.vms_ctlr_nmbr));
        });
        tableDataArr.push(tableData);
    });

    for(let idx in tableDataArr){
        const tableData = tableDataArr[idx]
        tableData.sort(function(a,b){
            return a.vms_ctlr_nmbr - b.vms_ctlr_nmbr;
        });
        _imageMap.set(idx, new Map());
        tableData.forEach((obj)=>{

            _dataMap.get(jsonData[idx].monitoring_nm).set(obj.vms_nm, obj);
            const dsplDt = getParseDateTime(obj.provide_time) 
           
            const imageNm = obj.cmnc_stts_cd === 'CMS0' ? 'true' : 'false';
            
            let operClass = '';
            if (obj.oper_mode_desc === '자동') {
                operClass = 'green';
            } 
            else {
                operClass = obj.oper_mode_desc === '고정' ? 'wanrning' : 'yellow';
            }

            let powerClass = obj.pwer_stts_cd;
            if (!obj.pwer_stts_cd) powerClass = 'gray';

            let modlClass = obj.modl_stts_cd;
            if (!obj.modl_stts_cd) modlClass = 'gray';
            
            let doorClass = obj.cbox_door_stts_cd;
            if (! obj.cbox_door_stts_cd) doorClass = 'gray';
        
            let hetrClass = obj.hetr_stts_cd;
            if (!obj.hetr_stts_cd) hetrClass = 'gray';

            let fanClass = obj.fan_stts_cd;
            if (!obj.fan_stts_cd) fanClass = 'gray';
            
            let tempClass = '';
            if (obj.cbox_tmpr === 255 || obj.cbox_tmpr === null || obj.cbox_tmpr === "-") {
                obj.cbox_tmpr = '-';
                tempClass = 'gray';
            }
            let modleView = $('<div class="module-box">');
            modleView.css('width', '100%');
            modleView.css('height', obj.vms_hght + 10 + 'px');
            /**
             * {
    "vmsctlrid": "VMS10080",
    "vmsnm": "고덕-ATMS-021",
    "vms_ctlr_nmbr": 1008,
    "updt_dt": "20220921141704",
    "cmnc_stts_cd": "CMS1",
    "pwer_stts_cd": null,
    "modl_stts_cd": "PAS2",
    "cbox_door_stts_cd": "CDS2",
    "fan_stts_cd": "PAS2",
    "hetr_stts_cd": "HTS2",
    "cbox_tmpr": 255,
    "brgh_val": 0,
    "comm_stts_cd": null,
    "modl_stts": null,
    "pwer_stts": null,
    "vms_wdth": 256,
    "vms_hght": 192,
    "rows": 12,
    "cols": 16,
    "modl_rows": 12,
    "modl_cols": 16,
    "powr_rows": 12,
    "powr_cols": 16,
    "cmnc_stts_desc": "UNKNOWN",
    "pwer_stts_desc": "-",
    "modl_stts_desc": "-",
    "cbox_door_stts_desc": "-",
    "fan_stts_desc": "-",
    "hetr_stts_desc": "-",
    "comm_stts_desc": null,
    "miss_stts_yn": "N",
    "coll_cnt": 100,
    "vms_type_cd": "VMP1",
    "vms_modl_type_cd": null,
    "oper_mode": "A",
    "oper_mode_desc": "자동",
    "vms_cmnc_err_bass_val": null,
    "vms_nght_brgh_step": null,
    "vms_week_brgh_step": null,
    "vms_phse_chng_cycl": null,
    "vms_modl_err_rate": null,
    "vms_max_phse_num": 14,
    "fan_mtns_tmpr": null,
    "hetr_mtns_tmpr": null,
    "strm_sesn_nm": "rtsp://admin:admin13579@172.30.17.32/profile3/media.smp",
    "strm_http_addr": null,
    "strm_rtsp_addr": null,
    "vms_usag_type_desc": null,
    "vms_type_desc": "12단16열",
    "panl_on_time": "0000",
    "panl_off_time": "0000",
    "provide_time": "20220921141510",
    "provide_result": "N",
    "provide_svc": "Y",
    "provide_cnt": 3,
    "auto_total": 8,
    "auto_used": 8,
    "fixed_total": 0,
    "fixed_used": 0,
    "basic_total": 0,
    "basic_used": 0
  },
             */
            for ( let ii = 0; ii < obj.modl_rows; ii++ ){
                let height = Number(100 / obj.modl_rows).toFixed(2) + '%';
                let row = $('<div style="display:flex; width:95%;  height:' + height + ';">');
                for ( let jj = 0; jj < obj.modl_cols; jj++ ){
                    let color = '';
					let modelStts = null;
					if (obj.modl_stts) {	
						modelStts = obj.modl_stts.substring(jj, jj+1);
					}
					else {
						modelStts = "2";
					}

                    if ( "1" === modelStts ) {
                        color = 'green';
                    }
                    else if ( "0" === modelStts ) {
                        color = 'wanrning';
                    }
                    else {
                        color = 'gray';
                    }
                    let width = Number(100 / obj.modl_cols).toFixed(2) + '%';
                    row.append($('<div class="'+color+' dx-theme-border-color" style="width:' + width + '; height: '+obj.vms_hght+'; border:1px solid ;" ></div>'));
                }
                modleView.append(row);
            };

            height = 70 + obj.vms_hght;
            let div = $(
                        `<div class='phase-box dx-theme-border-color b0' style='height:${height}px;'>
                            <div class='phase-title dx-nav-item dx-theme-border-color' style='border-bottom:1px solid;' title='${obj.vms_ctlr_nmbr} [${obj.vms_ctlr_id}]\n${obj.vms_nm}'><img src='/images/op/icon/${imageNm}.png' width='20px' height='20px' align='center'> ${obj.vms_nm}</div>
                            <div class='image-box' style='width:100%; height:${obj.vms_hght + 20}px'>
                            </div>
                            <div class='state-box'>
                                <div class='${doorClass}  b0 dx-theme-border-color' title='도어 상태'>${obj.cbox_door_stts_desc}</div>
                                <div class='${fanClass}   b0 dx-theme-border-color' title='팬 동작 상태'>${obj.fan_stts_desc}</div>
                                <div class='${hetrClass}  b0 dx-theme-border-color' title='히터 가동 상태'>${obj.hetr_stts_desc}</div>
                                <div class='${modlClass}  b0 dx-theme-border-color' title='모듈'>${obj.modl_stts_desc}</div>
                                <div class='${powerClass} b0 dx-theme-border-color' title='모듈 전원 상태'>${obj.pwer_stts_desc}</div>
                                <div class='${tempClass}  b0 dx-theme-border-color' title='함체 온도'>${obj.cbox_tmpr}</div>
                                <div class='${operClass}  b0 dx-theme-border-color' title='운영 모드'>${obj.oper_mode_desc}</div>
                            </div>
                        </div>`
            );
            $(div).children().eq(1).append(modleView);
            dataSource[idx]['text'].push(div);
            dataSource[idx]['height'].push(height);
            dataSource[idx]['phase'].push($(div).children().eq(0).children().eq(1));
            dataSource[idx]['title'].push($(div).children().eq(0));
            _imageMap.get(idx).set('div', div);
        });

        let editArr = editBox();
        dataSource[idx]['editBox'] = editArr[0];
        dataSource[idx]['textColumns'] = editArr[1];
        dataSource[idx]['checkColumns'] = editArr[2];
        dataSource[idx]['btn'] = editArr[3];
        dataSource[idx]['table'] = editArr[4];
    }
    _scenarioTabs.option('dataSource', dataSource);
};

function editBox(){

    //박스 타이틀 선택 시 보이는 edit 화면
    const editBox = $(`
    <div class='edit-box b1 b2 b4 dx-theme-border-color'>
        <div class='serve-title dx-nav-item b2 dx-theme-border-color'>VMS 상태정보</div>
        <div class='vms-info b2 dx-theme-border-color'>
            <div>
                <div class='label'>VMS ID</div>
                <div class="ml-5">
                    <div class="vms_id tc"></div>
                </div>
                <div class='label ml-5'>VMS 유형</div>
                <div class="ml-5">
                    <div class='tc'></div>
                </div>
            </div>
            <div>
                <div class='label'>VMS 명칭</div>
                <div class="ml-5">
                    <div></div>
                </div>
            </div>
            <div>
                <div class='label'>운영모드</div>
                <div class="ml-5 ft-text">
                    <div class='tc'></div>
                </div>
                <div class='label ml-5'>VMS 통신</div>
                <div class="ml-5">
                    <div class='tc'></div>
                </div>
            </div>
        </div>
        <div class='module-info b2 dx-theme-border-color'>
            <div class='serve-title dx-nav-item b2 dx-theme-border-color'>모듈상태</div>
            <div>
                <div class="label">상태</div>
                <div class="ml-5">
                    <div class='tc'></div>
                </div>
                <div class="ml-10">전원 상태</div>
                <div class="ml-5" style='width:50px;'>
                    <div class='tc'></div>
                </div>
                <div class="ml-10">휘도값</div>
                <div class="ml-5">
                    <div class='tc'></div>
                </div>
            </div>
        </div>
        <div class='door-info b2 dx-theme-border-color'>
            <div class='serve-title dx-nav-item b2 dx-theme-border-color'>함체상태</div>    
            <div>
                <div>
                    <div class='label'>도어 상태</div>
                    <div class="ml-5 ft-text">
                        <div class='tc'></div>
                    </div>
                    <div class='label'>팬상태</div>
                    <div class="ml-5">
                        <div class='tc'></div>
                    </div>
                </div>
                <div>
                    <div class='label'>히터상태</div>
                    <div class="ml-5 ft-text">
                        <div class='tc'></div>
                    </div>
                    <div class='label'>온도값</div>
                    <div class="ml-5">
                        <div class='tc'></div>
                    </div>
                </div>
            </div>
        </div>
        <div class='btn-box b2 dx-theme-border-color'>
            <div>
                <div></div>
            </div>
            <div>
                <div></div>
            </div>
            <div>
                <div></div>
            </div>
            <div>
                <div></div>
            </div>
        </div>
        <div class='serve-title dx-nav-item b2 dx-theme-border-color'>VMS 표출 메시지 스케줄</div>
        <div class='dspl_dt'>제공시각:<span class='dspl_dt_text'></span></div>
        <div class='schedule-list'>
            <div></div>
        </div>
        <div class='btn-box'>
            <div></div>
        </div>
    </div>
    `);

    const vmsInfo   = $(editBox).children().eq(1);
    const vmsCtlrId = vmsInfo.children().eq(0).children().eq(1).children().eq(0);
    const vmsType = vmsInfo.children().eq(0).children().eq(3).children().eq(0);
    const vmsNm     = vmsInfo.children().eq(1).children().eq(1).children().eq(0);
    const operMode  = vmsInfo.children().eq(2).children().eq(1).children().eq(0);
    const cmncStts  = vmsInfo.children().eq(2).children().eq(3).children().eq(0);

    const modlInfo  = $(editBox).children().eq(2).children().eq(1);
    const modlStts  = modlInfo.children().eq(1).children().eq(0);
    const pwerStts  = modlInfo.children().eq(3).children().eq(0);
    const brghVal   = modlInfo.children().eq(5).children().eq(0);

    const doorInfo  = $(editBox).children().eq(3).children().eq(1);
    const doorStts  = doorInfo.children().eq(0).children().eq(1).children().eq(0); 
    const fanStts   = doorInfo.children().eq(0).children().eq(3).children().eq(0); 
    const hetrStts  = doorInfo.children().eq(1).children().eq(1).children().eq(0); 
    const cboxTemp  = doorInfo.children().eq(1).children().eq(3).children().eq(0); 

    const btnBox      = $(editBox).children().eq(4)
    const onCheck     = btnBox.children().eq(0).children().eq(0);
    const offCheck    = btnBox.children().eq(1).children().eq(0);
    const resetCheck  = btnBox.children().eq(2).children().eq(0);
    const sendBtn     = btnBox.children().eq(3).children().eq(0);
    $(editBox).children().eq(6)
    
    //텍스트 상자 옵션
    const textColumns = [
        { 
            column:'vms_ctlr_id',
            position : vmsCtlrId,
            box      : null,
            width    : 110,
            height   : 20,
            stylingMode : 'outlined',
        },
        { 
            column:'vms_type_desc',
            position : vmsType,
            box      : null,
            width    : 90,
            height   : 20,
            stylingMode : 'outlined',
        },
        { 
            column:'vms_nm',
            position : vmsNm,
            box      : null,
            width    : 270,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'oper_mode_desc',
            position : operMode,
            box      : null,
            width    : 50,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'cmnc_stts_desc',
            position : cmncStts,
            box      : null,
            width    : 90,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'modl_stts_desc',
            position : modlStts,
            box      : null,
            width    : 50,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'pwer_stts_desc',
            position : pwerStts,
            box      : null,
            width    : 50,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'brgh_val',
            position : brghVal,
            box      : null,
            width    : 50,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'cbox_door_stts_desc',
            position : doorStts,
            box      : null,
            width    : 50,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'fan_stts_desc',
            position : fanStts,
            box      : null,
            width    : 50,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'hetr_stts_desc',
            position : hetrStts,
            box      : null,
            width    : 50,
            height   : 20,
            stylingMode : 'outlined',
        }, 
        { 
            column:'cbox_tmpr',
            position : cboxTemp,
            box      : null,
            width    : 50,
            height   : 20,
            stylingMode : 'outlined',
        }, 
    ];

    //체크박스 상자 옵션
    const checkColumns = [
        {
            position : onCheck,
            text     : '전광판 ON',
            box      : null,
        },
        {
            position : offCheck,
            text     : '전광판 OFF',
            box      : null,
            
        },
        {
            position : resetCheck,
            text     : '제어기 리셋',
            box      :  null,
        },
    ]

    //전송 버튼 박스
    creatBtn(sendBtn, 'check', '전송', '전송', 'outlined', sendBtnClick, null, false, true);
    
    //화면 관리 버튼 박스
    creatBtn($(editBox).children().eq(8).children().eq(0), 'edit', '화면관리', '화면관리', 'outlined', editViewPopup, null, false, true);

    //edit 화면 하단 VMS 폼 이미지 리스트
    let editVmsFormList = $(editBox).children().eq(7).children().eq(0).width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : 'phase',
        noDataText              : '표출할 정보가 없습니다.',
        scrolling               : {
            mode : 'standard',
        },
        selection: {
            mode: 'single',
        },
        paging: {
            enabled: true,
            pageSize: 1000,
        },
        sorting  : {
            showSortIndexes : false,
            mode            : 'none',
        },
        columns:[
                    {
                        dataField    : "phase",
                        caption      : "S",
                        alignment    : "center",
                        cssClass     : 'no-padding',
                    },
                    {
                        dataField    : "vms_dspl_msg_imag",
                        caption      : "표출메시지",
                        alignment    : "center",
                        cssClass     : 'no-padding',
                        width        : 330,
                        cellTemplate(c,e){
                            c.css('padding','3px')
                            const imgSrc = 'data:image/png;base64,'+ e.displayValue
                            const image = $('<img src="'+imgSrc+'" >').css('width','100%');
                            return c.append(image);
                        }
                    },
                ],
    }).dxDataGrid('instance');

    //체크 박스 세팅
    checkColumns.map((item)=>{
        item.box = item.position.dxCheckBox({
            stylingMode : 'outlined',
            text        : item.text,
        }).dxCheckBox('instance');
    });
    
    //체크 박스 꺼짐 방지 이벤트
    $(onCheck).on('click',()=>{
        if(!getValue(checkColumns[0].box)) setValue(checkColumns[0].box, true);
    });
    $(offCheck).on('click',()=>{
        if(!getValue(checkColumns[1].box))setValue(checkColumns[1].box, true);
    })
    $(resetCheck ).on('click',()=>{
        if(!getValue(checkColumns[2].box))setValue(checkColumns[2].box, true);
    })
    
    //체크박스 처음 값 세팅
    setValue(checkColumns[0].box, true);
    
    //체크박스 선택시 나머지 체크 박스 값 초기화
    checkColumns[0].box.on('valueChanged',(e)=>{
        if (getValue(checkColumns[1].box)) setValue(checkColumns[1].box, !e.value)
        if (getValue(checkColumns[2].box)) setValue(checkColumns[2].box, !e.value)
    });
    checkColumns[1].box.on('valueChanged',(e)=>{
        if (getValue(checkColumns[0].box)) setValue(checkColumns[0].box, !e.value)
        if (getValue(checkColumns[2].box)) setValue(checkColumns[2].box, !e.value)
    });
    checkColumns[2].box.on('valueChanged',(e)=>{
        if (getValue(checkColumns[0].box)) setValue(checkColumns[0].box, !e.value)
        if (getValue(checkColumns[1].box)) setValue(checkColumns[1].box, !e.value)
    });

    //텍스트 박스 세팅
    textColumns.map((item)=>{
        item.box = item.position.dxTextBox({
            width       : item.width,
            height      : item.height,
            stylingMode : item.stylingMode,
            readOnly    : true,
        }).dxTextBox('instance');
    });

    return [editBox, textColumns, checkColumns, sendBtn, editVmsFormList];
}

function sendBtnClick() {
    if (!_selectedBox) {
        return alertWarning('VMS가 선택되지 않았습니다.<br>VMS 목록에서 VMS를 선택하십시오.<br>현재 통신이 비정상적인 VMS는 선택하실 수 없습니다.');
    }
    
    let title         = $(_selectedBox[0]).children().eq(0).text();
    let key           = title.substring(1, title.length);
    let id            = _scenarioTabs.option('selectedItem').id;
    let checkColumns  = _scenarioTabs.option('selectedItem').checkColumns;
    let obj           = _dataMap.get(id).get(key);
    
    if (obj.cmnc_stts_desc === '통신두절') {
        return alertWarning('VMS가 선택되지 않았습니다.<br>VMS 목록에서 VMS를 선택하십시오.<br>현재 통신이 비정상적인 VMS는 선택하실 수 없습니다.');
    }
    
    let onVal  = getValue(checkColumns[0].box);
    let offVal = getValue(checkColumns[1].box);
    let resetVal = getValue(checkColumns[2].box);
    let result = '';
    if (onVal){
        result = postInsertUpdate('/api/vms/control/power/' + obj.vms_ctlr_nmbr, {user_id:_userId, value : 0});
    }
    else if (offVal) {
        result = postInsertUpdate('/api/vms/control/power/' + obj.vms_ctlr_nmbr, {user_id:_userId, value : 1});
    }
    else if (resetVal) {
        result = postInsertUpdate('/api/vms/control/reset/' + obj.vms_ctlr_nmbr, {user_id:_userId, value : 0});
    }

    if(result > 0){
        fetchBaseData();
        return alertConfirm('VMS 상태 정보가 저장 되었습니다.');
    }
    //return alertError('VMS 상태 정보가 저장되지 않았습니다.');

}

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