import { TMapMngr, TFclt } from "/js/vworld/map-mngr.js";
import { LayerIndex } from "/js/vworld/map-const.js";

let _mapManager       = null;
let _selectFcltNmbr   = null;
let _vmsTableList     = null;
let _managerData      = [];

const _pageMsg        = 'VMS';
const _pageName       = 'VMS 기본정보 관리';
const _lyrIdx         = LayerIndex.Vms;
const _apiUri         = '/api/vms/manager/info';
const _vmsBtnBoxMap   = new Map();
const _vmsCdTypeMap   = new Map();
const _vmsInputBoxMap = new Map();
const _ipExpr         = /^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}$/;


const _updateColumns  = {
    altt_imag_dspl_yn: 'N',
    altt_imag_nmbr : 0,
    brgh_curr_step: 40,
    brgh_mode: 2,
    brgh_nght_step : 48,
    brgh_week_step : 64,
    cmnc_fail_rate : 60,
    def_phse_chng_cycl : 5,
    del_yn : 'N',
    fan_mode: 2,
    fan_run_tmpr : 30,
    hetr_mode : 2,
    hetr_run_tmpr : 0,
    istl_lctn_addr : null,
    istl_lctn_nm : null,
    modl_err_rate : 10,
    oper_mode : 'A',
    panl_off_time : '2300',
    panl_on_time : '0600',
    panl_pwer_mode : 2,
    strm_http_addr: null,
    strm_rtsp_addr: null,
    strm_sesn_nm : null,
    vms_ctlr_id : null,
    vms_ctlr_ip : null,
    vms_ctlr_local_no : 0,
    vms_ctlr_nmbr : 0,
    vms_ctlr_port : null,
    vms_max_phse_num : 14,
    vms_nm : null,
    vms_type_cd : null,
    web_cmra_cmpy: null,
    web_cmra_id : null,
    web_cmra_ip : null,
    web_cmra_mdl : null,
    web_cmra_port : 0,
    web_cmra_pwd : null,
    web_rtc_id: null,
    web_rtc_svr_ip: null,
    web_rtc_svr_port: 0,
    x_crdn : 0,
    y_crdn : 0,
}

const _btnClasses     = [
    'all-vms-apply-btn',
    'close-btn',
    'edit-btn',
    'add-btn',
    'del-btn',
    'save-btn',
    'cancle-btn'
];

const _inputClasses   = [
    'vms_ctlr_nmbr',
    'vms_ctlr_id',
    'vms_nm',
    'vms_type_cd',
    'x_crdn',
    'y_crdn',
    'vms_ctlr_ip',
    'vms_ctlr_port',
    'web_cmra_ip',
    'web_cmra_port',
    'web_cmra_id',
    'web_cmra_pwd',
    'strm_sesn_nm',
    'vms_max_phse_num',
    'panl_on_time',
    'panl_off_time',
    'strm_http_addr',
    'strm_rtsp_addr',
    'web_rtc_id',
    'web_rtc_svr_ip',
    'web_rtc_svr_port'
];

const panlTimeColumns = [
    'panl_on_time',
    'panl_off_time'
];

