//우측 섹션 관련
let trafficData      = [];
let trafficTable     = null;
let trafficChart     = null;

//탭
let linkTabs         = null;
let searchTabs       = null;

//구간별 사용 박스
let termSelect       = null;
let termStartDate    = null;
let termStartTIme    = null;
let termEndDate      = null;
let termEndTIme      = null;
let termSearchBtn    = null;

//시간별 사용 박스
let hourSearchBtn    = null;
let hourSelect       = null;
let hourStartDate    = null;
let hourStartTime    = null;
let hourEndDate      = null;
let hourEndTime      = null;

//지정 시각별 사용 박스
let specSelect       = null;
let specStartTime    = null;
let specEndTime      = null;
let specDayTable     = null;
let specSearchBtn    = null;
let selectTableData  = [];

//링크 테이블 관련
let linkData         = [];
let ifscData         = [];
let roadData         = [];
let linkTable        = null;
let ifscTable        = null;
let roadTable        = null;
let sectSearchBtn    = null;

//구간 검색 관련
let atrdSelect       = null;
let atrdData         = [];
let atrdFmmData      = [];

//시간 세팅
let endDate          = new Date();
let startDate        = new Date().setDate(new Date().getDate()-1);

//공통 uri
let commouUri        = '/api/statistics/atrd-traffic';

//차트 관련
let series           = [];
let xAxis            = [];
let filename         = ' 기간검색_';

//지정 시각 테이블 날짜 세팅
const year = new Date().getFullYear();
const month = timeFormmater(new Date().getMonth()+1);

const _pageName = '간선도로 소통정보 통계';

let dateCnt = 5;
for( let ii = 1; ii <= 5; ii++ ){
    selectTableData.push({
        id   : ii,
        date : getBefAftDay(-dateCnt--),
    })
}



//구간별 탭
const termTabs = $("<div class='search-box'>").html(`
<div class="first-tab-top">
    <div class="label">통계 구분</div>
    <div>
        <div class="stat-select">
            <div class="select-box"></div>
        </div>
    </div>
</div>
<div>
    <div class="label">검색시작시각</div>
    <div>
        <div class="strt-date-box">
            <div class="strt-date"></div>
        </div>
    </div>
    <div>
        <div class="strt-time-box">
            <div class="strt-time"></div>
        </div>
    </div>
</div>
<div>
    <div class="label">검색종료시각</div>
    <div>
        <div class="end-date"></div>
    </div>
    <div>
        <div class="end-time"></div>
    </div>
</div>
<div class="search-btn-box">
    <div class="worning-text">검색기간이 클 경우 검색 결과가 늦어질수 있습니다.</div>
    <div class="search-btn"></div>
</div>
`
);

//시간별 탭
const hourTabs = $('<div class="search-box">').html(
    `<div class="second-tab-top">
    <div class="label">통계 구분</div>
    <div>
        <div>
            <div class="statistics-select"></div>
        </div>
    </div>
</div>
<div>
    <div class="label">검색시작일</div>
    <div>
        <div>
            <div class="strt-date"></div>
        </div>
    </div>
</div>
<div>
    <div class="label">검색종료일</div>
    <div>
        <div class="end-date"></div>
    </div>
</div>
<div id="time-bound">
    <div class="label">시간대</div>
    <div>
        <div class="strt-time"></div>
    </div>
    <div> ~ </div>
    <div>
        <div class="end-time"></div>
    </div>
</div>
<div class="search-btn-box">
    <div class="worning-text">검색 조건에 따라 검색 결과가 늦어질수 있습니다.</div>
    <div class="search-button"></div>
</div>
`
)

//지정 시각 탭
const specTabs = $('<div class="search-box">').html(
    `<div class="third-tab-top">
        <div class="label">통계 구분</div>
        <div>
            <div>
                <div class="statistics-select"></div>
            </div>
        </div>
    </div>
    <div id="third-right-box">
        <div class="label">지정일선택</div>
        <div>
            <div class="select-date-table"></div>
        </div>
    </div>
    <div id="time-bound">
        <div id="no-margine" class="label">시간대</div>
        <div>
            <div class="strt-time"></div>
        </div>
        <div> ~ </div>
        <div>
            <div class="end-time"></div>
        </div>
    </div>
    <div class="search-btn-box">
        <div class="worning-text">검색 조건에 따라 검색 결과가 늦어질수 있습니다.</div>
        <div class="search-button"></div>
    </div>`
)

//chart series
series = [
    {
        id   : 'sped',
        name : '속도(km/h)',
        color: 'rgb(124, 181, 236)',
        data : [],
    },
    {
        id   : 'trvl_hh',
        name : '통행시간(초)',
        color: 'rgb(247, 163, 92)',
        data : [],
    },
]

