roadData            = [];
roadMakeUpData      = [];
let modalContent    = null;
let searchBtn       = null;
let modalCancleBtn  = null;
const _apiUri       = '/api/database/road';
let roadTable       = null;
let _selectedRoad   = null;
$(()=>{
    //모달창 바디에 넣기
    $("body").append(modalDiv);
    $(".modal-title").prepend($("<div>도로정보 수정</div>"));
    $(".modal-background").css("display",'none');
    
    $(".edit-btn").dxButton({
        text:'수정',
        icon:'edit',
        stylingMode:'outlined',
        onClick(){
            if(roadTable.getSelectedRowsData().length > 0){
                $(".modal-background").css("display",'flex');
                let selectVal = roadTable.getSelectedRowsData()[0];
                modalContent.updateData('도로_ID',selectVal.road_id);
                modalContent.updateData('도로명',selectVal.road_nm);
                modalContent.updateData('시점명',selectVal.strt_nm);
                modalContent.updateData('종점명',selectVal.end_nm);
            }
        }
    })

    $(".search-button").dxButton({
        text:'조회',
        icon:'refresh',
        stylingMode:'outlined',
        height:'30px',
        width: '80px',
        onClick(){
            fetchListData();
        }
    })
    
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    })
    
    $(".modal-cancle").dxButton({
        icon:'close',
        stylingMode:'text',
        onClick(){
            $(".modal-background").css("display",'none');
        }
    })
    
    $(".modal-save-Btn").dxButton({
        stylingMode:'outlined',
        text:'저장',
        icon:'save',
        onClick(){
            const road_id = modalContent.option().formData.도로_ID;
            const road_nm = modalContent.option().formData.도로명;
            const strt_nm = modalContent.option().formData.시점명;
            const end_nm  = modalContent.option().formData.종점명;
            const frontContent = '도로 ID : ' + road_id + '<br>';
            const validationArr = [
                [road_nm, '도로명', 'road_nm', 50],
                [strt_nm, '시점명', 'strt_nm', 100],
                [end_nm,  '종점명', 'end_nm', 100],
            ]
            const selectedData = roadTable.getSelectedRowsData()[0];
            let sameCnt = 0;
            for (let validation of validationArr) {
                const empty = nullChecker(validation[0]) === "";
                if (empty) {
                    return alertWarning(frontContent + validation[1] +"을 입력해주세요.", null, modalContent.getEditor(validation[1]));
                }
                else if (getByteLength(validation[0]) > validation[3]) {
                    return alertWarning(frontContent + validation[1] +"을 " + validation[3] + "바이트 이내로 입력해주세요.", null, modalContent.getEditor(validation[1]));
                }
                if (selectedData[validation[2]] === validation[0]) {
                    sameCnt++;
                }
            }
            if (sameCnt === 3) {
                return alertWarning(frontContent + "변경 된 사항이 없습니다.", null);
            }
            confirmMessage( frontContent + "도로 정보를 수정하시겠습니까?").done((yes) => {
                if (yes === true) {
                    const updateData = {
                        road_nm: road_nm,
                        strt_nm: strt_nm,
                        end_nm: end_nm
                    }
                    let result = putUpdate( _apiUri + '/name/' + road_id, updateData);
                    if ( result > 0){
                        fetchListData();
                        $(".modal-background").css("display","none");
                        alertConfirm(frontContent + "<br>도로 정보를 수정하였습니다.");
                    }
                }
            });

        },
    })
    
    $(".modal-cancle-Btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        icon:'close',
        onClick(){
            $(".modal-background").css("display",'none');
        },
    })
    
    modalContent = $('.modal-content')
        .dxForm({
            formData: null,
            minColWidth: 200,
            labelLocation: 'left',
            items: [
                {
                    caption: '도로정보',
                    itemType: 'group',
                    colCount: 2,
                    items: [
                        {
                            dataField: '도로_ID',
                            disabled: true,
                            editorOptions: {
                                width: '160px',
                                stylingMode: 'outlined',
                            },
                        },
                        {
                            dataField: '도로명',
                            editorOptions: {
                                width: '160px',
                                stylingMode: 'outlined',
                            },
                        },
                    ],
                },
                {
                    itemType: 'group',
                    colCount: 2,
                    items: [
                        {
                            dataField: '시점명',
                            editorOptions: {
                                width: '160px',
                                stylingMode: 'outlined',
                            },
                        },
                        {
                            dataField: '종점명',
                            editorOptions: {
                                width: '160px',
                                stylingMode: 'outlined',
                            },
                        },
                    ],
                },
            ],
        })
        .dxForm('instance');

    roadTable = $(".road-table").width('100%').height('100%').dxDataGrid({
            dataSource : null,
            allowColumnReordering   : true,
            showColumnLines         : true,
            allowColumnResizing     : true,
            showBorders             : true,
            rowAlternationEnabled   : true,
            columnAutoWidth         : true,
            noDataText              : '표출할 정보가 없습니다.',
            focusedRowEnabled       : true,
            keyExpr                 : 'road_id',
            selection: {
            mode: 'single',
            },
           filterRow: {
                visible: true,
                applyFilter: "auto",
                showOperationChooser:false,
            },
            headerFilter: {
                visible: true,
            },
            grouping: {
                autoExpandAll: true,
            },
            paging: {
                pageSize : 1000,
            },
            groupPanel:{
                visible: true,
                emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
            },
            export:{
                enabled: true,
                texts: {
                    exportAll:"엑셀 파일",
                },
            },
            onExporting(e){
                gridExcellExporting(e, '도로 정보');
            },
            columns:[
                {
                    dataField:"road_id",
                    caption:"ID",
                    dataType : 'string',
                    alignment:"center",
                    width:'100px',
                    sortIndex: 0, 
                    sortOrder: "asc"
                },
                {
                    dataField:"road_nm",
                    caption:"도로명",
                    alignment:"center",
                    cellTemplate(c,e){
                        alignTemplate(c, e, 'left');
                    }
                },
                {
                    dataField:"drct_desc",
                    caption:"방향",
                    alignment:"center",
                    cellTemplate(c,e){
                        let result = nullChecker(e.displayValue);
                        return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                    }
                },
                {
                    dataField:"strt_nm",
                    caption:"시점명",
                    alignment:"center",
                    cellTemplate(c,e){
                        let result = nullChecker(e.displayValue);
                        return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                    }
                },
                {
                    dataField:"end_nm",
                    caption:"종점명",
                    alignment:"center",
                    cellTemplate(c,e){
                        let result = nullChecker(e.displayValue);
                        return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                    }
                },
                {
                    dataField:"sect_lngt",
                    caption:"구간 길이",
                    alignment:"center",
                },
                {   
                    dataField:"f_node_id",
                    caption:"시작 노드 ID",
                    alignment:"center",
                },
                {
                    dataField:"t_node_id",
                    caption:"종료 노드 ID",
                    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>')
                    }
                },
                {
                    dataField:"area_cd",
                    caption:"지역 코드",
                    alignment:"center",
                },
                {
                    dataField:"del_yn",
                    caption:"삭제 여부",
                    alignment:"center",
                },
                
            ],
            onRowClick(e){
                roadMakeUpData = [];
                if (_selectedRoad === null || _selectedRoad !== e.data.road_id) {
                    _selectedRoad = e.data.road_id;
                    getData("/api/database/road/rltn/" + e.data.road_id, roadMakeUpData)
                    roadMakeupTable.option("dataSource",roadMakeUpData[0]);
                    roadMakeupTable.clearSelection();
                    roadMakeupTable.option('focusedRowIndex', -1);
                }
            },
            onRowDblClick(e){
                $(".modal-background").css("display",'flex');
                modalContent.updateData('도로_ID',e.data.road_id);
                modalContent.updateData('도로명',e.data.road_nm);
                modalContent.updateData('시점명',e.data.strt_nm);
                modalContent.updateData('종점명',e.data.end_nm);
            }
    }).dxDataGrid("instance");

    const roadMakeupTable = $(".road-makeup-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'ord',
        selection : {
            mode : 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter : {
            visible : true,
        },
        grouping : {
            autoExpandAll : true,
        },
        groupPanel : {
            visible : true,
            emptyPanelText : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        export : {
            enabled : true,
            texts : {
                exportAll : "엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, '정보제공구간 링크 정보');
        },
        columns:[
            {
                dataField:"ord",
                caption:"순서",
                alignment:"center",
                sortIndex: 0, 
                sortOrder: "asc"
            },
            {
                dataField:"ifsc_id",
                dataType : 'string',
                caption:"ID",
                alignment:"center",
            },
            {
                dataField:"ifsc_nm",
                caption:"명칭",
                alignment:"center",
                cellTemplate(c,e){
                    c.css('text-align','left');
                    c.text(e.displayValue)
                }
            },
            {
                dataField:"drct_desc",
                caption:"방향",
                alignment:"center",
            },
            {
                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:"sect_lngt",
                caption:"길이",
                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>')
                }
            }
        ],
        
    }).dxDataGrid("instance");

    fetchListData();
})

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