import { TMapMngr } 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;
const _lyrType  = LayerType.ROAD;
const _lyrIdx   = LayerIndex.Road1;
const _btnMap   = new Map();
const _pageName = '간선도로 정보';
let   _idArr    = [];
let   _btnOn    = false;
class TRoadInfo {
    constructor(atrd_id, ord, road_id, road_name, strt_nm, end_nm, f_node_id, t_node_id, sect_lngt) {
        this.atrd_id = atrd_id;
        this.ord = ord;
        this.road_id = road_id;
        this.road_name = road_name;
        this.strt_nm = strt_nm;
        this.end_nm = end_nm;
        this.f_node_id = f_node_id;
        this.t_node_id = t_node_id;
        this.sect_lngt = sect_lngt;
    }
}

class TSelObj {
    constructor(obj, color) {
        this.atrd_id = obj.atrd_id;
        this.ord = obj.ord;
        this.road_id = obj.road_id;
        this.road_name = obj.road_name;
        this.strt_nm = obj.strt_nm;
        this.end_nm = obj.end_nm;
        this.t_node_id = obj.t_node_id;
        this.f_node_id = obj.f_node_id;
        this.sect_lngt = obj.sect_lngt;
        this.color = color;
    }
}
const _selObjMap = new Map();
let _selIdx = 1;

let atrdData             = [];
let _atrdEditTable       = null;
let _linkIdText          = null;
let _atrdIdText          = null;
let _atrdNmText          = null;
let _atrdDircSelect      = null;
let _atrdList            = null;
let _modalIdText         = null;
const dirc = [{drct_cd : '0', drct_cd_desc : '[0] 상행'},{drct_cd : '1', drct_cd_desc : '[1] 하행'}];
const btnClasses = [
    'link-add-btn',
    'link-del-btn',
    'add-btn',
    'del-btn',
    'edit-btn',
    'save-btn',
    'cancle-btn',
    'move-down-btn',
    'move-up-btn',
];