$(()=>{
    $('.page-box > div').hover(function(){
        $(this).addClass('dx-menu-item dx-state-hover');
    },function(){
        $(this).removeClass('dx-menu-item dx-state-hover');
    })
    //기간 셀렉트박스
    termSelect = $(termTabs).children().eq(0).children().eq(1).children().eq(0).children().eq(0).dxSelectBox({
        items       : ['15분 통계','시간 통계(1시간)','일 통계(1일)','월 통계(1개월)','년 통계(1년)'],
        width       : 250,
        height      : 28,
        stylingMode : "outlined",
        value       : '15분 통계',
        onItemClick(e){
            sectSearchBtn.off('click');
            termSearchBtn.off('click');
            switch (e.itemData) {
                case '15분 통계':
                    termStartDate.option( 'width', 170 );
                    termStartDate.option( 'displayFormat', 'yyyy년 MM월 dd일' );
                    termEndDate.option( 'width', 170);
                    termEndDate.option( 'displayFormat', 'yyyy년 MM월 dd일' );
                    termStartTIme.option( 'visible', true);
                    termEndTIme.option( 'visible', true);
                    sectSearchBtn.on( 'click', () => termEvent( '15m', e.itemData, 'sect' ) );
                    termSearchBtn.on( 'click', () => termEvent( '15m', e.itemData, 'atrd' ) );
                    break;
                case '시간 통계(1시간)':
                    termStartDate.option( 'width', 170 );
                    termStartDate.option( 'displayFormat', 'yyyy년 MM월 dd일' );
                    termEndDate.option( 'width', 170 );
                    termEndDate.option( 'displayFormat', 'yyyy년 MM월 dd일' );
                    termStartTIme.option( 'visible', true );
                    termEndTIme.option( 'visible', true );
                    sectSearchBtn.on( 'click', () => termEvent( 'hh', e.itemData, 'sect' ) );
                    termSearchBtn.on( 'click', () => termEvent( 'hh', e.itemData, 'atrd' ) );
                    break;
                case '일 통계(1일)':
                    termStartDate.option( 'width', 250 );
                    termStartDate.option( 'displayFormat', 'yyyy년 MM월 dd일' )
                    termEndDate.option( 'width', 250 );
                    termEndDate.option( 'displayFormat', 'yyyy년 MM월 dd일' )
                    termStartTIme.option( 'visible', false );
                    termEndTIme.option( 'visible', false );
                    sectSearchBtn.on( 'click', () => termEvent( 'dd', e.itemData, 'sect' ) );
                    termSearchBtn.on( 'click', () => termEvent( 'dd', e.itemData, 'atrd' ) );
                    break;
                case '월 통계(1개월)':
                    termStartDate.option( 'width', 250 );
                    termStartDate.option( 'displayFormat', 'yyyy년 MM월' );
                    termEndDate.option( 'width', 250 );
                    termEndDate.option( 'displayFormat', 'yyyy년 MM월');
                    termStartTIme.option( 'visible', false );
                    termEndTIme.option( 'visible', false );
                    sectSearchBtn.on( 'click', () => termEvent( 'mn', e.itemData, 'sect' ) );
                    termSearchBtn.on( 'click', () => termEvent( 'mn', e.itemData, 'atrd' ) );
                    break;

                case '년 통계(1년)':
                    termStartDate.option( 'width', 250 );
                    termStartDate.option( 'displayFormat', 'yyyy년' );
                    termEndDate.option( 'width', 250 );
                    termEndDate.option( 'displayFormat', 'yyyy년' );
                    termStartTIme.option( 'visible', false );
                    termEndTIme.option( 'visible', false );
                    sectSearchBtn.on( 'click', () => termEvent( 'yy', e.itemData, 'sect' ) );
                    termSearchBtn.on( 'click', () => termEvent( 'yy', e.itemData, 'atrd' ) );
                    break;

                default:
                    break;
            }
        }
    }).dxSelectBox('instance');

    //기간 검색시작일시 년월일
    termStartDate =  $(termTabs).children().eq(1).children().eq(1).children().eq(0).children().eq(0).dxDateBox({
        type                : 'date',
        value               : startDate,
        width               : '170px',
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy년 MM월 dd일',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000년 00월 00일',
    }).dxDateBox('instance');

    //기간 검색시작일시 시간
    termStartTIme =  $(termTabs).children().eq(1).children().eq(2).children().eq(0).children().eq(0).dxDateBox({
        type                : 'time',
        value               : new Date().getTime(),
        width               : '75px',
        height              : '28px',
        interval            : 60,
        stylingMode         :'outlined',
        displayFormat       : 'HH 시',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00 시',
    }).dxDateBox('instance');

    //기간 검색종료일시 년월일
    termEndDate =  $(termTabs).children().eq(2).children().eq(1).children().eq(0).dxDateBox({
        type                : 'date',
        value               : endDate,
        width               : '170px',
        height              : '28px',
        stylingMode         :'outlined',
        displayFormat       : 'yyyy년 MM월 dd일',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000년 00월 00일',
    }).dxDateBox('instance');

    //기간 검색종료일시 시간
    termEndTIme =  $(termTabs).children().eq(2).children().eq(2).children().eq(0).dxDateBox({
        type                : 'time',
        value               : new Date().getTime(),
        width               : '75px',
        height              : '28px',
        interval            : 60,
        stylingMode         :'outlined',
        displayFormat       : 'HH 시',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00 시',
    }).dxDateBox('instance');

    //기간 조회 버튼
    termSearchBtn = $(termTabs).children().eq(3).children().eq(1).dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
    }).dxButton("instance").on('click', () => termEvent( '15m', termSelect.option('value'), 'atrd' ));

    //시간대 셀렉트박스
    hourSelect = $(hourTabs).children().eq(0).children().eq(1).children().eq(0).children().eq(0).dxSelectBox({
        items       : ['15분 통계','시간 통계(1시간)'],
        width       : 250,
        height      : 30,
        stylingMode : "outlined",
        value       : '15분 통계',
        onItemClick(e){
            sectSearchBtn.off('click');
            hourSearchBtn.off('click');
            switch (e.itemData) {
                case '15분 통계':
                    sectSearchBtn.on( 'click', () => hourEvent( '15m' ), 'sect' );
                    hourSearchBtn.on( 'click', () => hourEvent( '15m' ), 'atrd' );
                    break;
                case '시간 통계(1시간)':
                    sectSearchBtn.on( 'click', () => hourEvent( 'hh' ), 'sect' );
                    hourSearchBtn.on( 'click', () => hourEvent( 'hh' ), 'atrd' );
                    break;
                default:
                    break;
            }
        }
    }).dxSelectBox('instance');

    //시간대 검색시작일시 년월일
    hourStartDate = $(hourTabs).children().eq(1).children().eq(1).children().eq(0).children().eq(0).dxDateBox({
        type                : 'date',
        value               : startDate,
        width               : '250px',
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy년 MM월 dd일',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000년 00월 00일',
    }).dxDateBox('instance');

    //시간대 검색종료일시 년월일
    hourEndDate = $(hourTabs).children().eq(2).children().eq(1).children().eq(0).dxDateBox({
        type                : 'date',
        value               : endDate,
        width               : '250px',
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy년 MM월 dd일',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000년 00월 00일',
    }).dxDateBox('instance');

    //시간대 검색시작일시 시간
    hourStartTime = $(hourTabs).children().eq(3).children().eq(1).children().eq(0).dxDateBox({
        type                : 'time',
        value               : new Date().getTime(),
        width               : '103px',
        height              : '28px',
        interval            : 60,
        stylingMode         :'outlined',
        displayFormat       : 'HH 시',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00 시',
    }).dxDateBox('instance');

    //시간대 검색종료일시 시간
    hourEndTime = $(hourTabs).children().eq(3).children().eq(3).children().eq(0).dxDateBox({
        type                : 'time',
        value               : new Date().getTime(),
        width               : '103px',
        height              : '28px',
        interval            : 60,
        stylingMode         : 'outlined',
        displayFormat       : 'HH 시',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00 시',
    }).dxDateBox('instance')

    //시간대 조회 버튼
    hourSearchBtn = $(hourTabs).children().eq(4).children().eq(1).dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
    }).dxButton("instance").on('click', () => hourEvent( '15m', 'atrd' ));

    //지정 시각 검색 셀렉트 박스
    specSelect    =  $(specTabs).children().eq(0).children().eq(1).children().eq(0).dxSelectBox({
        items       : ['15분 통계','시간 통계(1시간)'],
        width       : 250,
        height      : 30,
        stylingMode : "outlined",
        value       : '15분 통계',
        onItemClick(e){
            sectSearchBtn.off('click');
            specSearchBtn.off('click');
            switch (e.itemData) {
                case '15분 통계':
                    sectSearchBtn.on( 'click', () => specEvent( '15m', 'sect' ));
                    specSearchBtn.on( 'click', () => specEvent( '15m', 'atrd' ));
                    break;
                case '시간 통계(1시간)':
                    sectSearchBtn.on( 'click', () => specEvent( 'hh', 'sect' ));
                    specSearchBtn.on( 'click', () => specEvent( 'hh', 'atrd' ));
                    break;

                default:
                    break;
            }
        }
    }).dxSelectBox('instance');

    //지정 시각 검색 시작일시 시간
    specStartTime = $(specTabs).children().eq(2).children().eq(1).children().eq(0).dxDateBox({
        type                : 'time',
        value               : new Date().getTime(),
        width               : '100px',
        height              : '28px',
        interval            : 60,
        stylingMode         : 'outlined',
        displayFormat       : 'HH 시',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00 시',
    }).dxDateBox('instance');

    //지정 시각 검색 종료일시 시간
    specEndTime   = $(specTabs).children().eq(2).children().eq(3).children().eq(0).dxDateBox({
        type                : 'time',
        value               : new Date().getTime(),
        width               : '100px',
        height              : '28px',
        interval            : 60,
        stylingMode         :'outlined',
        displayFormat       : 'HH 시',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00 시',
    }).dxDateBox('instance');

    //지정 시각 검색 일검색 테이블
    specDayTable  = $(specTabs).children().eq(1).children().eq(1).children().eq(0).width('250px').dxDataGrid({
        dataSource      : selectTableData,
        noDataText      : '표출할 정보가 없습니다.',
        showColumnLines : true,
        showBorders     : true,
        keyExpr         : 'id',
        selection       : {
            allowSelectAll      : false,
            mode                : 'multiple',
            showCheckBoxesMode  : "onClick"
        },
        columns         : [
            {
                dataField : 'date',
                alignment : 'center',
                dataType  : 'date',
                format    : 'yyyy-MM-dd',
                cssClass  : 'no-padding',
                caption   : '일자',
            }
        ]
    }).dxDataGrid('instance');

    //지정 시각 검색 조회 버튼
    specSearchBtn = $(specTabs).children().eq(3).children().eq(1).dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
    }).dxButton("instance").on( 'click', () => specEvent( '15m', 'atrd'));

    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance")

    //소통정보통계 테이블
    trafficTable = $(".traffic-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        focusedRowEnabled       : true,
        selection: {
            mode: 'single',
        },
        keyExpr : ['id', 'stat_dt'],
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible: true,
        },
        grouping: {
            autoExpandAll: true,
        },
        scrolling: {
            mode: 'standard',
        },
        paging   : {
            pageSize : 1000,
        },
        sorting : {
            showSortIndexes : false,
        },
        groupPanel:{
            visible: true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        export:{
            enabled: true,
            texts: {
                exportAll:"엑셀 파일",
            },
        },
        columns : [
            {
                caption   : "기본 정보",
                alignment : "center",
                columns:[
                    {
                        dataField    : "ord",
                        caption      : "순서",
                        alignment    : "center",
                        visible      : false
                    },
                    {
                        dataField    : "id",
                        caption      : "ID",
                        alignment    : "center",
                        sortIndex    : 0,
                        sortOrder    : "asc",
                    },
                    {
                        dataField    : "t_name",
                        caption      : "명칭",
                        alignment    : "center",
                        cellTemplate(c,e){
                            c.css('text-align','left');
                            c.text(e.displayValue)
                        }
                    },
                    {
                        dataField    : "sect_lngt",
                        caption      : "길이",
                        alignment    : "center",
                        format       : "#,###,##0",
                    },
                    {
                        dataField    : "stat_dt",
                        caption      : "통계시각",
                        alignment    : "center",
                        sortIndex    : 1,
                        sortOrder    : "asc",
                    },

                ]

            },
            {
                caption   : "통계 정보",
                alignment : "center",
                columns:[
                    {
                        dataField    : "sped",
                        caption      : "속도",
                        alignment    : "center",
                    },
                    {
                        dataField    : "trvl_hh",
                        caption      : "통행시간",
                        alignment    : "center",
                        format       : "#,###,##0",
                    },

                ]

            },

        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },

    }).dxDataGrid("instance");


    //링크 테이블
    linkTable = $("<div>").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : 'id',
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible: true,
        },
        grouping: {
            autoExpandAll: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        groupPanel:{
            visible: true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        columns:[
            {
                dataField    : "id",
                caption      : "링크 ID",
                alignment    : "center",
                allowEditing : false,
                cssClass     : 'link-padding',
                sortIndex    : 0,
                sortOrder    : "asc",
                dataType     : 'string',
            },

            {
                dataField    : "strt_nm",
                caption      : "시작노드",
                cssClass     : 'link-padding',
                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      : "종료노드",
                cssClass     : 'link-padding',
                alignment    : "center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            // {
            //     dataField:"link_leng",
            //     caption:"길이(m)",
            //     alignment:"center",
            // },
            // {
            //     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:"road_no",
            //     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_use_desc",
            //     caption:"도로사용여부",
            //     alignment:"center",
            // },
            // {
            //     dataField:"lanes",
            //     caption:"차로수",
            //     alignment:"center",
            // },
            // {
            //     dataField:"max_spd",
            //     caption:"최고제한속도",
            //     alignment:"center",
            // },

            // {
            //     dataField:"sect_grad_cd_desc",
            //     caption:"구간등급코드",
            //     alignment:"center",
            //     cellTemplate(c,e){
            //         let result = nullChecker(e.data.sect_grad_cd_desc);
            //         return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
            //     }
            // }
        ],
        onContentReady(e){
            e.component.clearSelection();
            e.component.option('focusedRowIndex', -1);
        },
    })

    //서비스링크 테이블
    ifscTable = $("<div>").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        focusedRowEnabled       : true,
        keyExpr                 : 'id',
        selection: {
            mode: 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible: true,
        },
        grouping: {
            autoExpandAll: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        groupPanel:{
            visible: true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        columns:[
            {
                dataField    : "id",
                caption      : "ID",
                alignment    : "center",
                cssClass     : 'link-padding',
                dataType     : 'string',
                allowEditing : false,
                sortIndex: 0,
                sortOrder: "asc",
            },

            {
                dataField    : "strt_nm",
                caption      : "시작노드",
                cssClass     : 'link-padding',
                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      : "종료노드",
                cssClass     : 'link-padding',
                alignment    : "center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },

            // {
            //     dataField:"ifsc_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:"drct_cd_desc",
            //     caption:"방향",
            //     alignment:"center",
            // },
            // {
            //     dataField:"link_leng",
            //     caption:"길이(m)",
            //     alignment:"center",
            // },
            // {
            //     dataField:"sect_grad_cd_desc",
            //     caption:"구간등급코드",
            //     alignment:"center",
            //     cellTemplate(c,e){
            //         let result = nullChecker(e.data.sect_grad_cd_desc);
            //         return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
            //     }
            // }
            // {
            //     dataField:"rmrk",
            //     caption:"비고",
            //     alignment:"center",
            // },
            // {
            //     dataField:"extr_cnct_sect_yn",
            //     caption:"외부연계",
            //     alignment:"center",
            // },
        ],
        onContentReady(e){
            e.component.clearSelection();
            e.component.option('focusedRowIndex', -1);
        },
    })

    //로드 테이블
    roadTable = $("<div>").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : 'id',
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible: true,
        },
        grouping: {
            autoExpandAll: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        groupPanel:{
            visible: true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        columns:[
            {
                dataField    : "id",
                caption      : "ID",
                alignment    : "center",
                cssClass     : 'link-padding',
                dataType     : 'string',
                allowEditing : false,
                sortIndex    : 0,
                sortOrder    : "asc",
            },

            {
                dataField    : "strt_nm",
                caption      : "시작노드",
                cssClass     : 'link-padding',
                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     : "종료노드",
                cssClass    : 'link-padding',
                alignment   : "center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            // {
            //     dataField:"link_leng",
            //     caption:"길이(m)",
            //     alignment:"center",
            // },
            // {
            //     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:"drct_cd_desc",
            //     caption:"방향",
            //     alignment:"center",
            // },
        ],
        onContentReady(e){
            e.component.clearSelection();
            e.component.option('focusedRowIndex', -1);
        },
    })

    //간선도로 셀렉트
    atrdSelect = $(".atrd-select").dxSelectBox({
        items       : null,
        width       : 240,
        height      : 30,
        displayExpr : 'display',
        valueExpr   : 'atrd_id',
        stylingMode : "outlined",
        onItemClick(e){
            if (e.itemData){
                if(e.itemData.atrd_id) {
                    fetchTrafficWithAtrdId(e.itemData.atrd_id);
                }
            }
        },
    }).dxSelectBox('instance');

    sectSearchBtn = $(".sect-search-btn").dxButton({
        text        : '선택구간조회',
        stylingMode : 'outlined',
    }).dxButton('instance').on( 'click', () => termEvent( '15m', '15분 통계', 'sect' ));

    //링크 tabs
    linkTabs = $('.link-table').width('100%').height('100%').dxTabPanel({
        dataSource:[
            {
                id     : 1,
                name   : '링크(레벨1)',
                table  : linkTable,
                column : 'linkColumns',
            },
            {
                id     : 2,
                name   : '정보제공구간(레벨2)',
                table  : ifscTable,
                column : 'ifscColumns',
            },
            {
                id     : 3,
                name   : '도로(레벨3)',
                table  : roadTable,
                column : 'roadColumns',
            },
        ],
        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>');
            div.css({width:'100%', height:'100%'});
            return  div.append(e.table);
        },
        onSelectionChanged(e){
            e.addedItems[0].table.dxDataGrid('instance').clearSelection();
            e.addedItems[0].table.dxDataGrid('instance').option('focusedRowIndex', -1);
        },
    }).dxTabPanel('instance');

    //조회 tabs
    searchTabs = $('.search-tabs').width('100%').height('100% - 80px').dxTabPanel({
        dataSource:[
            {
                id     : 1,
                name   : '기간검색',
                box    : termTabs,
                css    : ['213px','calc(100% - 358px)'],
            },
            {
                id     : 2,
                name   : '시간대 검색',
                box    : hourTabs,
                css    : ['241px','calc(100% - 386px)'],
            },
            {
                id     : 3,
                name   : '지정 시각 검색',
                box    : specTabs,
                css    : ['314px','calc(100% - 459px)'],
            },
        ],
        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){
            return e.box;
        },
        onSelectionChanged(e){
            filename = ' ' + e.addedItems[0].name + '_';
            $('.tab-box').css('height',e.addedItems[0].css[0]);
            $('.link-box').css('height', e.addedItems[0].css[1]);
            $('.selected-index').text(e.component.option('selectedIndex') + 1);
            sectSearchBtn.off('click');
            termSearchBtn.off('click');
            switch (e.component.option('selectedIndex')) {
                case 0:
                    termSelect.option('value','15분 통계');
                    termStartDate.option('value', startDate);
                    termStartTIme.option('value', new Date().getTime());
                    termEndDate.option('value', endDate);
                    termEndTIme.option('value', new Date().getTime());
                    termStartDate.option( 'width', 170 );
                    termStartDate.option( 'displayFormat', 'yyyy년 MM월 dd일' );
                    termEndDate.option( 'width', 170);
                    termEndDate.option( 'displayFormat', 'yyyy년 MM월 dd일' );
                    termStartTIme.option( 'visible', true);
                    termEndTIme.option( 'visible', true);
                    sectSearchBtn.on( 'click', () => termEvent( '15m', '15분 통계', 'sect' ) );
                    termSearchBtn.on( 'click', () => termEvent( '15m', '15분 통계', 'atrd' ) );
                    break;
                case 1:
                    hourSearchBtn.off('click');
                    hourSelect.option('value', '15분 통계')
                    hourStartDate.option('value', startDate);
                    hourStartTime.option('value', new Date().getTime());
                    hourEndDate.option('value', endDate);
                    hourEndTime.option('value', new Date().getTime());
                    sectSearchBtn.on( 'click', () => hourEvent( '15m' ), 'sect' );
                    hourSearchBtn.on( 'click', () => hourEvent( '15m' ), 'atrd' );
                    break;
                case 2:
                    specSearchBtn.off( 'click');
                    specSearchBtn.on( 'click', () => specEvent( '15m', 'atrd' ));
                    sectSearchBtn.on( 'click', () => specEvent( '15m', 'sect' ) );
                    specSelect.option('value', '15분 통계');
                    specDayTable.deselectAll();
                    specStartTime.option('value', new Date().getTime());
                    specEndTime.option('value', new Date().getTime());
                    break;
                default:
                    break;
            }
        },
    }).dxTabPanel('instance');

    //차트 이지미 저장 버튼
    $(".export-button").dxButton({
        stylingMode : 'outlined',
        text        : '차트 저장',
        icon        : 'export',
        height      : '40px',
        width       : '110px',
        onClick(){
            if( trafficData.length <= 0 || trafficData[0].length <= 0 ){
                alertWarning("저장하실 차트 데이터가 없습니다.");
                return false;
            };
            confirmMessage("간선도로 소통정보 통계 차트를 파일로 저장 하시겠습니까?").done((yes)=>{
                if (yes){
                    trafficChart.exportChart({
                        filename: '간선도로 소통정보 통계 -' + filename + excellTime()
                    });
                }
            });
        }
    })

    //차트 변경 버튼
    $(".chart-change").dxMenu({
        dataSource: chartDataSource,
        hideSubmenuOnMouseLeave: true,
        cssClass:'dx-button-mode-outlined',
        height: 40,
        showFirstSubmenuMode: {
            name: "onClick",
            delay: { show: 0, hide: 100 },
        },
        displayExpr: "name",
        submenuDirection: "auto",
        visible: true,
        onItemClick(info){
            const item = info.itemData;
            if(item.type){
                const dataSource = [...info.component.option('dataSource')]
                dataSource[0].name = item.name
                dataSource[0].icon = item.type
                info.component.option('dataSource', dataSource);
                trafficChart.update({
                    chart: {
                        type: item.type,
                    }
                })
            }
        }
    }).dxMenu("instance");


    //간선도로 소통정보 차트
    trafficChart = Highcharts.chart('traffic-chart', {
        chart: {
            type: 'line',
            height: 338,
            backgroundColor: {
                classNmae: 'dx-theme-background-color',
            },
            zoomType: 'x',
            events: {
                load: function() {
                }
            },
        },
        title: {
            text: null
        },
        xAxis: {
            categories: null,
            title: {
                text: '통계시각',
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                }
            },
            labels:{
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                }
            }
        },

        yAxis: {
            min: 0,
            title: null,
            labels: {
                overflow: 'justify',
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                },
                format: '{value:,.0f}'
            },
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            },
            series: {
                lineWidth: 2,
                turboThreshold: 0,
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            floating: false,
            y: 50,
            borderWidth: 1,
            itemStyle:{
                color: $('.dx-theme-material-typography').css('color'),
            },
            backgroundColor: {
                className : 'dx-nav-item dx-theme-border-color',
            },
            shadow: true,
        },
        exporting : {
            enabled : false,
        },
        credits : {
            enabled : false
        },
        series : series
    });
    window.$chart = trafficChart;
    fetchComboData();
})