$(()=>{
    _vmsTableList = $('.list-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        focusedRowEnabled       : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'vms_ctlr_nmbr',
        headerFilter            : {
            visible: true,
        },
        scrolling               : {
            mode : 'standard',
        },
        paging: {
            enabled: true,
            pageSize: 1000,
        },
        selection: {
            mode: 'single',
        },
        columns:[
            {
                dataField    : "vms_ctlr_nmbr",
                caption      : "번호",
                alignment    : "center",
                sortOrder    : 'asc',
                sortIndex    : 0,
                cssClass     : 'no-padding',
            },
            {
                dataField    : "vms_nm",
                caption      : "명칭",
                alignment    : "center",
                cssClass     : 'no-padding',
                cellTemplate(c,e) {
                    c.css('text-align', 'left');
                    c.text(e.displayValue);
                }
            },
            {
                dataField    : "vms_ctlr_id",
                caption      : "VMS ID",
                alignment    : "center",
                cssClass     : 'no-padding',
            },
            {
                dataField    : "vms_type_cd",
                caption      : "유형",
                alignment    : "center",
                cssClass     : 'no-padding',
                lookup       : {
                    dataSource  : null,
                    valueExpr   : "vms_type_cd",
                    displayExpr :  "vms_type_desc",
                }
            },
            {
                dataField    : "vms_ctlr_ip",
                caption      : "제어가 IP",
                alignment    : "center",
                cssClass     : 'no-padding',
            },
            {
                dataField    : "vms_ctlr_port",
                caption      : "통신포트",
                alignment    : "center",
                cssClass     : 'no-padding',
            },
            {
                dataField    : "web_cmra_ip",
                caption      : "웹카메라 IP",
                alignment    : "center",
                cssClass     : 'no-padding',
            },
            {
                dataField    : "panl_on_time",
                caption      : "전광판 ON",
                alignment    : "center",
                cssClass     : 'no-padding',
            },
            {
                dataField    : "panl_off_time",
                caption      : "전광판 OFF",
                alignment    : "center",
                cssClass     : 'no-padding',
            },
            {
                dataField    : "vms_max_phse_num",
                caption      : "폼 최대갯수",
                alignment    : "center",
                cssClass     : 'no-padding',
            },
        ],
        onRowDblClick(row){
            vmsTableDblClick(row);
        }
    }).dxDataGrid('instance');

    fetchVmsInputArray();
    fetchVmsButtonArray();
    fetchBaseData();
});

//필요 데이터 가져오기
async function fetchBaseData(){
    getDataAsync('/api/vms/common/vms-type', fetchVmsType);
    // getDataAsync('/api/vms/common/vms-usage', fetchVmsUsage);
    getDataAsync(_apiUri, fetchInfoTableList );
}

//VMS 목록 수신 및 세팅
function fetchInfoTableList(jsonData){
    _vmsTableList.option('dataSource', jsonData);
    _managerData.push(jsonData);
    doMap();
    updateIcon();
}


//VMS 크기 코드 데이터 수신 및 데이터 소스 세팅
function fetchVmsType(jsonData){
    _vmsCdTypeMap.set('vms_type_cd', jsonData);
    _vmsTableList.option('columns[3].lookup.dataSource', jsonData);
    const vmsTypeCdSelect = _vmsInputBoxMap.get('vms_type_cd').get('input');
    vmsTypeCdSelect.option('dataSource', jsonData);
    setValue(vmsTypeCdSelect, jsonData[0].vms_type_cd);
    _vmsInputBoxMap.get('vms_type_cd').set('init', jsonData[0].vms_type_cd);
}

//버튼들 화면 세팅
function fetchVmsButtonArray(){
    _btnClasses.forEach( (btnClass)=>{
        _vmsBtnBoxMap.set(btnClass, new Map());
        const btnInfoBox = _vmsBtnBoxMap.get(btnClass);
        btnInfoBox.set('btn', $('.'+btnClass).dxButton({}).dxButton('instance'));
        switch(btnClass){
            case 'all-vms-apply-btn':
                setVmsBtnOption(btnClass, '전체 VMS 적용', null, allVmsApplyEvent, true, false);
                break;
            case 'close-btn':
                setVmsBtnOption(btnClass, '닫기', 'close', closeEvent);
                break;
            case 'edit-btn':
                setVmsBtnOption(btnClass, '편집', 'edit', editEvent, true, true);
                btnInfoBox.set('dblClick', [true, false]);
                btnInfoBox.set('event', [false, false]);
                btnInfoBox.set('cancle', [true, false, true]);
                break;
            case 'add-btn':
                setVmsBtnOption(btnClass, '추가', 'plus', addEvent, true, false);
                btnInfoBox.set('dblClick', [true, false]);
                btnInfoBox.set('event', [true, true]);
                btnInfoBox.set('cancle', [true, false, false]);
                break;
            case 'del-btn':
                setVmsBtnOption(btnClass, '삭제', 'minus', delEvent, true, true);
                btnInfoBox.set('dblClick', [true, false]);
                btnInfoBox.set('event', [true, true]);
                btnInfoBox.set('cancle', [true, false, true]);
                break;
            case 'save-btn':
                setVmsBtnOption(btnClass, '저장', 'save', null, true, true);
                btnInfoBox.set('dblClick', [true, true]);
                btnInfoBox.set('event', [true, false]);
                btnInfoBox.set('cancle', [true, true, true]);
                break;
            case 'cancle-btn':
                setVmsBtnOption(btnClass, '취소', 'close', cancleEvent, false, false);
                btnInfoBox.set('dblClick', [false, false]);
                btnInfoBox.set('event', [true, false]);
                btnInfoBox.set('cancle', [false, false, false]);
                break;
            default :
                break
        }
    });
}