$(() => {
    $('body').append(modalDiv);
    $(".modal-title").prepend($("<div>간선도로 ID</div>"));
    $(".modal-background").css("display",'none');
    $('.modal-content').append($("<div>신규 간선도로 ID를 입력하세요</div><div class='modal-id'></div>"))

    //모달 road_id 입력 창
    _modalIdText = $('.modal-id').dxTextBox({
        stylingMode : "outlined",
        width       : '80%',
        height      : 30,
        maxLength   : 10,
        onEnterKey(e) {
            insertRoadId(getValue(e.component));
        },
    }).dxTextBox('instance');

    //모달 x 버튼
    creatBtn($(".modal-cancle"), "close", null, "닫기", "text", modalCancle);

    //모달 저장 버튼
    creatBtn( $(".modal-save-Btn"), "save", "저장", null, "outlined", () => insertRoadId(getValue(_modalIdText)));

    //모달 취소 버튼
    creatBtn( $(".modal-cancle-Btn"), "close", "취소", null, "outlined", modalCancle);

    //도로 ID 텍스트
    _atrdIdText = $(".atrd_id").dxTextBox({
        stylingMode : "outlined",
        width       : 150,
        height      : 30,
        readOnly    : true,
    }).dxTextBox('instance');

    //도로명 텍스트
    _atrdNmText = $(".atrd_nm").dxTextBox({
        stylingMode : "outlined",
        width       : 220,
        height      : 30,
        maxLength   : 30,
        readOnly    : true,
    }).dxTextBox('instance');

    //도로 방향 셀렉트
    _atrdDircSelect = $(".drct_cd").dxSelectBox({
        stylingMode : "outlined",
        width       : 160,
        height      : 30,
        items       : dirc,
        displayExpr : "drct_cd_desc",
        valueExpr   : "drct_cd",
        readOnly    : true,
    }).dxSelectBox('instance');

    //링크 ID 텍스트
    _linkIdText = $(".link-id-text").dxTextBox({
        stylingMode : "outlined",
        width       : 100,
        height      : 25,
        readOnly    : true,
    }).dxTextBox('instance');

    //상단 닫기 버튼
    creatBtn($('.close-btn'), "close", "닫기", null, "outlined", ()=>{window.close()}, 80);

    //간선도로 리스트 테이블
    _atrdList = $(".atrd-table")
        .width("100%")
        .height("100%")
        .dxDataGrid({
            dataSource              : null,
            allowColumnReordering   : true,
            showColumnLines         : true,
            allowColumnResizing     : true,
            showBorders             : true,
            rowAlternationEnabled   : true,
            columnAutoWidth         : true,
            noDataText              : "표출할 정보가 없습니다.",
            focusedRowEnabled       : true,
            keyExpr                 : "atrd_id",
            selection: {
                mode: "single",
            },
            scrolling               : {
                mode : 'standard',
            },
            paging: {
                enabled: true,
                pageSize: 1000,
            },
            headerFilter: {
                visible: true,
            },
            export: {
                enabled: true,
                texts: {
                    exportAll: "엑셀 파일",
                },
            },
            onExporting(e) {
                gridExcellExporting(e, _pageName);
            },
            columns: [
                {
                    dataField: "atrd_id",
                    caption: "도로 ID",
                    alignment: "center",
                    width: 126,
                    sortIndex: 0,
                    sortOrder: "asc",
                },
                {
                    dataField: "atrd_nm",
                    caption: "도로명",
                    alignment: "center",
                    cellTemplate(c, e) {
                        let result = nullChecker(e.displayValue);
                        return $('<div style="text-align: left;">' + result + "</div>");
                    },
                },
                {
                    dataField: "drct_desc",
                    caption: "방향",
                    alignment: "center",
                },
                {
                    dataField: "area_cd",
                    caption: "지역코드",
                    alignment: "center",
                },
                {
                    dataField: "del_yn",
                    caption: "삭제 여부",
                    alignment: "center",
                },
            ],
            onRowDblClick(row) {
                atrdTableDblClick(row);
            },
        })
        .dxDataGrid("instance");

    //간선도로 편집 테이블
    _atrdEditTable = $(".atrd-edit-table")
        .width("100%")
        .height("100%")
        .dxDataGrid({
            dataSource              : null,
            allowColumnReordering   : true,
            showColumnLines         : true,
            allowColumnResizing     : true,
            showBorders             : true,
            rowAlternationEnabled   : true,
            focusedRowEnabled       : true,
            columnAutoWidth         : true,
            noDataText: "표출할 정보가 없습니다.",
            keyExpr: "ord",
            scrolling               : {
                mode : 'standard',
            },
            sorting: {
                mode : "none",
            },
            paging: {
                enabled: true,
                pageSize: 1000,
            },
            selection: {
                mode: "single",
            },
            columns: [
                {
                    dataField: "-",
                    caption: "-",
                    alignment: "center",
                    width: 50,
                    cellTemplate(c, e){
                        c.css('background-color', EditLinkColor[e.data.color]);
                    }
                },
                {
                    dataField : 'ord',
                    visible   : false,
                    sortIndex : 0,
                    sortOrder : 'asc',
                },
                {
                    dataField : "road_id",
                    caption   : "도로 ID",
                    alignment : "center",
                },

                {
                    dataField: "strt_nm",
                    caption: "시작지점명",
                    alignment: "center",
                    cellTemplate(c, e) {
                        let result = nullChecker(e.data.strt_nm);
                        return $('<div style="text-align: left; padding-left: 10px;">' + result + "</div>");
                    },
                },
                {
                    dataField: "end_nm",
                    caption: "종료지점명",
                    alignment: "center",
                    cellTemplate(c, e) {
                        let result = nullChecker(e.data.end_nm);
                        return $('<div style="text-align: left; padding-left: 10px;">' + result + "</div>");
                    },
                },
                // 도로명(road_name), 시작지점ID(f_node_id), 종료지점ID(t_node_id)
                {
                    dataField: "sect_lngt",
                    caption: "구간 길이",
                    alignment: "center",
                },
            ],
            onRowDblClick(row) {
                atrdEditTableDblClick(row);
            },
        })
        .dxDataGrid("instance");

    //버튼 화면 세팅
    fetchButtons();

    //맵 세팅
    doMap();
});

/**
 * 지도
 */
