import { TMapMngr, TFclt } from '/js/vworld/map-mngr.js';
import { LayerType, LayerIndex, EditLinkColor } from '/js/vworld/map-const.js';
import { apiGet } from '/js/utils/restApi.js';

let _mapManager     = null;
let _selectFcltNmbr = null;
let _managerData    = [];
const _linkMap      = new Map();
const _lyrIdx       = LayerIndex.Dsrc;
const _lyrType      = LayerType.LINK;
const _lyrLinkIdx   = LayerIndex.Link1;
const _pageName     = 'DSRC 수집구간 관리';
const _dsrcCtrlMap  = new Map()
const _selObjMap    = new Map();
let _linkData       = [];
let _prevLinkId = null;

//우측 섹션 관련
let _listTable;
let _linkTable;
let ctlrSelBtn;
let linkBtn;
let rseSectId;
let secLngt;
let strtRseCtlrNmbr;
let endRseCtlrNmbr;
let linkId;
let rseSectNm;
let strtSpotNm;
let endSpotNm;
let strtMapCheck;
let endMapCheck;
let dsrcIdCheck;
let delBtn;
let editBtn;
let addBtn;
let saveBtn;
let cancelBtn;
let addLinkBtn;
let delLinkBtn;
let inputArr;
let idArr = [];
let _dsrcTable;
let _modalText;
let _modalSaveBtn;
let _modalCancelBtn;
let _modalXBtn;
let lyrInfo;

// 모달 관련
let vdsCtrlInfoTable = null;
const _updateColumns ={
    del_yn : 'N',
    end_rse_ctlr_nmbr : 0,
    end_spot_nm : null,
    rse_sect_id : 0,
    rse_sect_nm : null,
    sect_lngt : 0,
    strt_rse_ctlr_nmbr : 0,
    strt_spot_nm : null
}
let _selCnt = 1;
//공통
let _apiUri        = '/api/rse/tb_rse_sect';
const _linkRltnApi = '/api/rse/tb_rse_sect_rltn_link';
const pageMsg        = 'DSRC 수집구간'