//inputBox 화면 세팅
function fetchVmsInputArray(){
    _inputClasses.forEach( (inputClass)=>{
        _vmsInputBoxMap.set(inputClass, new Map());
        const inputBox = _vmsInputBoxMap.get(inputClass);
        inputBox.set('input', null);
        switch(inputClass){
            case 'vms_ctlr_nmbr' :
                setVmsInputOption(inputClass, 'text', 60, null, 10, [true, false, false], '제어기번호');
                break
            case 'vms_ctlr_id':
                setVmsInputOption(inputClass, 'text', 100, null, 30, [true, false, false], 'VMS ID');
                break
            case 'vms_nm' :
                setVmsInputOption(inputClass, 'text', 250, null, 40, [true, false, false], 'VMS 명칭');
                break
            case 'vms_usag_type_cd' :
                setVmsInputOption(inputClass, 'select', 250, null, null, [true, false, false], 'VMS 유형');
                break
            case 'vms_type_cd' :
                setVmsInputOption(inputClass, 'select', 250, null, null, [true, false, false], 'VMS 크기');
                break
            case 'x_crdn' :
                setVmsInputOption(inputClass, 'text', 120, '0.0000000', 11, [true, false, false], '위치좌표 X');
                inputBox.get('input').on('valueChanged', (text) => crdnChanges(text, 3));
                break
            case 'y_crdn' :
                setVmsInputOption(inputClass, 'text', 120, '0.0000000', 11,[true, false, false], '위치좌표 Y');
                inputBox.get('input').on('valueChanged', (text) => crdnChanges(text, 2));
                break
            case 'vms_ctlr_ip' :
                setVmsInputOption(inputClass, 'text', 170, null, 20, [true, true, false], '제어기 IP');
                inputBox.set('ip', true);
                break
            case 'vms_ctlr_port' :
                setVmsInputOption(inputClass, 'text', 70, null, 5, [true, false, true], '제어기 PORT');
                break
            case 'web_cmra_ip' :
                setVmsInputOption(inputClass, 'text', 170, null, 20, [false, true, false], '웹카메라 IP');
                break
            case 'web_cmra_port' :
                setVmsInputOption(inputClass, 'text', 70, null, 5, [false, false, true], '웹카메라 PORT');
                break
            case 'web_cmra_id' :
                setVmsInputOption(inputClass, 'text', 120, null, 30, null, '웹카메라 접속 ID');
                break
            case 'web_cmra_pwd' :
                setVmsInputOption(inputClass, 'text', 120, null, 64, null, '웹카메라 접속 패스워드');
                inputBox.get('input').option('mode', 'password');
                break
            case 'strm_sesn_nm' :
                setVmsInputOption(inputClass, 'text', 250, null, 200, null, '스트리밍주소');
                break
            case 'strm_http_addr' :
                setVmsInputOption(inputClass, 'text', 250, null, 200, null, '스트리밍 HTTP 주소');
                break
            case 'strm_rtsp_addr' :
                setVmsInputOption(inputClass, 'text', 250, null, 200, null, '스트리밍 RSTP 주소');
                break
            case 'web_rtc_id' :
                setVmsInputOption(inputClass, 'text', 250, null, 56, null, 'WEB RCT ID');
                break
            case 'web_rtc_svr_ip' :
                setVmsInputOption(inputClass, 'text', 170, null, 20, [false, true, false], 'WEB RTC IP');
                break
            case 'web_rtc_svr_port' :
                setVmsInputOption(inputClass, 'text', 70, null, 5, [false, false, true], 'WEB RTC PORT');
                break
            case 'vms_max_phse_num' :
                setVmsInputOption(inputClass, 'number', 70, 14, 16, null, '표출폼최대갯수');
                inputBox.get('input').option('min', 1);
                inputBox.get('input').on('valueChanged', (e)=>{
                    if (e.value === null) {
                        setValue(e.component, 1);
                    }
                })
                break
            case 'panl_on_time' :
                setVmsInputOption(inputClass, 'time', 70, 1696626000000, null, [true, false, false], '전광판 ON 시각');
                break
            case 'panl_off_time' :
                setVmsInputOption(inputClass, 'time', 70, 1696687200000, null, [true, false, false], '전광판 OFF 시각');
                break
            default :
                break
        }

    });
}