function doMap() {
    _mapManager = new TMapMngr("map", "tooltip");
    _mapManager.onSelectObjFunc = onSelectObjFunc; // 객체 선택 이벤트 반환

    _mapManager.setLayerVisible(_lyrIdx, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
    _mapManager.setEditMode(_lyrIdx, true);
    _mapManager.setSelectMode(true);
    _mapManager.setZoom(15);
    fetchListData();
    fetchBaseData();
    fetchMapIconBar($('.map-bar'), _mapManager, _lyrIdx, '간선도로 관리');
}
function onSelectObjFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY, X, Y) {
    if (ALyrIdx != _lyrIdx) {
        return;
    }
    // 편집모드 이면 리턴
    let selObj = _selObjMap.get(ANmbr);
    setValue(_linkIdText, ANmbr);
    if (selObj) {
        console.log("이미 등록된 도로 정보임....");
        return;
    }
    // 링크 ID 박스에 추가(ANmbr)
    // 추가 버튼 클릭하면 목록에 추가함
}

async function fetchBaseData() {
    console.time("***** fetchBaseData: ");

    const road = apiGet("/api/database/road/list"); // 도로정보 요청
    const vrtx = apiGet("/api/manage/main/map/vrtx/road/5"); // 버텍스정보 요청(5 => 13)
    Promise.all([road, vrtx])
        .then((results) => Promise.all(results.map((r) => r.json())))
        .then((values) => {
            _mapManager.makeTrafficObject(_lyrType, values[0]);
            _mapManager.makeLayer(_lyrIdx, values[1]);
            console.log(`BaseData, ROAD(${values[0].length}), VRTX(${values[1].length})`);
        })
        .catch((err) => {
            console.error(`${currDt()}: Error in fetchBaseData ${err}`);
        })
        .finally(() => console.timeEnd("***** fetchBaseData: "));
}

function fetchListData(method){
    getDataAsync("/api/database/atrd", (jsonData)=>{
        atrdData = jsonData;
        _idArr   = [];
        if (atrdData.length > 0){
            atrdData.map((obj)=>{
                _idArr.push(obj.atrd_id);
            })
        }
        _atrdList.option('dataSource', atrdData);
        _atrdList.clearSelection();
        if (method) {
            method();
        }
    }, null, null, true);
}
function fetchAtrdRoadRltn(AAtrdId) {
    // 기존 데이터 지도 선택 클리어
    if(_selObjMap.size > 0){
        _selObjMap.forEach((obj) => {
            _mapManager.updateEditLink(_lyrIdx, obj.road_id, 0, false);
        });
    }

    // 전역데이터 초기화
    _selObjMap.clear();
    _selIdx = 1;

    // 간선도로에 속한 도로정보 조회
    let atrdInfo = [];
    getData("/api/database/atrd/" + AAtrdId, atrdInfo);
    let nmbrs = [];
    if (atrdInfo[0]) {
        atrdInfo[0].roads.sort(function(a,b){
            return  a['ord'] < b['ord'] ? -1 : 1;
        });
        atrdInfo[0].roads.forEach((road) => {
            _selObjMap.set(road.road_id, new TSelObj(road, _selIdx));
            _mapManager.updateEditLink(_lyrIdx, road.road_id, _selIdx, false);
            _selIdx++;
            if (_selIdx === 19) _selIdx = 1;
            nmbrs.push(road.road_id);
        });

    }

    // 간선도로 도로정보 표출
    const data = Array.from(_selObjMap.values());
    _atrdEditTable.option("dataSource", data);
    _mapManager.extentLayerObject(
        _lyrIdx,
        data.map((obj) => obj.road_id)
    );
}

/**
 * 버튼 이벤트
 */
//편집 버튼 이벤트
function editEvent(){
    eventOn();
}

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

//추가 버튼 이벤트
function addEvent(){
    $(".modal-background").css("display", 'flex');
    _modalIdText.focus();
}

//이벤트 활성화
function eventOn(){
    dsblOnBtn(_atrdList);
    _atrdNmText.option('readOnly', false);
    _atrdDircSelect.option('readOnly', false);

    btnClasses.forEach((btnClass) => {
        const btnBox = _btnMap.get(btnClass);
        if(btnBox.get('on')){
            let visible = btnBox.get('on')[0];
            let disabled = btnBox.get('on')[1];
            btnBox.get('btn').option('visible', visible);
            btnBox.get('btn').option('disabled', disabled);
        }
    });

}