const btnArr    = [
    editBtn = {
        class       : 'edit-btn',
        box         : null,
        option      : 80,
        visible     : true,
        disabled    : true,
        dbdsb       : false,
        edit        : {
            click   : {
                visible  : false,
                disabled : false,
            },
            cancle : {
                visible  : true,
                disabled : false,
            }
        },
        add         : {
            click   : {
                visible  : false,
                disabled : false,
            },
            selected : {
                visible  : true,
                disabled : false,
            }
            ,
            unSelected : {
                visible  : true,
                disabled : true,
            },
        }
        ,
        addvsb      : false,
        icon        : 'edit',
        text        : '편집',
        method      : function(){
            editEvent();
        }
    },
    cancelBtn = {
        class       : 'cancle-btn',
        box         : null,
        option      : 80,
        visible     : false,
        disabled    : false,
        dbdsb       : false,
        edit        : {
            click   : {
                visible  : true,
                disabled : false,
            },
            cancle : {
                visible  : false,
                disabled : false,
            }
        },
        add         : {
            click   : {
                visible  : true,
                disabled : false,
            },
            selected : {
                visible  : false,
                disabled : false,
            }
            ,
            unSelected : {
                visible  : false,
                disabled : false,
            },
        },
        addvsb      : true,
        icon        : 'close',
        text        : '취소',
    },
    addBtn = {
        class       : 'add-btn',
        box         : null,
        option      : 80,
        disabled    : false,
        visible     : true,
        edit        : {
            click   : {
                visible  : true,
                disabled : true,
            },
            cancle : {
                visible  : true,
                disabled : false,
            }
        },
        add         : {
            click   : {
                visible  : true,
                disabled : true,
            },
            selected : {
                visible  : true,
                disabled : false,
            }
            ,
            unSelected : {
                visible  : true,
                disabled : false,
            },
        },
        dbdsb       : false,
        adddsb      : true,
        icon        : 'plus',
        text        : '추가',
        method      : function(){
            addEvent();
        }
    },
    delBtn = {
        class       : 'del-btn',
        box         : null,
        option      : 80,
        disabled    : true,
        visible     : true,
        edit        : {
            click   : {
                visible  : true,
                disabled : true,
            },
            cancle : {
                visible  : true,
                disabled : false,
            }
        },
        add         : {
            click   : {
                visible  : true,
                disabled : true,
            },
            selected : {
                visible  : true,
                disabled : false,
            }
            ,
            unSelected : {
                visible  : true,
                disabled : true,
            },
        },
        dbdsb       : false,
        adddsb      : true,
        icon        : 'minus',
        text        : '삭제',
        method      : delEvent,
    },
    saveBtn = {
        class       : 'save-btn',
        box         : null,
        option      : 80,
        disabled    : true,
        dbdsb       : true,
        edit        : {
            click   : {
                visible  : true,
                disabled : false,
            },
            cancle : {
                visible  : true,
                disabled : true,
            }
        },
        add         : {
            click   : {
                visible  : true,
                disabled : false,
            },
            selected : {
                visible  : true,
                disabled : true,
            }
            ,
            unSelected : {
                visible  : true,
                disabled : true,
            },
        },
        adddsb      : false,
        visible     : true,
        icon        : 'save',
        text        : '저장',
    },
   
]
$(()=>{
    $("body").append(modalDiv);
    $(".modal-title").prepend($("<div>수집구간 ID</div>"));
    $(".modal-background").css("display",'none');
    $(".modal-content").append($("<div class='modal-content-title'>")
        .html("수집구간 ID를 입력하십시오."),$("<div class='modal-text'>"));

    _modalText      = new dxNumber($('.modal-text'), 'outlined', 250, null, 0, 9999999999, false, null, 'rse_sect_id', '#', false);
    _modalSaveBtn   = new dxBtn($('.modal-save-Btn'),  '적용', 'check', 'outlined', null, null, false, true);
    _modalCancelBtn = new dxBtn($('.modal-cancle-Btn'),'취소', 'close', 'outlined', null, null, false, true);
    _modalXBtn      = new dxBtn($('.modal-cancle'), null, 'close', 'text', null, null, false, true);
    _modalText.onEnterKey(modalSaveEvent);
    _modalSaveBtn.onClick(modalSaveEvent);
    _modalCancelBtn.onClick(modalCloseEvent);
    _modalXBtn.onClick(modalCloseEvent);

    rseSectId       = new dxNumber($('.rse_sect_id'), 'outlined', 130, 30, 1, 9999999999, true, null, 'rse_sect_id', '#0', true, '수집구간 ID');
    secLngt         = new dxNumber($('.sect_lngt'), 'outlined', 80, 30, 1, 99999, true, null, 'sect_lngt', '#0', true, '연장');
    strtRseCtlrNmbr = new dxNumber($('.strt_rse_ctlr_nmbr'), 'outlined', 130, 30, 1, 9999999999, true, null, 'strt_rse_ctlr_nmbr', '#0', true, '시점 DSRC ID');
    endRseCtlrNmbr  = new dxNumber($('.end_rse_ctlr_nmbr'), 'outlined', 130, 30, 1, 9999999999, true, null, 'end_rse_ctlr_nmbr', '#0', true, '종점 DSRC ID');
    linkId          = new dxNumber($('.link_id'), 'outlined', 100, 30, 1, 999, true, null, 'link_id', '#0', true);
    rseSectNm       = new dxTxt($('.rse_sect_nm'), 'rse_sect_nm', 60, '수집구간명', 200, 30, null, true);
    strtSpotNm      = new dxTxt($('.strt_spot_nm'), 'strt_spot_nm', 60, '시점 DSRC 구간명', 201, 30, null, true);
    endSpotNm       = new dxTxt($('.end_spot_nm'), 'end_spot_nm', 60, '종점 DSRC 구간명', 201, 30, null, true);
    strtMapCheck    = new dxCheck($('.strt-map-click'), '지도에서 선택', false, true, null);
    endMapCheck     = new dxCheck($('.end-map-click'), '지도에서 선택', false, true, null);
    dsrcIdCheck     = new dxCheck($('.dsrc-id-check'), 'DSRC ID', true, false, null);
    const mapSizeUpCheck = new dxCheck($('.map-size-up'), '지도 크게보기', false, false, null);
    mapSizeUpCheck.onValueChanged(mapResize)
    addLinkBtn      = new dxBtn($('.add-link'), '추가', null, 'outlined', null, null, true, true);
    delLinkBtn      = new dxBtn($('.del-link'), '삭제', null, 'outlined', null, null, true, true);
    const closeBtn= new dxBtn($('.close-button'), '닫기', 'close', 'outlined', 80, 30, false, true);
    closeBtn.onClick(()=>window.close());
    addLinkBtn.onClick(addLinkBtnClick);
    delLinkBtn.onClick(delLinkBtnClick);
    strtMapCheck.onValueChanged(strtMapCheckVC);
    endMapCheck.onValueChanged(endMapCheckVC);
    dsrcIdCheck.onValueChanged(dsrcIdCheckVC);
   
    inputArr = [
        rseSectId,
        rseSectNm,
        secLngt,
        strtRseCtlrNmbr,
        strtSpotNm,
        endRseCtlrNmbr,
        endSpotNm,
    ];

    //버튼 박스 화면 세팅
    btnArr.map((item)=>{
        item.box = $('.' + item.class).dxButton({
            icon              : item.icon,
            width             : item.option,
            text              : item.text,
            visible           : item.visible,
            disabled          : item.disabled,
            focusStateEnabled : false,
            stylingMode       : 'outlined',
            onClick(){
                if(item.method){
                    item.method();
                }
            }
        }).dxButton('instance')
    })

    //제어기 선택 테이블
     _listTable = $('.dtct-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        focusedRowEnabled       : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        keyExpr : 'rse_sect_id',
        
        headerFilter: {
            visible: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        columns:[
            {
                dataField    : 'rse_sect_id',
                caption      : 'SECT ID',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
                sortOrder    : 'asc',
                sortIndex    : 1,
                width        : 140,
            },
            {
                dataField    : 'rse_sect_nm',
                caption      : 'SECT 명칭',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
                cellTemplate(c,e){
                    alignTemplate(c, e, 'left');
                }
            },
            {
                dataField    : 'strt_spot_nm',
                caption      : '시점명',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
                cellTemplate(c,e){
                    alignTemplate(c, e, 'left');
                }
            },
            {
                dataField    : 'end_spot_nm',
                caption      : '종점명',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
                cellTemplate(c,e){
                    alignTemplate(c, e, 'left');
                }
            },
            {
                dataField    : 'sect_lngt',
                caption      : '연장',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
            },
        ],
        onRowDblClick(e){
            listTableDblClick(e);
        }
    }).dxDataGrid('instance');
    
    _dsrcTable = $('.dsrc-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        focusedRowEnabled       : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        keyExpr : 'rse_ctlr_nmbr',
        
        headerFilter: {
            visible: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        columns:[
            {
                dataField    : 'rse_ctlr_nmbr',
                caption      : 'ID',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
            },
            {
                dataField    : 'rse_ctlr_id',
                caption      : 'DSRC ID',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
            },
            {
                dataField    : 'rse_nm',
                caption      : '명칭',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
                cellTemplate(c,e){
                    alignTemplate(c, e, 'left');
                }
            },
                    
        ],
        onRowDblClick(e){
            _selectFcltNmbr = e.data.rse_ctlr_nmbr;
            selectFcltObject(_selectFcltNmbr);
        }
    }).dxDataGrid('instance');

    _linkTable = $('.link-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        focusedRowEnabled       : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        keyExpr : 'link_id',
        
        headerFilter: {
            visible: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        columns:[
            {
                dataField : 'link_ord',
                caption   : '-',
                cssClass  : 'padding-ctrl',
                alignment : 'center',
                cellTemplate(c, e) {
                    c.css('background-color', EditLinkColor[e.data.color]);
                }
            },
            {
                dataField    : 'link_id',
                caption      : '링크 ID',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
            },
            {
                dataField    : 'f_node_id',
                caption      : '시작지점 ID',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
            },
            {
                dataField    : 'from_node',
                caption      : '시작지점명',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
                cellTemplate(c,e){
                    alignTemplate(c, e, 'left');
                }
            },
            {
                dataField    : 't_node_id',
                caption      : '종료지점 ID',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
            },
            {
                dataField    : 'to_node',
                caption      : '종료지점명',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
                cellTemplate(c,e){
                    alignTemplate(c, e, 'left');
                }
            },
            {
                dataField    : 'link_leng',
                caption      : '연장',
                cssClass     : 'padding-ctrl',
                alignment    : 'center',
            },
        ],
        onRowDblClick(e){
            _mapManager.extentLayerObject( _lyrLinkIdx, [e.data.link_id] );
        }
    }).dxDataGrid('instance');
    doMap();

    sectionResize($('.e-resize'), $('.body-box'), $('.left-section'), $('.right-section'), null, ()=>{_mapManager.updateSize()}, 'width');
    sectionResize($('.n-resize'), $('.left-section'), $('.left-section > div:nth-child(1)'), $('.left-section > div:nth-child(3)'), null, ()=>{
        _listTable.refresh();
        _dsrcTable.refresh();
    }, 'height');
});