function fetchTrafficWithAtrdId(atrdId){
    const param = encodeURIComponent(atrdId);
    getDataAsync(commouUri + '/atrd/ifsc/' + param, recvTableData, ifscTable );
    getDataAsync(commouUri + '/atrd/link/' + param, recvTableData, linkTable );
    getDataAsync(commouUri + '/atrd/road/' + param, recvTableData, roadTable );
}

function recvTableData(jsonData, table){
    const instance = table.dxDataGrid('instance');
    instance.clearSelection();
    instance.option('focusedRowIndex', -1);
    instance.option('dataSource', jsonData);
}
//지정 시각별 이벤트
function specEvent( uriType, eventType ){
    linkChooger( specSettings, '/spec', uriType, eventType );
}

//구간별 이벤트
function termEvent(uriType, selectVal, eventType){
    linkChooger( termSettings, '/term', uriType, selectVal, eventType);
}

//시간별 이벤트
function hourEvent( uriType, eventType ){
    linkChooger( hourSettings, '/hour', uriType, eventType);
}

//지정 시각별 데이터 세팅
function specSettings( table, idName, uri, eventType){
    let tableData  = table.dxDataGrid('instance').getSelectedRowsData();
    let FROM_HM    = null;
    let TO_HM      = null;
    let updateData = {};
    let statDays   = "";
    let timeFormatLength = 16;

    if( eventType === 'sect' && tableData.length <= 0 ){
        const name = linkTabs.option('selectedItem').name
        alertWarning(name.substring(0,name.indexOf("(")) + " 목록을 선택해주세요")
        return false;
    }

    if( specDayTable.getSelectedRowsData().length <= 0){
        alertWarning( '검색 지정일을 선택하지 않았습니다.' );
        return false;
    }

    if ( !validationCheck( null, null, specStartTime, specEndTime )) return false;
    FROM_HM = timeSetup( specStartTime.option('value') ).substring( 0, 2 );
    TO_HM   = timeSetup( specEndTime.option('value') ).substring( 0, 2 );

    if( FROM_HM > TO_HM ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, specStartTime);
        return false;
    };

    for ( let ii = 0; ii < specDayTable.getSelectedRowsData().length; ii++ ){
        statDays += dateFormmater( new Date(specDayTable.getSelectedRowsData()[ii].date)) + ","
    }
    statDays = statDays.substring(0, statDays.length-1);
    updateData[ 'statDays' ] = statDays;
    updateData[ 'FROM_HM' ]  = FROM_HM;
    updateData[ 'TO_HM' ]    = TO_HM;

    if(eventType === 'sect'){
        updateData[ idName ] = tableData[0].id;
        sectEvent( uri, updateData, timeFormatLength );
    }
    else {
        updateData[ 'ATRD_ID' ] = atrdSelect.option('value')
        atrdEvent( uri + '/atrd', updateData, timeFormatLength );
    }

}

