let clctHsData       = [];
let clctSystStupData = [];
let clctHsTable      = null;
let clctHsChart      = null;
let searchBtn        = null;
let userCnnsHsUri    = '/api/history/user-cnns-hs';
let strtDateBox      = null;
let strtTimeBox      = null;
let endDateBox       = null;
let endTimeBox       = null;
let endDate          = new Date().setDate(new Date().getDate()-1);
let startDate        = new Date().setDate(new Date().getDate()-1);
let linkTable        = null;
let dataSource       = [];
let columns          = [];
let series           = [];
let xAxis            = [];
let data             = [];
const _pageName      = '수집데이터 이력';
const _linkData      = _trafficMap.get('link');
$(()=>{
    $('.page-box > div').hover(function(){
        $(this).addClass('dx-menu-item dx-state-hover');
    },function(){
        $(this).removeClass('dx-menu-item dx-state-hover');
    })
    //검색시작일시 년월일
    strtDateBox = $(".strt-date").dxDateBox({
        type                : 'date',
        value               : startDate,
        width               : '120px',
        height              : '25px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy-MM-dd',
        readonly            : true,
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox("instance");

    //검색시작일시 시간
    strtTimeBox = $(".strt-time").dxDateBox({
        type                : 'time',
        value               : 1645110000000,
        width               : '90px',
        height              : '25px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox("instance");

    //검색종료일시 년월일
    endDateBox  = $(".end-date").dxDateBox({
        type                : 'date',
        value               : endDate,
        width               : '120px',
        height              : '25px',
        stylingMode         :'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox("instance");

    //검색종료일시 시간
    endTimeBox  = $(".end-time").dxDateBox({
        type                : 'time',
        value               : 1645196399000,
        width               : '90px',
        height              : '25px',
        stylingMode         :'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox("instance");

    //차트 이미지 파일 저장 버튼
    $(".export-button").dxButton({
        stylingMode : 'outlined',
        text        : '차트 저장',
        icon        : 'export',
        height      : '40px',
        width       : '110px',
        onClick(){
            if ( data <= 0 ){
                alertWarning("저장하실 차트 데이터가 없습니다.");
                return false;
            }
            confirmMessage("수집데이터 이력 조회 차트를 파일로 저장 하시겠습니까?").done((yes)=>{
                if (yes) {
                    clctHsChart.exportChart({
                        filename: '수집데이터 이력조회_'+ excellTime()
                    });
                }
            })
        }
    })

    //상단 조회 버튼
    searchBtn = $(".search-button").dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
        onClick(){
            const selectedData = linkTable.getSelectedRowsData();
            if(selectedData.length <= 0){
                alertWarning("링크 목록을 선택해주세요")
                return false;
            }

            if(!validationCheck( strtDateBox, endDateBox, strtTimeBox, endTimeBox)) return false;

            let FROM_DT  = getDate(strtDateBox.option("value"), strtTimeBox.option("value"));
            let TO_DT    = getDate(endDateBox.option("value"), endTimeBox.option("value"));

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

            if (Number(FROM_DT) + 100000000 <= Number(TO_DT)) {
                return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, endDateBox);
            }
            let updateData = {
                FROM_DT : FROM_DT,
                LINK_ID : selectedData[0].link_id,
                TO_DT   : TO_DT,
            }


            clctHsData = [];
            getDataAsync('/api/history/clct-hs', (jsonData)=>{
                clctHsData = jsonData;

                //dataSource = [];
                data       = [];
                xAxis      = [];
                if (clctHsData) {
                    dataSorting(clctHsData, 'prcn_dt');
                    clctHsData.map((item) => {
                        if(item.prcn_dt){
                            item.prcn_dt = getParseDateTime(item.prcn_dt);
                        }
                        xAxis.push(item.prcn_dt)
    
                        data.push(
                            {
                                OPER01  : item.OPER01,
                                UTIS01  : item.UTIS01,
                                UTIS02  : item.UTIS02,
                                VDS01   : item.VDS01 ,
                                MOCT01  : item.MOCT01,
                            }
                        )
                    })
                }
                clctHsTable.option('dataSource', clctHsData);
                clctHsTable.clearSelection();
                clctHsTable.option('focusedRowIndex', -1);
                series.map((item)=>{
                    item.data = [];
                    for( let ii = 0; ii < data.length; ii++){
                        if(item.id === 'OPER01') item.data.push(data[ii].OPER01);
                        if(item.id === 'UTIS01') item.data.push(data[ii].UTIS01);
                        if(item.id === 'UTIS02') item.data.push(data[ii].UTIS02);
                        if(item.id === 'VDS01') item.data.push(data[ii].VDS01);
                        if(item.id === 'MOCT01') item.data.push(data[ii].MOCT01);
                    }
                })
                clctHsChart.update({
                    xAxis : {
                        categories : xAxis,
                    },
                    series : series
                })
                pageNation(clctHsChart, xAxis);

                alertConfirm('데이터 조회가 완료 되었습니다. [' + clctHsData.length + '건]')
            }, null, updateData);
        }
    }).dxButton("instance");

    //차트 변경 버튼
    $(".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);
                clctHsChart.update({
                    chart: {
                        type: item.type,
                    }
                })
            }
        }
    }).dxMenu("instance");

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

    //링크 테이블
    linkTable = $(".link-table").width('100%').height('calc(100%  - 1px)').dxDataGrid({
        dataSource              : _linkData,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : 'link_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    : "link_id",
                caption      : "링크 ID",
                alignment    : "center",
                allowEditing : false,
                sortIndex    : 0,
                width        : 120,
                dataType     : 'string',
                cssClass     : 'table-padding',
                sortOrder    : "asc",
            },

            {
                dataField    : "from_node",
                caption      : "시작노드",
                alignment    : "center",
                cssClass     : 'table-padding',
                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",
                cssClass     : 'table-padding',
                cellTemplate(c,e){
                    let result = nullChecker(e.data.to_node);
                    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);
        },
    }).dxDataGrid("instance");

    fetchBaseData();
})

function fetchBaseData(){
    getDataAsync("/api/history/clct-hs/clct-syst-stup", recvColumnData);
}

function recvColumnData(jsonData) {
    clctSystStupData = jsonData;
    columns.push(
        {
            dataField    : "link_id",
            caption      : "링크 ID",
            alignment    : "center",
            dataType     : 'string',
            allowEditing : false,
        },
        {
            dataField    : "prcn_dt",
            caption      : "가공일시",
            alignment    : "center",
            sortIndex    : 0,
            sortOrder    : "asc",
        }
    )

    if (clctSystStupData.length > 0){
        for ( let ii = 0; ii < clctSystStupData.length; ii++ ){
            columns.push({
                dataField    : clctSystStupData[ii].clct_syst_cd,
                caption      : clctSystStupData[ii].clct_syst_nm,
                alignment    : "center",
                format       : '#,###,##0',
            })

            series.push({
                id   : clctSystStupData[ii].clct_syst_cd,
                name : clctSystStupData[ii].clct_syst_nm,
                data : [],
                color : 'rgb(' +colorList[ii] + ')',
            })
        }
    }
    drawChart();
    makeTable();
}

function makeTable(){
    //수집데이터 이력조회 테이블
    clctHsTable = $(".clct-hs-table").width('100%').height('100%').dxDataGrid({
        dataSource              : clctHsData,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : ['link_id', 'prcn_dt'],
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible: true,
        },
        grouping: {
            autoExpandAll: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        groupPanel:{
            visible: true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        export:{
            enabled: true,
            texts: {
                exportAll:"엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        columns : columns
    }).dxDataGrid("instance");
}

function drawChart() {
    //차트 그리기
    clctHsChart = Highcharts.chart('clct-hs-chart', {
        chart: {
            type: 'line',
            height: 342,
            backgroundColor: {
                className: 'dx-theme-background-color',
            },
            zoomType: 'x',
            events: {
                load: function() {
                    this.xAxis[0].setExtremes(0, 15);
                }
            },
        },
        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: {
                text: '속도(km/h)',
                align: 'high',
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                }
            },
            labels: {
                overflow: 'justify',
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                },
                format: '{value:,.0f}'
            },
        },
        tooltip: {
            valueSuffix: ' km/h'
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            }
            ,
            series: {
                lineWidth: 2,
                turboThreshold: 0,
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            floating: false,
            y: 50,
            borderWidth: 1,
            shadow: true,
            itemStyle:{
                color: $('.dx-theme-material-typography').css('color'),
            },
            backgroundColor: {
              className : 'dx-nav-item dx-theme-border-color',
            },  
        },
        exporting: {
            enabled: false,
        },
        credits: {
            enabled: false
        },
        series: series
    });
    window.$chart = clctHsChart;
}