//이벤트 비활성화
function eventOff(){
    dsblOffBtn(_atrdList);
    _atrdNmText.option('readOnly', true);
    _atrdDircSelect.option('readOnly', true);

    if (_atrdList.getSelectedRowsData().length > 0){
        const atrd_id = _atrdList.getSelectedRowsData()[0].atrd_id
        fetchAtrdRoadRltn(atrd_id);
        setValue(_atrdIdText, atrd_id);
        setValue(_atrdNmText, _atrdList.getSelectedRowsData()[0].atrd_nm);
        setValue(_atrdDircSelect, _atrdList.getSelectedRowsData()[0].drct_cd);
        _btnOn = true;
    }
    else {
        _atrdEditTable.option('dataSource', []);
        textBoxInit();
        _atrdEditTable.clearSelection();
        _atrdEditTable.option('focusedRowIndex', -1);
        _btnOn = false;
    }

    btnClasses.forEach((btnClass) => {
        const btnBox = _btnMap.get(btnClass);

        if(btnBox.get('off')){
            let visible = btnBox.get('off')[0];
            let unselect = btnBox.get('off')[1];
            let select = btnBox.get('off')[2];
            btnBox.get('btn').option('visible', visible);
            let disabled = _btnOn? select : unselect;
            btnBox.get('btn').option('disabled', disabled);
        }
    });

}

//링크 추가 이벤트
function linkAddBtnClick(){
    const roadId = getValue(_linkIdText);
    const atrdId = getValue(_atrdIdText);
    const selObj = _selObjMap.get(roadId);
    if (selObj) {
        console.log("이미 등록되어 있는 도로정보입니다.");
        return;
    }
    const road = _mapManager.findRoadObject(roadId);
    if (road) {
        const roadInfo = new TRoadInfo(atrdId, _selObjMap.size+1, roadId, road.NAME, road.STRT_NM, road.END_NM, road.fNodeId, road.tNodeId, road.SECT_LNGT);
        _selObjMap.set(roadId, new TSelObj(roadInfo, _selIdx));
        _mapManager.updateEditLink(_lyrIdx, roadId, _selIdx, false);
        _selIdx++;
        if (_selIdx === 19)  _selIdx = 1;
        const data = Array.from(_selObjMap.values());
        _atrdEditTable.option("dataSource", data);
        setValue(_linkIdText, "");
    }
}

//링크 삭제 이벤트
function linkDelBtnClick(){
    const roadId =_atrdEditTable.getSelectedRowsData()[0].road_id;
    if (roadId) {
        _selObjMap.delete(roadId);
        let dataSource = Array.from(_selObjMap.values());
        dataSource.sort(function(a,b){
            return a["ord"] - b["ord"];
        })
        _atrdEditTable.option("dataSource", dataSource);
        _mapManager.updateEditLink(_lyrIdx, roadId, 0, false);
        _atrdEditTable.refresh().done(()=>{
            if(nullChecker(_atrdEditTable.option('focusedRowIndex')) !== ""){
                _atrdEditTable.selectRows(_atrdEditTable.getKeyByRowIndex(_atrdEditTable.option('focusedRowIndex')), true);
            }
        })
    }

}

//위, 아래 리스트 이동 이벤트
let isMove = true;
function listMove(changeNum){
    if (!isMove) {
        console.log("dup click. move dn");
        return;
    }
    const selRowKeys = _atrdEditTable.getSelectedRowKeys();
    if (selRowKeys == 0) {
        console.log("unselected: ", _atrdEditTable.getSelectedRowsData().length);
        return;
    }
    const selectKey = selRowKeys[0];
    const selectRow = _atrdEditTable.getRowIndexByKey(selectKey);
    const changeRow = selectRow + changeNum;
    let result = false;
    if(changeNum === 1){
        result = changeRow < _atrdEditTable.option('dataSource').length ? true : false;
    }
    else{
        result = changeRow >= 0 ? true : false;
    }

    if (result) {
        isMove = false;
        const dataSource = [..._atrdEditTable.option('dataSource')];
        dataSource.sort(function(a,b){
            return a['ord'] - b['ord'];
        })
        const selectData = {...dataSource[selectRow]};
        const changeData = {...dataSource[changeRow]};
        const columns = ['atrd_id', 'color', 'end_nm', 'f_node_id', 'road_id', 'road_name', 'sect_lngt', 'strt_nm', 't_node_id'];
        columns.forEach((column) => {
            dataSource[selectRow][column] = changeData[column];
            dataSource[changeRow][column] = selectData[column];
        });
        _selObjMap.set(dataSource[selectRow].road_id, dataSource[selectRow]);
        _selObjMap.set(dataSource[changeRow].road_id, dataSource[changeRow]);
        _atrdEditTable.option('dataSource', dataSource);

        _atrdEditTable.refresh().done(()=>{
            _atrdEditTable.clearSelection();
            _atrdEditTable.selectRowsByIndexes(changeRow);
            _atrdEditTable.option('focusedRowIndex', changeRow);
            isMove = true;
        });
    }
}