//시간별 데이터 세팅
function hourSettings( table, idName, uri, eventType){
    let tableData        = table.dxDataGrid('instance').getSelectedRowsData();
    let FROM_HM          = null;
    let TO_HM            = null;
    let updateData       = {};
    let timeFormatLength = 16;
    if( eventType === 'sect' && tableData.length <= 0 ){
        const name = linkTabs.option('selectedItem').name
        alertWarning(name.substring(0,name.indexOf("(")) + " 목록을 선택해주세요")
        return false;
    }

    if ( !validationCheck( hourStartDate, hourEndDate, hourStartTime, hourEndTime )) return false;
    FROM_DT = dateFormmater( new Date( hourStartDate.option('value') ));
    TO_DT   = dateFormmater( new Date( hourEndDate.option('value') ));
    FROM_HM = timeSetup( hourStartTime.option('value') ).substring( 0, 2 );
    TO_HM   = timeSetup( hourEndTime.option('value') ).substring( 0, 2 );


    if ( FROM_DT > TO_DT ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, hourStartDate);
        return false;
    };
    if (Number(FROM_DT) + 100 <= Number(TO_DT)) {
        return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, hourEndDate);
    }
    
    if ( FROM_HM > TO_HM ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, hourStartTime);
        return false;
    };

    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;
    updateData[ 'FROM_HM' ] = FROM_HM;
    updateData[ 'TO_HM' ]   = TO_HM;

    if (eventType === 'sect') {
        updateData[ idName ] = tableData[0].id;
        sectEvent( uri, updateData , timeFormatLength);
    }
    else {
        updateData[ 'ATRD_ID' ] = atrdSelect.option('value')
        atrdEvent( uri + '/atrd', updateData , timeFormatLength);
    }

}