/**
 * DSRC 수집구간 목록 더블 클릭 이벤트
 * @param {*} e Table row 정보
 */
function listTableDblClick(e){
    const row = e.data;
    let data = [];
    getData(_linkRltnApi + '/' + row.rse_sect_id, data);
    inputArr.map((item)=>{
        item.setValue(row[item.column]);
    });
    
    linkInit();

    dataSorting(data[0], 'link_ord');
    _linkData = [];
    let color = 1;
    data[0].map((item)=>{
        const obj = {..._linkMap.get(item.link_id)};
        obj.link_ord = item.link_ord;
        obj.color    = color;
        _linkData.push(obj);
        _mapManager.updateEditLink(_lyrLinkIdx, item.link_id, color++, true);
    })
    _mapManager.extentLayerObject(
        _lyrLinkIdx,
        _linkData.map((obj) => obj.link_id)
    );
    _linkTable.option('dataSource', _linkData);
    dsblOffBtn(editBtn.box);
    dsblOffBtn(delBtn.box);
}

function linkInit(){
    const data = _linkTable.option('dataSource');
    if (data && data.length > 0) {
        data.map((item)=>{
            _mapManager.updateEditLink(_lyrLinkIdx, item.link_id, 0, false);
        })
        _linkTable.option('dataSource', []);
        _linkData = [];
    }
}

