let _scenarioData     = [];
let _scenarioTabs     = null;
let _tabNameData      = [];
const commonUri       = '/api/vms/monitoring/edit/scenario/phase';
let _intervalMap      = new Map();
_intervalMap.set('interval', []);
let _magnigication    = 1.0;
const _divMap         = new Map();
const _dataMap        = new Map();
let _selectedBox      = null;
let _deselectInterval = [];
let _selectedInterval = [];
const _userId         = window.opener.$userId;
$(() =>{
    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;

            if(!_intervalMap.get(e.id)){
                _intervalMap.set(e.id, new Map());
            }
            let intervalBox = _intervalMap.get(e.id);
            intervalBox.set('selectedEventElement', new Array());
            intervalBox.set('deselectEventElement', new Array());
            let selectedElenmet = intervalBox.get('selectedEventElement');
            let deselectElenmet = intervalBox.get('deselectEventElement');
            clearMap();
            //한줄 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);
                }

                deselectElenmet.push([[...e.msgs[idx]], e.position[idx], e.phase[idx]]);
            };

            //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);
                }
                selectedElenmet.push([[...e.msgs[idx]], $(cloneDiv).children().eq(1).children().eq(0), $(cloneDiv).children().eq(0).children().eq(1)]);
            };
            selected.css('display', 'none');
            deselect.css('display', 'flex');
            //첫 생성시 인터벌 생성
            for(let idx in selectedElenmet){
                intervalEvent(selectedElenmet[idx][0], selectedElenmet[idx][1], selectedElenmet[idx][2], 0);
                intervalEvent(deselectElenmet[idx][0], deselectElenmet[idx][1], deselectElenmet[idx][2], 0);
            };
            c.append(deselect, selected, e.editBox);
            return c;
        },
        onSelectionChanged(e){
            //이전 탭
            const removeTab = e.removedItems[0];
            //현재 탭
            const selectedTab = e.addedItems[0];
            clearMap();
            //화면 초기화
            $('.edit-box').css('display', 'none');
            $('.padding-box').css('width','100%');
            $('.deselect-div-box').css('display', 'flex');
            $('.selected-div-box').css('display', 'none');
            $('.edit-box').css('display', 'none');
            $('.padding-box').css('width','100%');
            $('.phase-box').css('width','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;
            }

            if (removeTab) {
                if (selectedTab) {
                    let intervalBox = _intervalMap.get(selectedTab.id);
                    let selectedElenmet = intervalBox.get('selectedEventElement');
                    let deselectElenmet = intervalBox.get('deselectEventElement');
                    for(let idx in selectedElenmet){
                        intervalEvent(selectedElenmet[idx][0], selectedElenmet[idx][1], selectedElenmet[idx][2], 0);
                        intervalEvent(deselectElenmet[idx][0], deselectElenmet[idx][1], deselectElenmet[idx][2], 0);
                    }
                }
            }
        },
    }).dxTabPanel('instance');

    fetchBaseData();
})

function clearMap(){
    if (_intervalMap.get('interval') &&_intervalMap.get('interval').length > 0) {
        _intervalMap.get('interval').map((timer)=>{
            window.clearTimeout(timer);
        });
        _intervalMap.set('interval', []);
    }
}
//타이틀 클릭 이벤트
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 = Number(title.attr('id'));
    let obj = _dataMap.get(e.id).get(key);
    //선택 된 화면 모양을 위한 css 틀 설정
    $('#' + key).addClass('dx-theme-accent-as-background-color');
    $(clone).children().eq(0).addClass('dx-theme-accent-as-background-color');
    _selectedBox = [e.text[idx], clone];
    //텍스트 화면 값 세팅
    e.textColumns.map((item)=>{
        setValue(item.box, obj[item.column]);
    });

    //제공시각 입력
    $('.dspl_dt_text').text(getParseDateTime(obj['dspl_dt']));

    //통신 상태에 따른 제공시각 색상 설정
    let color = obj.cmnc_stts_desc === '통신두절'? 'red' : '#fff';
    $('.dspl_dt').css('color', color);

    //우측 화면 하단 VMS 표출메시지 스케줄 데이터 교체
    e.table.option('dataSource', obj.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);
}

//데이터 생성
function fetchBaseData(){
    // 전체 표출 메시지 조회
    getDataAsync('/api/vms/monitoring/edit/scenario/phase', fetchTabs);
    phaseInterval();
}

let _listTimer = null;
function phaseInterval() {
    if (_listTimer) {
        window.clearInterval(_listTimer);
    }
    _listTimer = setInterval(() => {
        getDataAsync('/api/vms/monitoring/edit/scenario/phase', fetchTabs);
    }, 60 * 1000);
}