//구간별 데이터 세팅
function termSettings( table, idName, uri, condition, eventType ) {
    let tableData  = table.dxDataGrid('instance').getSelectedRowsData();
    let FROM_DT    = null;
    let TO_DT      = null;
    let updateData = {};
    let timeFormatLength = null;
    if( eventType === 'sect' && tableData.length <= 0 ){
        const name = linkTabs.option('selectedItem').name
        alertWarning(name.substring(0,name.indexOf("(")) + " 목록을 선택해주세요")
        return false;
    }

    //조건 체크에 따른 시간 포맷
    switch (condition) {
        case '15분 통계' :
            if ( !validationCheck( termStartDate, termEndDate, termStartTIme, termEndTIme )) return false;
            FROM_DT = getDate(termStartDate.option('value'), termStartTIme.option('value')).substring(0, 10);
            TO_DT   = getDate(termEndDate.option('value'), termEndTIme.option('value')).substring(0, 10);
            if (Number(FROM_DT) + 10000 <= Number(TO_DT)) {
                return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, termEndDate);
            }
            timeFormatLength = 16;
            break;
        case '시간 통계(1시간)' :
            if ( !validationCheck( termStartDate, termEndDate, termStartTIme, termEndTIme )) return false;
            FROM_DT = getDate(termStartDate.option('value'), termStartTIme.option('value')).substring(0, 10);
            TO_DT   = getDate(termEndDate.option('value'), termEndTIme.option('value')).substring(0, 10);
            if (Number(FROM_DT) + 10000 <= Number(TO_DT)) {
                return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, termEndDate);
            }
            timeFormatLength = 16;
            break;
        case '일 통계(1일)' :
            if ( !validationCheck( termStartDate, termEndDate )) return false;
            FROM_DT = dateFormmater(new Date(termStartDate.option('value')));
            TO_DT   = dateFormmater(new Date(termEndDate.option('value')));
            if (Number(FROM_DT) + 100 <= Number(TO_DT)) {
                return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, termEndDate);
            }
            timeFormatLength = 10;
            break;
        case '월 통계(1개월)' :
            if ( !validationCheck( termStartDate, termEndDate )) return false;
            FROM_DT = dateFormmater(new Date(termStartDate.option('value'))).substring(0, 6);
            TO_DT   = dateFormmater(new Date(termEndDate.option('value'))).substring(0, 6);
            timeFormatLength = 7;
            break;
        case '년 통계(1년)' :
            if ( !validationCheck( termStartDate, termEndDate )) return false;
            FROM_DT = dateFormmater(new Date(termStartDate.option('value'))).substring(0, 4);
            TO_DT   = dateFormmater(new Date(termEndDate.option('value'))).substring(0, 4);
            timeFormatLength = 4;
            break;
        default:
            break;
    };


    if( FROM_DT > TO_DT ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, termStartDate);
        return false;
    };

    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;

    if (eventType === 'sect') {
        updateData[ idName ] = tableData[0].id;
        sectEvent( uri, updateData, timeFormatLength );
    }
    else {
        updateData[ 'ATRD_ID' ] = atrdSelect.option('value')
        atrdEvent( uri + '/atrd', updateData, timeFormatLength );
    }
}