/**
 * vds 이름 보이기/숨기기
 * @param {*} e 체크박스 정보
 */
function dsrcIdCheckVC(e){
    _mapManager.showFcltObjectText(_lyrIdx, e.value);
    updateIcon();
}
function strtMapCheckVC(e){
    if (e.value){
        endMapCheck.setValue(false);
    }
}
function endMapCheckVC(e){
    if (e.value) {
        strtMapCheck.setValue(false);
    }
}
function getIdArr(){
    const listData = _listTable.option('dataSource');
    let idArr = [];
    if (listData) {
        listData.map((item)=>{
            idArr.push(item.rse_sect_id);
        })
    }
    return idArr;
}
function modalSaveEvent(){
    const idArr = getIdArr();
    const idVal = _modalText.getValue();
    const label = '수집구간 ID';
    if (_modalText.isNull()) {
        return alertWarning(label + "를 입력해주세요.", null, _modalText);
    }
    else if (idArr.includes(idVal)) {
        return alertWarning(label + " : " + idVal + "<br>이미 사용중인 " + label + "입니다.", null, _modalText);
    }
    else if (_modalText.getByte() > _modalText.max){
        return alertWarning(label + "를 "+ _modalText.max +"바이트 이내로 입력해주세요.", null, _modalText);
    }
    else  {
        modalCloseEvent();
        eventOn();
        boxInit(true);
        cancelBtn.box.off("click");
        cancelBtn.box.on("click", () => addCancel());
        rseSectId.setValue(idVal);
        btnArr.map((item) => {
            item.box.option("visible", item.add.click.visible);
            item.box.option("disabled", item.add.click.disabled);
        });
        linkInit();
        saveBtn.box.off('click');
        saveBtn.box.on('click', () => saveEvent('add'));
        _selCnt = 1;
    }
}
function modalCloseEvent(){
    modalDiv.css('display', 'none');
    _modalText.setValue(null);
}
//마우스 드래그 리사이즈 함수
function sectionResize(position, parent, position1, position2, serve, callBackFunc, type) {
    const dragBorder = position;
    dragBorder.on('mousedown', function(event){
        let clientX = event.clientX;
        let clientY = event.clientY;
        dragBorder.on("dragstart", function(event){
            const dropPosition = parent;
            let whVal1 = type === "width" ? position1.width() : position1.height();
            
            dropPosition.on('dragover', function(event){
                event.preventDefault();
            })
            
            dropPosition.on('drop',function(event){
                event.preventDefault();
                let moveVal = null;
                let position1Val = null;
                if (type === "width") {
                    moveVal = event.clientX - clientX;
                    position1Val = whVal1 + moveVal + 4;
                }
                else if (type === "height") {
                    moveVal = event.clientY - clientY;
                    position1Val = whVal1 + moveVal;
                }
                position1.css(type, position1Val + 'px');
                position2.css(type, 'calc(100% - '+ position1Val + 'px)');
                if (serve) {
                    serve.css(type, serveVal);
                }
                dragBorder.off('dragstart');
                dropPosition.off('dragover');
                dropPosition.off('drop');
                if (callBackFunc) {
                    callBackFunc();
                }
            })
        });
    })

    dragBorder.on('dblclick',()=>{
        const firstVal1 = type === "width" ? 419 : 278;
        position1.css(type, firstVal1);
        position2.css(type, 'calc(100% - ' + firstVal1 + 'px)');
        if (callBackFunc) {
            callBackFunc();
        }
    })
}