//input 옵션 세팅
function setVmsInputOption( inputClass, type, width, value, max, validation, label){
    const inputBox = _vmsInputBoxMap.get(inputClass);
    const position =  $('.' + inputClass);

    inputBox.set('label', label);
    if (validation) {
        inputBox.set('must', validation[0]);
        inputBox.set('ip', validation[1]);
        inputBox.set('port', validation[2]);
    }
    inputBox.set('init', '');

    if(value) inputBox.set('init', value);

    switch (type) {
        case 'text':
            inputBox.set('input', position.dxTextBox({
                value       : value,
                readOnly    : true,
                width       : width,
                stylingMode : 'outlined',
                height      : 25,
                maxLength   : max,
            }).dxTextBox('instance'));
            inputBox.set('max', max);
            break;
        case 'number':
            inputBox.set('input', position.dxNumberBox({
                value           : value,
                readOnly        : true,
                width           : width,
                stylingMode     : 'outlined',
                showSpinButtons : true,
                height          : 25,
                min             : 1,
                max             : max,
            }).dxNumberBox('instance'));
            inputBox.set('max', max.length);
            break;
        case 'select':
            const valueExpr   = inputClass;
            const displayExpr = valueExpr.substring(0,valueExpr.length-2) + 'desc';
            inputBox.set('input', position.dxSelectBox({
                displayExpr     : displayExpr,
                valueExpr       : valueExpr,
                readOnly        : true,
                width           : width,
                stylingMode     : 'outlined',
                height          : 25,
            }).dxSelectBox('instance'));
            break;
        case 'time':
            inputBox.set('input', position.dxDateBox({
                type               : type,
                value              : value,
                readOnly           : false,
                width              : width,
                stylingMode        : 'outlined',
                height             : 25,
                displayFormat      : 'HH:mm',
                interval           : 10,
                invalidDateMessage : '형식에 맞게 입력해주세요 ex) 00:00',
            }).dxDateBox('instance'));
            break
        default:
            break;
    }



}

//버튼 옵션 세팅
function setVmsBtnOption( classNm, text, icon, event, visible, disabled){
    let btn = _vmsBtnBoxMap.get(classNm).get('btn');
    if(btn){
        btn.option('text', text);
        btn.option('icon', icon);
        btn.option('onClick', event);
        btn.option('visible', visible);
        btn.option('disabled', disabled);
        btn.option('stylingMode', 'outlined');
    };
};