//테이블 및 차트 세팅
function sectEvent( uri, updateData, timeFormatLength ){
    trafficData = [];
    xAxis       = [];
    getDataAsync(uri, (jsonData)=>{
        trafficData = jsonData;

        series[0].data = [];
        series[1].data = [];

        if (trafficData) {
            dataSorting(trafficData, 'stat_dt');
            trafficData.map((item)=>{
                if(item.stat_dt){
                    item.stat_dt = getParseDateTime(item.stat_dt).substring(0, timeFormatLength);
                }
                xAxis.push(item.stat_dt)
                series[0].data.push(item[series[0].id])
                series[1].data.push(item[series[1].id])
            })
        }
        trafficTable.option( 'dataSource', trafficData );

        trafficChart.update({
            xAxis :{
                categories: xAxis
            },
            series:series
        })

        //showColumn( trafficTable, 'ord' );
        trafficTable.columnOption('ord','sortIndex','0');
        trafficTable.columnOption('id','sortIndex', null);
        trafficTable.columnOption('ord','sortOrder','asc');
        trafficTable.columnOption('id','sortOrder', null);
        $('.chart-box').css('display','block');
        $('.right-box > div:nth-child(2)').css('height','calc(100% - 434.7px)');
        pageNation(trafficChart, xAxis);
        trafficTable.refresh();
        trafficTable.clearSelection();
        trafficTable.option('focusedRowIndex', -1);
        alertConfirm('데이터 조회가 완료 되었습니다. [' + trafficData.length + '건]')
    }, null, updateData);
}