function mapResize(e){
    let display;
    let height;
    if (e.value) {
        display = 'none';
        height = 'calc(100% - 245px)';
    }
    else {
        display = 'block';
        height = 'calc(100% - 352px)';
    }
    $('.map-size-toggle').css('display', display);
    $('.map-box').css('height', height);
    _mapManager.updateSize();
}

function editEvent(){
    cancelBtn.box.off('click');
    cancelBtn.box.on('click', () => editCancle());

    eventOn();
    
    buttonReset('add', 'click');

    saveBtn.box.off('click');
    saveBtn.box.on('click', () => saveEvent('edit'));
    let data = _linkTable.option('dataSource');
    if (data && data.length > 0) {
        _selCnt = data.length % 19 + 1;
        if (_selCnt === 0) {
            _selCnt = 1;
        }
    }
}

/**
 * 저장 버튼 클릭 이벤트
 * @param {*} type add/edit 
 * @returns 
 */
function saveEvent(type){
    for (let input of inputArr) {
        const value = input.getValue();
        let   max   = input.getByte();
        const label = input.label;
        if (input.isNull()) {
            return alertWarning('필수 항목을 입력해주세요. [ ' + label +' ]', null, box);
        }
        else {
            if (max && getByteLength(value) > max) {
                return alertWarning(max + ' 바이트 이내로 입력해주세요. [ ' + label +' ]', null, box);
            }
        }
    }
    const sectId = rseSectId.getValue();
    let updateData = {..._updateColumns}
    
    if (type === 'edit') {
        const rowData = _listTable.getSelectedRowsData()[0];
        for (let key in updateData) {
            updateData[key] = rowData[key];
        }
    }

    inputArr.map((item)=>{
        if (item.column && nullChecker(item.getValue()) !== '') updateData[item.column] = item.getValue();
    })
    const linkData = _linkTable.option('dataSource');
    dataSorting(linkData, 'link_ord');
    let updateLinkData = {
        links: [
        ],
        rse_sect_id: sectId
    };

    linkData.map((item)=>{
        updateLinkData.links.push(
            {
                link_id     : item.link_id,
                link_ord    : item.link_ord,
            }
        )
    });

    let result = postInsertUpdate(_apiUri + '/' + sectId, updateData);
    if (result > 0 ){
        result = postInsertUpdate(_linkRltnApi + '/' + sectId, updateLinkData);
        if (result > 0) {
            insResultMsg(pageMsg);
            eventCancel();
            let listData = [];
            getData(_apiUri, listData);
            _listTable.option('dataSource', listData[0]);
            _listTable.refresh().done(()=>{
                _listTable.selectRows(sectId);
                _listTable.option('focusedRowKey', sectId);
                buttonReset('add','selected');
            })
        }
    }
}