//전체 VMS 적용 이벤트
function allVmsApplyEvent(){
    const panlOnTime  = getInput('panl_on_time');
    const panlOffTime = getInput('panl_off_time');
    let onTime        = getValue(panlOnTime);
    let offTime       = getValue(panlOffTime)
    let panlTimeParam = {};
    let data = [];
    let ctrlNmvr = null;
    for (let panlTimeColumn of panlTimeColumns){
        const inputBox = _vmsInputBoxMap.get(panlTimeColumn);
        const input = getInput(panlTimeColumn);

        if (nullChecker(getValue(input)) === ""){
            return alertWarning(inputBox.get('must') + '을 입력해주세요', null, input);
        }
        else if (input.option('validationError')){
            return alertWarning('전광판 On/Off 시각을 바르게 입력해주세요', null, input);
        }
    };

    if (_vmsTableList.getSelectedRowsData().length > 0) ctrlNmvr = _vmsTableList.getSelectedRowsData()[0].vms_ctlr_nmbr;

    confirmMessage("제어기 설정 정보를 전체 VMS에 동일하게 적용 하시겠습니까?").done((yes) => {
        if (yes === true) {
            onTime  = getSendTime(onTime);
            offTime = getSendTime(offTime);
            panlTimeParam['panl_on_time'] = onTime;
            panlTimeParam['panl_off_time'] = offTime;

            const result = postInsertUpdate(_apiUri + '/panl-time', panlTimeParam);
            if (result > 0) {
                refresh(_vmsTableList, data, _apiUri);

                if (ctrlNmvr){
                    _vmsTableList.clearSelection();
                    _vmsTableList.refresh().done(function () {
                        _vmsTableList.selectRows(ctrlNmvr, true);
                        _vmsTableList.option("focusedRowKey", ctrlNmvr);
                        eventOff();
                    });
                };

                return alertConfirm('VMS 제어기 설정 정보저장<br>제이기 설정 정보를 전체 제어기에 적용 하였습니다.');
            };
            //return alertConfirm('VMS 제이기 설정 정보저장<br>제이기 설정 정보를 전체 제어기에 적용 되지 않았습니다.');
        }
    });
};

//닫기 이벤트
function closeEvent(){
    window.close();
};


//편집 이벤트
function editEvent(){
    eventOn();
    editFcltObject(_selectFcltNmbr, true);
    _vmsBtnBoxMap.get('save-btn').get('btn').off('click');
    _vmsBtnBoxMap.get('save-btn').get('btn').on('click', () => saveEvent('edit'));
};

//추가 이벤트
function addEvent(){
    eventOn(true);
    let center = _mapManager.getCenter();
    const xCrdn = getInput('x_crdn');
    const yCrdn = getInput('y_crdn');
    setValue(xCrdn, center[0].toFixed(7));
    setValue(yCrdn, center[1].toFixed(7));
    const newNum = getNewNmbr();
    addFcltObject(newNum);
    setValue( getInput('vms_ctlr_nmbr'), newNum);
    _vmsBtnBoxMap.get('save-btn').get('btn').off('click');
    _vmsBtnBoxMap.get('save-btn').get('btn').on('click', () => saveEvent());
};

//삭제 이벤트
function delEvent(){
    const vmsCtlrNmbr = _vmsTableList.getSelectedRowsData()[0].vms_ctlr_nmbr;
    confirmMessage(_pageMsg + "번호 : " + vmsCtlrNmbr + "\n선택하신 " + _pageMsg + " 정보를 삭제하시겠습니까?").done((yes)=>{
        if (yes) {
            const result = deleteData(_apiUri, vmsCtlrNmbr);
            if (result > 0) {
                delResultMsg(_pageMsg);
                _managerData = refresh(_vmsTableList, _managerData, _apiUri);
                deleteFcltObject(vmsCtlrNmbr);
                _vmsTableList.refresh().done(function () {
                    _vmsTableList.option("focusedRowIndex", -1);
                    _vmsTableList.clearSelection();
                    eventOff();
                });
            }
        }
    });
}

