let linkData = [];
const _apiUri =  '/api/database/link';
let modalContent = null;
let searchBtn = null;
let modalCancleBtn = null;
let linkTable = null;
let cancleBtn = null;
const _pageName = '링크 정보'

$(()=>{
    $("body").append(modalDiv);
    $(".modal-title").prepend($("<div>링크정보 수정</div>"));
    $(".modal-background").css("display","none");

    modalContent=$(".modal-content").dxForm({
        formData:null,
        minColWidth:200,
        labelLocation:'left',
        items:[{
            caption:'링크 정보',
            itemType: 'group',
            items:[{
                dataField: '링크_ID',
                disabled: true,
                editorOptions: {
                    stylingMode: 'outlined',
                    width:'300px',
            }
            },{
            dataField: '도로명칭',         
            editorOptions: {
                width:'300px',
                stylingMode: 'outlined',
            },
        },] 
    }]
    }).dxForm("instance");
    
    $(".modal-save-Btn").dxButton({
        stylingMode:'outlined',
        text:'저장',
        icon:'save',
        onClick(){
            const link_id      = modalContent.option().formData.링크_ID;
            const road_name    = modalContent.option().formData.도로명칭;
            const frontContent = "링크 ID : " + link_id + "<br>";
            const input        = modalContent.getEditor('도로명칭');
            if (nullChecker(road_name) === "") {
                return alertWarning(frontContent + '도로 명칭을 입력해주세요', null, input)
            }
            else if (road_name === linkTable.getSelectedRowsData()[0].road_name) {
                return alertWarning(frontContent + "<br>" + '변경 된 사항이 없습니다.', null, input);
            }
            else if (getByteLength(road_name) > 50) {
                return alertWarning(frontContent + '도로 명칭을 50 바이트 이내로 입력해주세요.', null, input)
            }
            confirmMessage(frontContent + _pageName + "를 수정하시겠습니까?").done((yes) => {
                if (yes === true) {
                    let result = putUpdate( _apiUri + '/name/' + link_id, {road_name:road_name});
                    if ( result > 0){
                        linkData=[];
                        getData(_apiUri ,linkData);
                        linkTable.option('dataSource',linkData[0]);
                        $(".modal-background").css("display","none");
                        return alertConfirm(frontContent + "<br>" + _pageName + "를 수정하였습니다.");
                    }
                }
            });

        },
    })
    
    $(".modal-cancle-Btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        icon:'close',
        onClick(){
            $(".modal-background").css("display",'none');
        },
    })

    modalCancleBtn=$(".modal-cancle").dxButton({
        stylingMode:'text',
        icon:'close',
        onClick(){
            $(".modal-background").css("display",'none');
        }
    });

    $(".edit-btn").dxButton({
        text:'수정',
        icon:'edit',
        stylingMode:'outlined',
        onClick(){
            if(linkTable.getSelectedRowsData().length > 0){
                let selectVal = linkTable.getSelectedRowsData()[0];
                $(".modal-background").css("display",'flex');
                modalContent.updateData('링크_ID',selectVal.link_id);
                modalContent.updateData('도로명칭',selectVal.road_name);
            }
        }
    });

    cancleBtn = $(".cancle-button").dxButton({
        stylingMode:'outlined',
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        onClick(){
            window.close();
        }
    });
   
    searchBtn = $(".select-button").dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        height:'30px',
        width: '80px',
        onClick(){
            fetchListData();
        }
    });

    linkTable = $(".link-table").width('100%').height('100%').dxDataGrid({
        dataSource : null,
        allowColumnReordering: true,
        showColumnLines: true,
        allowColumnResizing: true,
        showBorders: true,
        rowAlternationEnabled:true,
        columnAutoWidth:true,
        focusedRowEnabled:true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr:'link_id',
        selection: {
            mode: 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible: true,
        },
        paging: {
            pageSize: 1000,
        },
        grouping: {
            autoExpandAll: true,
        },
        groupPanel:{
            visible: true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        export:{
            enabled: true,
            texts: {
                exportAll:"엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        columns:[
            {
                dataField:"link_id",
                caption:"ID",
                alignment:"center",
                dataType : 'string',
                width:'100px',
                sortIndex: 0, 
                sortOrder: "asc"
            },
            {
                dataField:"road_name",
                caption:"도로명",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.data.road_name);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            {
                dataField:"from_node",
                caption:"시작노드",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.data.from_node);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            {
                dataField:"to_node",
                caption:"종료노드",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.data.to_node);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            {   
                dataField:"road_use_desc",
                caption:"도로사용여부",
                alignment:"center",
            },
            {
                dataField:"lanes",
                caption:"차로수",
                alignment:"center",
            },
            {
                dataField:"road_rank_desc",
                caption:"도로등급",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.data.road_rank_desc);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            {
                dataField:"road_type_desc",
                caption:"도로유형",
                alignment:"center",
            },
            {
                dataField:"road_no",
                caption:"도로번호",
                alignment:"center",
            },
            
            {
                dataField:"max_spd",
                caption:"최고제한속도",
                alignment:"center",
            },
            {
                dataField:"link_leng",
                caption:"길이(m)",
                alignment:"center",
            },
            {
                dataField:"sect_grad_desc",
                caption:"구간등급코드",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            }
        ],
        onRowDblClick(e){
            $(".modal-background").css("display",'flex');
            modalContent.updateData('링크_ID',e.data.link_id);
            modalContent.updateData('도로명칭',e.data.road_name);
        }
    }).dxDataGrid("instance");
  
    fetchListData();
})

function fetchListData(){
    getDataAsync(_apiUri, (jsonData) => {
        linkTable.option('dataSource', jsonData);
    })
}