function editCancle(){
    eventCancel();
    boxPull();
    buttonReset( 'edit', 'cancle' );
}

function addCancel(){
   
    eventCancel();

    if (_listTable.getSelectedRowsData().length > 0){
        boxPull();
        buttonReset('add','selected');
    }
    else  {
        boxInit();
        linkInit();
        buttonReset('add','unSelected');
    }

}

function addEvent(){
    modalDiv.css('display', 'flex');
    _modalText.focus();
}

//리스트에 선택된 데이터 가져오기
function boxPull(){
    //선택 row 데이터
    let selectedRow = _listTable.getSelectedRowsData()[0];
    let data = [];
    getData(_linkRltnApi + '/' + selectedRow.rse_sect_id, data);
   
    //텍스트 상자에 값 입력
    inputArr.map((item)=>{
        item.setValue(selectedRow[item.column]);
    });

    linkInit();

    dataSorting(data[0], 'link_ord');
    _linkData = [];
    let color = 1;
    data[0].map((item)=>{
        const obj = {..._linkMap.get(item.link_id)};
        obj.link_ord = item.link_ord;
        obj.color    = color;
        _linkData.push(obj);
        _mapManager.updateEditLink(_lyrLinkIdx, item.link_id, color++, true);
    })
    _mapManager.extentLayerObject(
        _lyrLinkIdx,
        _linkData.map((obj) => obj.link_id)
    );
    _linkTable.option('dataSource', _linkData);
}

function boxInit(){
    inputArr.map((item)=>{
        item.setValue(null); 
    });
    strtMapCheck.setValue(false);
    endMapCheck.setValue(false);
    linkId.setValue(null);
}

function buttonReset(eventName, option){
    btnArr.map((item)=>{
        item.box.option( 'visible', item[eventName][option].visible   );
        item.box.option( 'disabled', item[eventName][option].disabled );
    })
}

function eventCancel(){
    dsblOffBtn(_listTable);
    dsblOffBtn(_dsrcTable);
    inputArr.map((item)=>{
        item.setReadOnly(true);
    });
    strtMapCheck.setReadOnly(true);
    endMapCheck.setReadOnly(true);
    addLinkBtn.setDisabled(true);
    delLinkBtn.setDisabled(true);
}

function eventOn(){
    dsblOnBtn(_listTable);
    dsblOnBtn(_dsrcTable);
    const hideColumns = ['rse_sect_id', 'strt_rse_ctlr_nmbr', 'end_rse_ctlr_nmbr', 'sect_lngt'];
    inputArr.map((item)=>{
        if (!hideColumns.includes(item.column)) {
            item.setReadOnly(false);
        }
    });
    strtMapCheck.setReadOnly(false);
    endMapCheck.setReadOnly(false);
    addLinkBtn.setDisabled(false);
    delLinkBtn.setDisabled(false);
}


function vailableAlert(box, msg){
    if(nullChecker(box.box.option('value')) === ''){
        box.box.focus();
        alertWarning(msg, null, box.box);
        return false;
    }
    return true;
}