//버튼 생성 및 화면 세팅
function fetchButtons(){
    btnClasses.forEach((btnClass) => {
        _btnMap.set(btnClass, new Map());
        const btnBox = _btnMap.get(btnClass);
        switch (btnClass) {
            case 'link-add-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "add", "추가", null, "outlined", linkAddBtnClick, null, true, true));
                btnBox.set('on', [true, false]);
                btnBox.set('off', [true, true, true]);
                break;
            case 'link-del-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "minus", "삭제", null, "outlined", linkDelBtnClick, null, true, true));
                btnBox.set('on', [true, false]);
                btnBox.set('off', [true, true, true]);
                break;
            case 'add-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "add", "추가", null, "outlined", addEvent, null, false, true));
                btnBox.set('on', [true, true]);
                btnBox.set('off', [true, false, false]);
                break;
            case 'del-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "minus", "삭제", null, "outlined", delEvent, null, true, true));
                btnBox.set('on', [true, true]);
                btnBox.set('off', [true, true, false]);
                btnBox.set('dbl', true);
                break;
            case 'edit-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "edit", "편집", null, "outlined", editEvent, null, true, true));
                btnBox.set('dbl', true);
                btnBox.set('off', [true, true, false]);
                btnBox.set('on', [false, false]);
                break;
            case 'save-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "save", "저장", null, "outlined", saveEvent, null, true, true));
                btnBox.set('on', [true, false]);
                btnBox.set('off', [true, true, true]);
                break;
            case 'cancle-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "close", "취소", null, "outlined", cancleEvent, null, false, false));
                btnBox.set('on', [true, false]);
                btnBox.set('off', [false, false, false]);
                break;
            case 'move-up-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "spinup", "위로", null, "outlined", ()=>{listMove(-1);}, 95, true, true));
                btnBox.set('on', [true, false]);
                btnBox.set('off', [true, true, true]);
                break;
            case 'move-down-btn':
                btnBox.set('btn', creatBtn($('.' + btnClass), "spindown", "아래로", null, "outlined", ()=>{listMove(1);}, 95, true, true));
                btnBox.set('on', [true, false]);
                btnBox.set('off', [true, true, true]);
            default:
                break;
        }
    })

}

//삭제 이벤트
function delEvent(){
    const atrd_id = _atrdList.getSelectedRowsData()[0].atrd_id;

    confirmMessage("간선 도로 ID : " + atrd_id + "<br>선택하신 간선도로 정보를 삭제하시겠습니까?").done((yes) => {
        if (yes === true) {
            const result = deleteData('/api/database/atrd', atrd_id);
            if(result > 0){
                delResultMsg("간선 도로 ID : " + atrd_id + "<br>간선 도로");
                fetchListData(()=>{
                    _atrdList.refresh().done(()=>{
                        _atrdList.option('focusedRowIndex', -1);
                        eventOff();
                    })
                });

                if(_selObjMap.size > 0){
                    _selObjMap.forEach((obj) => {
                        _mapManager.updateEditLink(_lyrIdx, obj.road_id, 0, false);
                    })
                };

                _selObjMap.clear();
                return
            }
            //return alertError('간선도로 정보가 삭제되지 않았습니다.');
        }
    });

}