//테이블 및 차트 세팅
function atrdEvent( uri, updateData, timeFormatLength ){
    trafficData = [];
    //getData( uri, trafficData, updateData );
    getDataAsync(uri, (jsonData)=>{
        trafficData = jsonData;

        if (trafficData) {
            if (trafficData.length > 0) {
                dataSorting(trafficData, 'stat_dt');
                trafficData.map((item)=>{
                    if (item.stat_dt) {
                        item.stat_dt = getParseDateTime(item.stat_dt).substring(0, timeFormatLength);
                    }
                })
            }

            trafficTable.option( 'dataSource', trafficData );

            trafficTable.columnOption('ord','sortIndex', null);
            trafficTable.columnOption('ord','sortOrder',null);
            trafficTable.columnOption('id','sortIndex','0');
            trafficTable.columnOption('id','sortOrder', 'asc');
            hideColumn( trafficTable, 'ord' );
            $('.chart-box').css('display','none');
            $('.right-box > div:nth-child(2)').css('height','calc(100% - 34.7px)');
            trafficTable.refresh();
            trafficTable.clearSelection();
            trafficTable.option('focusedRowIndex', -1);
            alertConfirm('데이터 조회가 완료 되었습니다. [' + trafficData.length + '건]')
        }
    }, null, updateData);
}