/**
 * 지도 인터페이스 함수........
 */
 function doMap() {
    _mapManager = new TMapMngr('traf-hs-map', 'tooltip');
    const data = _trafficMap.get('link');
    const vrtx = _trafficMap.get('link1');
    const node = _trafficMap.get('node'); // 노드정보 요청
    _mapManager.setEditMode(_lyrIdx, true);
    _mapManager.showLayer(_lyrIdx, true);
    _mapManager.showFcltObjectText(_lyrIdx, true);
    _mapManager.onFcltDragEndFunc = onFcltDragEndFunc; // 객체(시설물) 편집시 객체 이동후 좌표 반환
    _mapManager.onMouseClickFunc = onMouseClickFunc; // 객체 마우스 클릭 이벤트 반환
    _mapManager.onSelectObjFunc = null; // 객체 선택 이벤트 반환
    _mapManager.setLayerVisible(_lyrLinkIdx, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
    _mapManager.setEditMode(_lyrLinkIdx, true);
    _mapManager.setSelectMode(false);
    _mapManager.setZoom(15);
    _mapManager.makeLayer(LayerIndex.Node, node);
    _mapManager.makeTrafficObject(_lyrType, data);
    _mapManager.makeLayer(_lyrLinkIdx, vrtx);
    data.map((item)=>{
        _linkMap.set(item.link_id, item);
    })
    fetchBaseData();
    fetchMapIconBar($('.map-bar'), _mapManager, _lyrIdx, _pageName);
   
}

function addLinkBtnClick(){
    const linkIdVal = linkId.getValue();
    const linkIdArr = getLinkIdArr();
    if (linkIdArr.includes(linkIdVal)) {
        return ;
    }
    
    if (nullChecker(linkIdVal) !== "") {
        const obj = {..._linkMap.get(linkIdVal)};
        _mapManager.updateEditLink(_lyrLinkIdx, linkIdVal, _selCnt, true);
        obj.color = _selCnt++;
        obj.link_ord = _linkData.length + 1;
        _linkData.push(obj);
        if (_linkData.length > 0) {
            let lngtVal = 0;
            _linkData.map((item)=>{
                lngtVal = lngtVal + item.link_leng;
            })
            secLngt.setValue(lngtVal);
        }
        _linkTable.option('dataSource', _linkData);
        if (_selCnt === 19) _selCnt = 1;
        linkId.setValue(null);
    }
}
function delLinkBtnClick(){
    const selectedData = _linkTable.getSelectedRowsData();
    if (selectedData.length > 0) {
        const row = selectedData[0];
        let data = _linkTable.option('dataSource');
        let cnt = 1;
        _linkData = [];
        let totLngt = 0;
        data.map((item)=>{
            let obj = {...item};
            if (obj.link_ord !== row.link_ord) {
                obj.link_ord = cnt++;
                _linkData.push(obj);
                totLngt += obj.link_leng;
            }
        })
        secLngt.setValue(totLngt);
        _linkTable.option('dataSource', _linkData);
        _linkTable.option('focusedRowIndex', -1);
        _mapManager.updateEditLink(_lyrLinkIdx, row.link_id, 0, false);
    }
}

function getLinkIdArr(){
    let linkIdArr = [];
    if (_linkData.length > 0) {
        _linkData.map((item)=>{
            linkIdArr.push(item.link_id);
        });
    }
    return linkIdArr;
}

function onSelectObjFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY, X, Y) {
    
    if (ALyrIdx != _lyrLinkIdx) {
        return;
    }
    let selObj = _selObjMap.get(ANmbr);
    if (!selObj) {
        selObj = new TSelObj(ANmbr, ACoordX.toFixed(8), ACoordY.toFixed(8));
    }
    else {
        // 기존 데이터의 x,y 좌표만 업데이트 수행
        selObj = new TSelObj(ANmbr, ACoordX.toFixed(8), ACoordY.toFixed(8));
        _selObjMap.set(ANmbr, selObj);
        return;
    }

    _selObjMap.forEach((obj) => {
        _mapManager.updateEditLink(_lyrLinkIdx, obj.id, 0, false);
    });

    _selObjMap.clear();
    selObj.link_color = 1; 
    
    setValue(linkId.box, ANmbr);
    _selObjMap.set(ANmbr, selObj);
    _mapManager.updateEditLink(_lyrLinkIdx, ANmbr, selObj.link_color, true);
};