//저장 이벤트
function saveEvent(){
    let atrdId = getValue(_atrdIdText);
    let atrdNm = getValue(_atrdNmText);
    if (atrdId) {
        atrdId = atrdId.trim();
    }
    if (atrdNm){
        atrdNm = atrdNm.trim();
    }

    let updateData = {
        area_cd: "LAT001",
        atrd_id: atrdId,
        atrd_nm: atrdNm,
        del_yn : 'N',
        drct_cd: getValue(_atrdDircSelect),
        roads:[]
    }
    const dataSource = _atrdEditTable.option('dataSource');
    dataSource.map((item, idx)=>{
        updateData.roads.push({
            ord : idx + 1,
            road_id: item.road_id,
        })
    });
    const frontContent = '간선도로 ID : ' + atrdId + '<br>';
    switch (true) {
        case !updateData.atrd_nm:
            alertWarning(frontContent + '도로명을 입력해주세요.', null, _atrdNmText);
            break;
        case getByteLength(updateData.atrd_nm) > 30:
            alertWarning(frontContent + '도로명은 30바이트 이내로 입력해주세요.', null, _atrdNmText);
            break;
        case updateData.drct_cd === null :
            alertWarning(frontContent + '방향을 선택해주세요.', null, _atrdDircSelect);
            break;
        case updateData.roads.length <= 0:
            alertWarning(frontContent + '간선도로 구간 구성 정보를 추가해주세요');
            break;
        default:
            const result = postInsertUpdate('/api/database/atrd/' + updateData.atrd_id, updateData);
            if(result > 0){
                insResultMsg(frontContent + '간선 도로');
                fetchListData(()=>{
                    _atrdList.clearSelection();
                    _atrdList.refresh().done(()=>{
                        _atrdList.selectRows(atrdId, true).done(()=>{
                            _atrdList.option('focusedRowKey', atrdId);
                            eventOff();
                        })
                    })
                });
            }
            //alertError('간선도로 정보가 저장되지 않았습니다.');
            break;
    }
}

/**
 * 테이블 더블 클릭 이벤트
 */
//간선도로 리스트 테이블 더블클릭
function atrdTableDblClick(row){
    const data = row.data;
    setValue(_atrdIdText, data.atrd_id);
    setValue(_atrdNmText, data.atrd_nm);
    setValue(_atrdDircSelect, data.drct_cd);
    fetchAtrdRoadRltn(data.atrd_id);

    if(!_btnOn){
        btnClasses.forEach((btnClass) => {
            const btnBox = _btnMap.get(btnClass);
            if(btnBox.get('dbl')){
                dsblOffBtn(btnBox.get('btn'));
            }
        });
        _btnOn = true;
    }
    _atrdEditTable.option('focusedRowIndex', -1);
    _atrdEditTable.clearSelection();
};

//간선도로 편집 테이블 더블클릭
function atrdEditTableDblClick(row){
    _mapManager.extentLayerObject( _lyrIdx, [row.data.road_id] );
}


/**
 * 모달 관련 이벤트
 */
//모달 값 도로 ID 텍스트 전달
function insertRoadId(value){
    const val = value;
    if(!val) {
        return alertWarning('간선도로 ID를 입력해주세요', null, _modalIdText);
    }
    else if (!val.trim()) {
        return alertWarning('간선도로 ID를 입력해주세요', null, _modalIdText);
    }
    else if (getByteLength(val) > 10) {
        return alertWarning('10바이트 이내로 입력해주세요', null, _modalIdText);
    }
    else if (_idArr.includes(val)) {
        return alertWarning('이미 사용중인 간선도로 ID 입니다.', null, _modalIdText);
    }
    let result = [];
    getData('/api/database/atrd/usage/' + val, result);

    if(result > 0){
        return alertWarning('이미 사용중인 간선도로 ID 입니다.', null, _modalIdText);
    }

    eventOn();
    modalCancle();

    _atrdEditTable.option('dataSource', []);
    textBoxInit();

    if (_selObjMap.size > 0) {
        _selObjMap.forEach((obj) => {
            _mapManager.updateEditLink(_lyrIdx, obj.road_id, 0, false);
        })
    }
    _selObjMap.clear();

    setValue(_atrdIdText, val.trim());
    _atrdNmText.focus();
}

//모달 취소 이벤트
function modalCancle(){
    $(".modal-background").css("display",'none');
    setValue(_modalIdText, null);
}

/**
 * 기타 이벤트
 */

//텍스트 상자 비우기
function textBoxInit(){
    setValue(_atrdIdText, null);
    setValue(_atrdNmText, null);
    setValue(_atrdDircSelect, '0');
}