//각 이벤트 별 링크 필터링
function linkChooger( event, uri ,uriType, selectVal, eventType ){
    switch (linkTabs.option('selectedIndex')) {
        case 0:
            event( linkTable, 'LINK_ID', commouUri + uri +'/link-' + uriType, selectVal, eventType );
            break;
        case 1:
            event( ifscTable, 'IFSC_ID', commouUri + uri + '/ifsc-' + uriType, selectVal, eventType )
            break;
        case 2:
            event( roadTable, 'ROAD_ID', commouUri + uri + '/road-' + uriType, selectVal, eventType )
            break;

        default:
            break;
    }
}

function fetchComboData(){
    getDataAsync(commouUri + '/atrd', recvComboFunc);
}

function recvComboFunc(jsonData){
    atrdData = jsonData;
    if (atrdData.length > 0) {
        atrdData.map(( item ) => {
            atrdFmmData.push( {
                atrd_id      : item.atrd_id,
                display      : item.atrd_nm + " [" + item.drct_desc + "]"
            })
        });
        atrdSelect.option('items', atrdFmmData);
        if(atrdFmmData.length > 0){
            setValue(atrdSelect, atrdFmmData[0].atrd_id);
            fetchTrafficWithAtrdId(atrdFmmData[0].atrd_id);
        }
    }
}