//저장 이벤트
function saveEvent(type){
    let updateData = {..._updateColumns};
    if (type === 'edit') {
        let rowData = _vmsTableList.getSelectedRowsData()[0];
        for (let key in updateData) {
            updateData[key] = rowData[key];
        }
    }

    let selected = false;
    for ( let inputClass of _inputClasses) {
        const inputBox   = _vmsInputBoxMap.get(inputClass);
        const input      = getInput(inputClass);
        const value      = input.option('value');
        const empty      = nullChecker(value) === "";
        const max        = inputBox.get('max');
        const label      = inputBox.get('label');
        if (empty) {
            if (inputBox.get('must')) {
                return alertWarning("필수 항목을 입력해주세요. [ " + label + " ]", null, input);
            }
        }
        else {
            if ( max && getByteLength(value) > max ) {
                return alertWarning( max + " 바이트 이내로 입력해주세요. [ " + label + " ]", null, input);
            }
            if (inputBox.get('ip') && !_ipExpr.test(value)) {
                return alertWarning("IP 형식에 맞게 입력해주세요. [ " + label + " ]", null, input);
            }
            if (inputBox.get('port') && isNaN(value)) {
                return alertWarning("PORT 형식에 맞게 입력해주세요. [ " + label + " ]", null, input);
            }
            if (input.option('validationError')) {
                return alertWarning("전광판 On/Off 시각을 바르게 입력해주세요. [ " + label + " ]", null, input);
            }
        }

        updateData[inputClass] = value;
    }

    updateData.panl_on_time = getSendTime(updateData.panl_on_time);
    updateData.panl_off_time = getSendTime(updateData.panl_off_time);

    if (_vmsTableList.getRowIndexByKey(updateData.vms_ctlr_nmbr) > -1 && _vmsTableList.getSelectedRowsData().length > 0){
        let selectedData = _vmsTableList.getSelectedRowsData()[0];
        for(let key in updateData){
            if(!_inputClasses.includes(key) && key !== 'vms_id' && key !== 'vms_modl_type_cd'){
                updateData[key] = selectedData[key];
            }
        }
        selected = true;
    }
    let result = postInsertUpdate(_apiUri + "/" + updateData.vms_ctlr_nmbr, updateData);

    if (result > 0) {
        insResultMsg("VMS 제어기");
        _managerData = refresh(_vmsTableList, _managerData, _apiUri);
        _vmsTableList.clearSelection();
        _vmsTableList.refresh().done(()=>{
            _vmsTableList.selectRows(updateData.vms_ctlr_nmbr, true);
            _vmsTableList.option("focusedRowKey", updateData.vms_ctlr_nmbr);
            eventOff();
        });
    }
};

//취소 이벤트
function cancleEvent(){
    eventOff();
};

//vms 목록 더블클릭 이벤트
function vmsTableDblClick(row){
    if(row.data){
        const vmsInfo = row.data;
        _selectFcltNmbr = vmsInfo.vms_ctlr_nmbr;
        selectFcltObject(_selectFcltNmbr);
        _inputClasses.forEach(inputClass => {
            const inputBox = _vmsInputBoxMap.get(inputClass).get('input');
            setValue(inputBox, vmsInfo[inputClass]);
            if(inputClass === 'panl_on_time' || inputClass === 'panl_off_time'){
                let timeVal = vmsInfo[inputClass];
                let now = nowTime();
                timeVal =  now.substring(0,10) +' '+ timeVal.substring(0,2) + ':' + timeVal.substring(2,4)+ ':00';
                timeVal = new Date(timeVal).getTime();
                setValue(inputBox, timeVal);
            }
        });
        _btnClasses.forEach( (btnClass)=>{
            const btnInfoBox = _vmsBtnBoxMap.get(btnClass);
            const btn = btnInfoBox.get('btn');
            if(btnInfoBox.get('dblClick')){
                const options = btnInfoBox.get('dblClick');
                btn.option('visible', options[0]);
                btn.option('disabled', options[1]);
            }
        })
    }
}

