let linkData = [];
let link     = null;
let ifsc     = null;
let road     = null;
let linkTabs = null;
let test     = null;
const commonUri = '/api/manage/traffic/current';

$(() =>{

    link = $("<div>").width('100%').height('100%').dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        focusedRowEnabled       : true,
        columnAutoWidth         : true,
        keyExpr                 : 'link_id',
        noDataText              : '표출할 정보가 없습니다.',
        selection               : {
            mode : 'single',
        },
        filterRow               : {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter            : {
            visible : true,
        },
        groupPanel              :{
            visible         : true,
            emptyPanelText  : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        paging                  : {
            pageSize : 18,
        },
        grouping                : {
            autoExpandAll : true,
        },
        pager                   : {
            visible               : true,
            showNavigationButtons : true,
        },
        searchPanel             : {
            visible : true,
            highlightCaseSensitive:true,
        },
        export                  : {
            enabled : true,
            texts: {
                exportAll : "엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, '링크소통정보');
        },
        columns:[
            {
                dataField    : "link_id",
                caption      : "ID",
                alignment    : "center",
                sortIndex    : 0, 
                sortOrder    : "asc",
                width        : 100,
                dataType     : 'string',
            },
            {
                dataField    : "f_node_nm",
                caption      : "시작 노드",
                alignment    : "center",
                cellTemplate(c,e){
                    let result=nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {
                dataField    : "t_node_nm",
                caption      : "종료 노드",
                alignment    : "center",
                cellTemplate(c,e){
                    let result=nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {
                dataField   : "prcn_dt",
                caption     : "최종가공시각",
                width       : 150,
                alignment   : "center",
                dataType    : 'datetime',
                format      : 'yyyy-MM-dd HH:mm:ss',
            },
            {
                dataField   : "sped",
                caption     : "속도",
                width       : 90,
                alignment   : "center",
            },
            {
                dataField   : "trvl_hh",
                caption     : "통행시간",
                width       : 110,
                alignment   : "center",
            },
            {
                dataField    : "cmtr_grad_desc",
                caption      : "소통등급",
                alignment    : "center",
                cellTemplate(c,e){
                    return gradTemplate(c, e);
                }
            },
            // {
            //     dataField    : "miss_yn",
            //     caption      : "결측여부",
            //     alignment    : "center",
            //     cellTemplate(c,e){
            //         let result='';
            //         if (e.data.miss_yn === 'Y')result=$('<div style="color:red;">결측</div>')
            //         return result;
            //     }
            // },
            {
                dataField   : "prcn_sped",
                caption     : "가공속도",
                width       : 110,
                alignment   : "center",
            },
            {
                dataField   : "smth_sped",
                caption     : "평활화속도",
                width       : 120,
                alignment   : "center",
            },
            {
                dataField   : "adjs_sped",
                caption     : "보정속도",
                width       : 110,
                alignment   : "center",
            },
            {
                dataField   : "ptrn_sped",
                caption     : "패턴속도",
                width       : 110,
                alignment   : "center",
            },
            {
                dataField   : "prcn_sorc_desc",
                caption     : "가공소스",
                alignment   : "center",
            },
            {
                dataField   : "adjs_sorc_desc",
                caption     : "보정소스",
                alignment   : "center",
                cellTemplate(c,e){
                    c.css('text-align','left')
                    return  c.text(e.displayValue)
                }
            },
            {
                dataField   : "data_num",
                caption     : "데이터개수",
                width       : 125,
                alignment   : "center",
            },
        ],
        onEditorPreparing(e) {
            if (e.parentType === "searchPanel") {
                e.editorOptions.stylingMode = "outlined";
            }
        },
    });

    ifsc = $("<div>").width('100%').height('100%').dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : 'ifsc_id',
        noDataText              : '표출할 정보가 없습니다.',
        selection               : {
            mode : 'single',
        },
        filterRow               : {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter            : {
            visible: true,
        },
        groupPanel              :{
            visible         : true,
            emptyPanelText  : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        paging                  : {
            pageSize : 18,
        },
        grouping                : {
            autoExpandAll : true,
        },
        pager                   : {
            visible               : true,
            showNavigationButtons : true,
        },
        searchPanel             : {
            visible : true,
        },
        export                  : {
            enabled : true,
            texts: {
                exportAll : "엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, '정보제공구간 소통정보');
        },
        onEditorPreparing(e) {
            if (e.parentType === "searchPanel") {
                e.editorOptions.stylingMode = "outlined";
            }
        },
        columns:[
            {
                dataField    : "ifsc_id",
                caption      : "ID",
                alignment    : "center",
                dataType     : 'string',
                sortIndex    : 0, 
                sortOrder    : "asc",
                width        : 100,
            },
            {
                dataField    : "ifsc_nm",
                caption      : "구간명",
                alignment    : "center",
                cellTemplate(c,e){
                    return  $('<div style="text-align: left;">'+e.data.ifsc_nm+'</div>')
                }
            },
            {
                dataField    : "drct_cd_desc",
                caption      : "방향",
                alignment    : "center",
            },
            {
                dataField    : "strt_nm",
                caption      : "시점명",
                alignment    : "center",
                cellTemplate(c,e){
                    return  $('<div style="text-align: left;">'+e.data.strt_nm+'</div>')
                }
            },
            {
                dataField    : "end_nm",
                caption      : "종점명",
                alignment    : "center",
                cellTemplate(c,e){
                    return  $('<div style="text-align: left;">'+e.data.end_nm+'</div>')
                }
            },
            {
                dataField    : "prcn_dt",
                caption      : "최종가공시각",
                alignment    : "center",
                dataType     : 'datetime',
                format       : 'yyyy-MM-dd HH:mm:ss',
            },
            {
                dataField    : "sped",
                caption      : "속도",
                alignment    : "center",
            },
            {
                dataField    : "trvl_hh",
                caption      : "통행시간",
                alignment    : "center",
            },
            {
                dataField    : "cmtr_grad_desc",
                caption      : "소통등급",
                alignment    : "center",
                cellTemplate(c,e){
                    return gradTemplate(c, e);
                }
            },
            // {
            //     dataField    : "miss_yn",
            //     caption      : "결측여부",
            //     alignment    : "center",
            //     cellTemplate(c,e){
            //         let result='';
            //         if (e.data.miss_yn === 'Y')result=$('<div style="color:red;">결측</div>')
            //         return result;
            //     }
            // },
            {
                dataField    : "ptrn_sped",
                caption      : "패턴속도",
                alignment    : "center",
            },
            {
                dataField    : "data_num",
                caption      : "데이터개수",
                alignment    : "center",
            },
        ]
    });

    road = $("<div>").width('100%').height('100%').dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : 'road_id',
        noDataText              : '표출할 정보가 없습니다.',
        selection               : {
            mode : 'single',
        },
        filterRow               : {
            visible     : true,
            applyFilter : 'auto',
            showOperationChooser:false,
        },
        headerFilter            : {
            visible : true,
        },
        groupPanel              :{
            visible         : true,
            emptyPanelText  : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        paging                  : {
            pageSize : 18,
        },
        grouping                : {
            autoExpandAll : true,
        },
        pager                   : {
            visible               : true,
            showNavigationButtons : true,
        },
        searchPanel             : {
            visible : true,
        },
        export                  : {
            enabled : true,
            texts: {
                exportAll : "엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, '도로소통정보');
        },
        onEditorPreparing(e) {
            if (e.parentType === "searchPanel") {
                e.editorOptions.stylingMode = "outlined";
            }
        },
        columns:[
            {
                dataField    : "road_id",
                caption      : "ID",
                alignment    : "center",
                sortIndex    : 0, 
                sortOrder    : "asc",
                width        : 100,
                dataType     : 'string',
            },
            {
                dataField    : "road_name",
                caption      : "도로명",
                alignment    : "center",
                cellTemplate(c,e){
                    return  $('<div style="text-align: left;">'+e.data.road_name+'</div>')
                }
            },
            {
                dataField    : "drct_cd_desc",
                caption      : "방향",
                alignment    : "center",
            },
            {
                dataField    : "strt_nm",
                caption      : "시점명",
                alignment    : "center",
                cellTemplate(c,e){
                    return  $('<div style="text-align: left;">'+e.data.strt_nm+'</div>')
                }
            },
            {
                dataField    : "end_nm",
                caption      : "종점명",
                alignment    : "center",
                cellTemplate(c,e){
                    return  $('<div style="text-align: left;">'+e.data.end_nm+'</div>')
                }
            },
            {
                dataField    : "prcn_dt",
                caption      : "최종가공시각",
                alignment    : "center",
                dataType     : 'datetime',
                format       : 'yyyy-MM-dd HH:mm:ss',
            },
            {
                dataField    : "sped",
                caption      : "속도",
                alignment    : "center",
            },
            {
                dataField    : "trvl_hh",
                caption      : "통행시간",
                alignment    : "center",
            },
            {
                dataField    : "cmtr_grad_desc",
                caption      : "소통등급",
                alignment    : "center",
                cellTemplate(c,e){
                    return gradTemplate(c, e);
                }
            },
            // {
            //     dataField    : "miss_yn",
            //     caption      : "결측여부",
            //     alignment    : "center",
            //     cellTemplate(c,e){
            //         let result='';
            //         if (e.data.miss_yn === 'Y')result=$('<div style="color:red;">결측</div>')
            //         return result;
            //     }
            // },
            {
                dataField    : "ptrn_sped",
                caption      : "패턴속도",
                alignment    : "center",
            },
            {
                dataField    : "data_num",
                caption      : "데이터개수",
                alignment    : "center",

            },
        ]
    });

    const searchBtn = new dxBtn($(".search-button"), '조회', 'refresh', 'outlined', 80, 30);
    searchBtn.onClick(fetchBaseData);

    const cancleBtn = new dxBtn($(".cancle-button"), '닫기', 'close', 'outlined', 80, 30);
    cancleBtn.onClick(()=>window.close());

    linkTabs = $('#current-traffic-table').width('100%').height('100%').dxTabPanel({
        dataSource:[
            {
                id    : 'link',
                name  : '링크(레벨1)',
                table : link,
            },
            {
                id : 'ifsc',
                name : '정보제공구간(레벨2)',
                table : ifsc,
            },
            {
                id : 'road',
                name : '도로(레벨3)',
                table : road,
            },
        ],
        selectIndex:0,
        loop:false,
        animationEnabled: true,
        swipeEnabled: false,
        itemTitleTemplate: function(e){
        return $('<div style="height:29px; line-height:29px;">'+e.name+'</div>')
        },
        itemTemplate: function(e){
            const div = $(`<div class="padding-box"></div>`);
            div.append(e.table);
        return div;
        },
        onSelectionChanged(e){
            const selectedTab = e.addedItems[0] 
            let table = selectedTab.table.dxDataGrid('instance');
            table.clearSelection();
            table.option('focusedRowIndex', -1);
        },
    }).dxTabPanel('instance');
    fetchBaseData();

});

function fetchBaseData(){
    getDataAsync(commonUri + '/link', recvListData, link);
    getDataAsync(commonUri + '/ifsc', recvListData, ifsc);
    getDataAsync(commonUri + '/road', recvListData, road);
}

function recvListData(jsonData, table){
    const listData = jsonData;
    if (listData) {
        listData.map((obj)=>{
            if (obj.prcn_dt) obj.prcn_dt = new Date(getParseDateTime(obj.prcn_dt));
        })
    }
    table.dxDataGrid('instance').option('dataSource', listData);
}

function gradTemplate(c, e){
    c.css('padding','2px');
    c.css('height','1px');
    const div = $('<div class="cmtr-text">');
    div.text(e.displayValue);
    if(!e.data.cmtr_grad_cd || e.data.cmtr_grad_cd === 'LTC0'){
        div.text('[LTC0] 정보없음')
    }
    c.append(div)
    cmtrColor.map((item)=>{
        if(item.name === e.data.cmtr_grad_cd) div.css('background-color', item.color)
    })
    return c;
}