//탭 생성
function fetchTabs(jsonData){
    let dataSource   = [];
    // 전체 모니터링 화면 목록
    let data = [];
    let dataMap = new Map();
    getData('/api/vms/common/vms-form/dspl-prst/all', data);
    if (data[0].length > 0) {
        data = data[0];
        data.map((obj) => {
            dataMap.set(obj.vms_ctlr_nmbr, obj);
        });
    }

    if (jsonData.length > 0) {
        for (let ii = 0; ii < jsonData.length; ii++) {
            let obj = jsonData[ii];
            let idx = dataSource.length - 1;
            if(!_dataMap.get(obj.monitoring_nm)) {
                _dataMap.set(obj.monitoring_nm, new Map());
            }
            if (dataSource.length === 0 || dataSource[idx].id !== obj.monitoring_nm) {
                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,
                });
                idx = dataSource.length - 1;
                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];
            }
            const data = dataMap.get(obj.vms_ctlr_nmbr);
            _dataMap.get(obj.monitoring_nm).set(obj.vms_ctlr_nmbr, data);
            const dsplDt = getParseDateTime(data.dspl_dt);

            const imageNm = data.cmnc_stts_desc === '통신두절' ? 'false' : 'true';

            let dsplDtColor = data.cmnc_stts_desc === '통신두절' ? 'wanrning' : '#fff';

            let operClass  = stateColorSelector(data.oper_mode_desc);
            let powerClass = stateColorSelector(data.pwer_stts_desc);
            let modlClass  = stateColorSelector(data.modl_stts_desc);
            let doorClass  = stateColorSelector(data.cbox_door_stts_desc);
            let hetrClass  = stateColorSelector(data.hetr_stts_desc);
            let fanClass   = stateColorSelector(data.fan_stts_desc);

            let tempClass = '';
            if (data.cbox_tmpr === 255 || data.cbox_tmpr === null || data.cbox_tmpr === '-') {
                data.cbox_tmpr = '-'
                tempClass = 'gray';
            }

            let height = 80 + data.vms_hght;
            data.msgs.sort(function(a,b){
                return a.phase - b.phase
            });

            let div = $(
                `<div class='phase-box b0 dx-theme-border-color' style='height:${height}px;'>
                    <div class='phase-title b2 dx-nav-item dx-theme-border-color' id='${data.vms_ctlr_nmbr}' title='${data.vms_ctlr_nmbr} [${data.vms_ctlr_id}]\n${data.vms_nm}'>
                        <img src='/images/op/icon/${imageNm}.png' width='20px' height='20px' align='center'> ${data.vms_nm} <span class='phase'>1/${data.msgs.length}</span></div>
                    <div class='image-box' style='width:100%; height:${data.vms_hght * _magnigication + 10}px'>
                        <img class='image' height='${data.vms_hght * _magnigication}px' src='data:image/png;base64,${data.msgs[0].vms_dspl_msg_imag}'>
                    </div>
                    <div class='date-text' style='color:${dsplDtColor}'>제공시각: ${dsplDt}</div>
                    <div class='state-box'>
                        <div class='${doorClass} b0 dx-theme-border-color' title='도어 상태'>${data.cbox_door_stts_desc}</div>
                        <div class='${fanClass} b0 dx-theme-border-color' title='팬 동작 상태'>${data.fan_stts_desc}</div>
                        <div class='${hetrClass} b0 dx-theme-border-color' title='히터 가동 상태'>${data.hetr_stts_desc}</div>
                        <div class='${modlClass} b0 dx-theme-border-color' title='모듈'>${data.modl_stts_desc}</div>
                        <div class='${powerClass} b0 dx-theme-border-color' title='모듈 전원 상태'>${data.pwer_stts_desc}</div>
                        <div class='${tempClass} b0 dx-theme-border-color' title='함체 온도'>${data.cbox_tmpr}</div>
                        <div class='${operClass} b0 dx-theme-border-color' title='운영 모드'>${data.oper_mode_desc}</div>
                    </div>
                </div>`
            );

            dataSource[idx]['text'].push(div);
            dataSource[idx]['msgs'].push(data.msgs);
            dataSource[idx]['height'].push(height);
            dataSource[idx]['position'].push($(div).children().eq(1).children().eq(0));
            dataSource[idx]['phase'].push($(div).children().eq(0).children().eq(1));
            dataSource[idx]['title'].push($(div).children().eq(0));
        }

    }
    _scenarioTabs.option('dataSource', dataSource);
};

function stateColorSelector(value) {
    let className = '';
    if (value === '중지' || value === '정상' || value === '닫힘' || value === '자동') {
        className = 'green';
    }
    else if (value === '가동' || value === '기본') {
        className = 'yellow';
    }
    else if (value === '-' || !value) {
        className = 'gray';
    }
    else {
        className = 'wanrning';
    }
    return className;
}

//이미지 인터벌 이벤트
function intervalEvent(value, position, phase, idx){
    if (value[idx]) {
        $(position).prop('src', 'data:image/png;base64,'+ value[idx].vms_dspl_msg_imag);
        idx++;
        $(phase).text(`${idx}/${value.length}`);
        if(idx === value.length) idx = 0;
        let dspl_hh = value[idx].dspl_hh;
        let timer = setTimeout(()=>{
            window.clearInterval(timer);
            intervalEvent(value, position, phase, idx);
        }, dspl_hh * 1000);
        _intervalMap.get('interval').push(timer);
    }
}

//에디트 박스 생성
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);

    //텍스트 상자 옵션
    const textColumns = [
        {
            column:'vms_ctlr_id',
            position : vmsCtlrId,
            box      : null,
            width    : 110,
            height   : 20,
            stylingMode : 'outlined',
        },
        {
            column:'vms_usag_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    : 45,
            height   : 20,
            stylingMode : 'outlined',
        },
        {
            column:'pwer_stts_desc',
            position : pwerStts,
            box      : null,
            width    : 45,
            height   : 20,
            stylingMode : 'outlined',
        },
        {
            column:'brgh_val',
            position : brghVal,
            box      : null,
            width    : 45,
            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);
    let key           = Number(title.attr('id'));
    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('./phase-popup-manager.html', 'VMS 모니터링 화면 관리', 'width = 1200, height = 650, top = 150, left = 300, resizable=yes, scrollbars=no');
}