//이벤트 실행시 발생 이벤트
function eventOn(init){
    _btnClasses.forEach( (btnClass)=>{
        const btnInfoBox = _vmsBtnBoxMap.get(btnClass);
        const btn = btnInfoBox.get('btn');
        if (btnInfoBox.get('event')) {
            const options = btnInfoBox.get('event');
            btn.option('visible', options[0]);
            btn.option('disabled', options[1]);
        };
    });

    _inputClasses.forEach(inputClass => {
        const inputInfoBox = _vmsInputBoxMap.get(inputClass);
        const inputBox     = inputInfoBox.get('input');
        inputBox.option('readOnly', false);

        if (inputClass === 'vms_ctlr_nmbr') {
            inputBox.option('readOnly', true);
        }

        if (init) {
            inputBox.option('value', inputInfoBox.get('init'));
        }
    });

    dsblOnBtn(_vmsTableList);
}

//이벤트 취소시 발생 이벤트
function eventOff(){

    dsblOffBtn(_vmsTableList);
    updateIcon();
    const selectedData = _vmsTableList.getSelectedRowsData();
    const selected     = selectedData.length > 0;

    if (selected) {
        _selectFcltNmbr = selectedData[0].vms_ctlr_nmbr;
        selectFcltObject(_selectFcltNmbr);
    }

    _btnClasses.forEach( (btnClass)=>{
        const btnInfoBox   = _vmsBtnBoxMap.get(btnClass);
        const btn          = btnInfoBox.get('btn');
        if(btnInfoBox.get('cancle')){
            const options = btnInfoBox.get('cancle');
            btn.option('visible', options[0]);
            if (selected) {
                btn.option('disabled', options[1]);
            } else{
                btn.option('disabled', options[2]);
            }
        };
    });

    _inputClasses.forEach(inputClass => {
        const inputInfoBox = _vmsInputBoxMap.get(inputClass);
        const inputBox     = inputInfoBox.get('input');
        inputBox.option('readOnly', true);
        if('panl_on_time' === inputClass || 'panl_off_time' === inputClass) inputBox.option('readOnly', false);

        if (selected) {
            if (inputClass === 'panl_on_time' || inputClass === 'panl_off_time'){
                let timeVal = selectedData[0][inputClass];
                let now = nowTime();
                timeVal =  now.substring(0,10) +' '+ timeVal.substring(0,2) + ':' + timeVal.substring(2,4)+ ':00';
                timeVal = new Date(timeVal).getTime();
                setValue(inputBox, timeVal);
            }
            else {
                inputBox.option('value', selectedData[0][inputClass]);
            }
        } else {
            inputBox.option('value', inputInfoBox.get('init'));
        }
    });


}

/**
 * 제어기 신규 ID 조회
 */
function getNewNmbr() {
    let newId = [];
    getData(_apiUri + "/new-id", newId);
    _selectFcltNmbr = newId[0].new_id;
    return _selectFcltNmbr;
}
/**
 * 지도 인터페이스 함수........
 */
function doMap() {
    _mapManager = new TMapMngr("vms-map", "tooltip");
    _mapManager.setEditMode(_lyrIdx, true);
    _mapManager.showLayer(_lyrIdx, true);
    _mapManager.showFcltObjectText(_lyrIdx, true);
    _mapManager.onFcltDragEndFunc = onFcltDragEndFunc; // 객체(시설물) 편집시 객체 이동후 좌표 반환
    _mapManager.onMouseClickFunc = onMouseClickFunc; // 객체 마우스 클릭 이벤트 반환
    fetchMapIconBar($('.map-bar'), _mapManager, _lyrIdx, _pageName);
}

function onFcltDragEndFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY) {
    if (ALyrIdx != _lyrIdx) {
        return;
    }
    if (ANmbr === _selectFcltNmbr) {
        setValue(getInput('x_crdn'), ACoordX.toFixed(7));
        setValue(getInput('y_crdn'), ACoordY.toFixed(7));
    }
    //console.log(`onFcltDragEndFunc, ${ALyrIdx}, ${ALyrName}, ${ANmbr}, ${ACoordX}, ${ACoordY}`);
}

function onMouseClickFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY, X, Y) {
    if (ALyrIdx != _lyrIdx) {
        return;
    }
    //console.log(`onMouseClickFunc, ${ALyrIdx}, ${ALyrName}, ${ANmbr}, ${ACoordX}, ${ACoordY}, ${X}, ${Y}`);
    const obj = _mapManager.findLayerObject(ALyrIdx, ANmbr);
    if (!obj) {
        return;
    }
    else  {
        if (_selectFcltNmbr === ANmbr) {
            return;
        }
        const editBtn = _vmsBtnBoxMap.get('edit-btn').get('btn');
        if (!editBtn.option('visible')) {
            return;
        }
        _selectFcltNmbr = ANmbr;
        selectFcltObject(_selectFcltNmbr);
        _vmsTableList.selectRows(ANmbr).done(()=>{
            _vmsTableList.option('focusedRowKey',ANmbr);
            const vmsInfo = _vmsTableList.getSelectedRowsData()[0];
            _inputClasses.forEach(inputClass => {
                const inputBox = _vmsInputBoxMap.get(inputClass).get('input');
                setValue(inputBox, vmsInfo[inputClass]);
                if(inputClass === 'panl_on_time' || inputClass === 'panl_off_time'){
                    let timeVal = vmsInfo[inputClass];
                    let now = nowTime();
                    timeVal =  now.substring(0,10) +' '+ timeVal.substring(0,2) + ':' + timeVal.substring(2,4)+ ':00';
                    timeVal = new Date(timeVal).getTime();
                    setValue(inputBox, timeVal);
                }
            });
            _btnClasses.forEach( (btnClass)=>{
                const btnInfoBox = _vmsBtnBoxMap.get(btnClass);
                const btn = btnInfoBox.get('btn');
                if(btnInfoBox.get('dblClick')){
                    const options = btnInfoBox.get('dblClick');
                    btn.option('visible', options[0]);
                    btn.option('disabled', options[1]);
                }
            })
        });
    }
}

/**
 * 지도에 시설물 객체 정보를 그린다.
 */
function updateIcon() {
    // 기존 객체를 모두 삭제한다.
    _mapManager.removeLayerObject(_lyrIdx);
    if (_managerData[0] && _managerData[0].length > 0) {
        // 시설물 객체를 지도에 그린다.
        const objs = new Array();
        _managerData[0].forEach((obj) => {
            const item = new TFclt(obj.vms_ctlr_nmbr, obj.vms_nm, obj.x_crdn, obj.y_crdn);
            objs.push(item);
        });
        _mapManager.initFcltObject(_lyrIdx, objs);
    }
}

function selectFcltObject(ANmbr) {
    _mapManager.selectLayerObject(_lyrIdx, ANmbr);
}
function editFcltObject(ANmbr, AIsEdit) {
    _mapManager.editFcltObject(_lyrIdx, ANmbr, AIsEdit, AIsEdit ? "1" : "0");
}
function deleteFcltObject(ANmbr) {
    _mapManager.deleteFcltObject(_lyrIdx, ANmbr);
    _selectFcltNmbr = null;
}
function addFcltObject(ANmbr) {
    _mapManager.createFcltObject(_lyrIdx, ANmbr, "New", "New", "1" /*아이콘색결정,시설물유형_N.png*/ /*, x_crdn, y_crdn*/);
}

function getInput(column){
    return _vmsInputBoxMap.get(column).get('input')
}