async function fetchBaseData() {
    let dsrcListData;
    let listData;
    dsrcListData = apiGet('/api/rse/tb_rse_ctlr');
    listData = apiGet('/api/rse/tb_rse_sect');
    //Promise.all([node, data, vrtx, dsrcListData])
    Promise.all([dsrcListData, listData])
        .then((results) => Promise.all(results.map((r) => r.json())))
        .then((values) => {
            _dsrcTable.option('dataSource', values[0]);
            _listTable.option('dataSource', values[1]);
            _managerData = values[0];
            updateIcon();
            //console.log(`BaseData, NODE(${values[0].length}), LINK/IFSC(${values[1].length}), VRTX(${values[2].length})`);
        })
        .catch((err) => {
            console.error(`Error in fetchBaseData ${err}`);
        })
        .finally(() => console.timeEnd('***** fetchBaseData: '));
}

function onFcltDragEndFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY) {
    if (ALyrIdx != _lyrIdx) {
        return;
    }
    if (ANmbr === _selectFcltNmbr) {
        cctvX.box.option('value', ACoordX.toFixed(7));
        cctvY.box.option('value', ACoordY.toFixed(7));
    }
    console.log(`onFcltDragEndFunc, ${ALyrIdx}, ${ALyrName}, ${ANmbr}, ${ACoordX}, ${ACoordY}`);
}

function onMouseClickFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY, X, Y) {
    // console.log(`onMouseClickFunc, ${ALyrIdx}, ${ALyrName}, ${ANmbr}, ${ACoordX}, ${ACoordY}, ${X}, ${Y}`);
    // console.log(_lyrIdx);
    // console.log(ALyrIdx);
    if (ALyrIdx !== _lyrIdx && ALyrIdx !== _lyrLinkIdx) {
        return;
    }
    const obj = _mapManager.findLayerObject(ALyrIdx, ANmbr);
   
    // if (!obj) {
    //     return;
    // }
    // else 
    if (cancelBtn.box.option('visible') === false) {
        return;
    }
    else if (ALyrIdx === _lyrLinkIdx){ 
        linkId.setValue(ANmbr);
    }
    else {
        if (strtMapCheck.getValue() === true) {
            strtRseCtlrNmbr.setValue(obj.NMBR);
            strtSpotNm.setValue(obj.NAME);
        }
        else if (endMapCheck.getValue() === true) {
            endRseCtlrNmbr.setValue(obj.NMBR);
            endSpotNm.setValue(obj.NAME);
        }
    }
}

/**
 * 지도에 시설물 객체 정보를 그린다.
 */
 function updateIcon() {
    // 기존 객체를 모두 삭제한다.
    _mapManager.removeLayerObject(_lyrIdx);
    if (_managerData && _managerData.length > 0) {
        // 시설물 객체를 지도에 그린다.
        const objs = new Array();
        _managerData.forEach((obj) => {
            const item = new TFclt(obj.rse_ctlr_nmbr, obj.istl_lctn_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 linkBtnClick(){
    if (_prevLinkId !== null) {
        _mapManager.updateEditLink(_lyrLinkIdx, _prevLinkId, 0, true);
        _prevLinkId = null;
        setValue(linkId.box, null);
    }
    _mapManager.onSelectObjFunc = onSelectObjFunc;
}

function listSorting(data, option1, option2) {
    data.sort(function(a,b){
        return a[option1] > b[option1] ? 1 : a[option2] > b[option2] ? 1 : -1;
    })
}

function delEvent(){
    const sectId = _listTable.getSelectedRowsData()[0].rse_sect_id;
    confirmMessage(pageMsg 
        + ' ID : ' 
        + sectId 
        + '<br>선택하신 ' 
        + pageMsg 
        + ' 정보를 삭제하시겠습니까?').done((yes)=>{
            if (yes === true){
                const selectedData = _listTable.getSelectedRowsData()[0];
                let result = deleteData(_apiUri, sectId);
                if (result > 0) {
                    delResultMsg(pageMsg);
                    boxInit();
                    linkInit();
                    buttonReset('add','unSelected');
                    _listTable.option('focusedRowKey', null);
                    let data = [];
                    refresh( _listTable, data, _apiUri);
                }
            }
    });
}