//우측 섹션 관련
let clctResultData      = [];
let clctResultTable     = null;
let clctResultChart     = null;

//좌측 섹션 관련
let clctResultStartDate = null;
let clctResultEndDate   = null;
let clctResultStartTime = null;
let clctResultEndTime   = null;
let clctResultSearchBtn = null;

//차트 관련
let series           = [];
let xAxis            = [];
let yAxisTitle       = '개수';
let xAxisTitle       = '수집시각';

//공통 uri
let commonUri        = '/api/analysis/clct-result/';
const _pageName      = '교통정보수집결과 분석'


//기본 날짜 세팅
const strtDate = new Date().setDate(new Date().getDate()-1);
const endDate = new Date().setDate(new Date().getDate()-1);

//chart series
series = [
        {
            id   : 'MOCT01',
            name : '민간정보',
            color: 'rgb(124, 181, 236)',
            data : [],
        },
        {
            id   : 'OPER01',
            name : '운영자개입',
            color: 'rgb(144, 237, 125)',
            data : [],
        },
        {
            id   : 'DSRC01',
            name : 'DSRC-RSE',
            color: 'rgb(43, 144, 143)',
            data : [],
        },
        {
            id   : 'GITS01',
            name : '경기도센터',
            color: 'rgb(128, 133, 233)',
            data : [],
        },
        {
            id   : 'VDS01',
            name : '영상 VDS',
            color: 'rgb(247, 163, 92)',
            data : [],
        },
]

$(()=>{
    
    //검색시작일시 년월일
    clctResultStartDate =  $('.strt-date').dxDateBox({
        type                : 'date',
        value               : strtDate,
        width               : 130,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox('instance');
    
    //검색 시작일시 시간
    clctResultStartTime =  $('.strt-time').dxDateBox({
        type                : 'time',
        value               : 1645110000000,
        tabIndex            : 0,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    
    //검색종료일시 년월일
    clctResultEndDate =  $('.end-date').dxDateBox({
        type                : 'date',
        value               : endDate,
        width               : 130,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox('instance');
    
    //검색종료일시 시간
    clctResultEndTime =  $('.end-time').dxDateBox({
        type                : 'time',
        value               : 1645196399000,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    
    
    //상단 조회 버튼
    clctResultSearchBtn = $('.clct-result-search-btn').dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
        onClick(){
            clctResultEvent();
        }
    }).dxButton("instance")
   
    //차트 이지미 저장 버튼
    $(".export-button").dxButton({
        stylingMode : 'outlined',
        text        : '차트 저장',
        icon        : 'export',
        height      : '40px',
        width       : '110px',
        onClick(){
            if( clctResultData.length <= 0 || clctResultData[0].length <= 0 ){
                alertWarning("저장하실 차트 데이터가 없습니다.");
                return false;
            }

            confirmMessage(_pageName + " 차트를 파일로 저장 하시겠습니까?").done((yes)=>{
                if (yes){
                    clctResultChart.exportChart({
                        filename: _pageName + '_' + excellTime()
                    });
                }
            });
        }
    })

    $('.page-box > div').hover(function(){
        $(this).addClass('dx-menu-item dx-state-hover');
    },function(){
        $(this).removeClass('dx-menu-item dx-state-hover');
    })
    //차트 변경 버튼
    $(".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);
                clctResultChart.update({
                    chart: {
                        type: item.type,
                    }
                })
            }
        }
    }).dxMenu("instance");
 
    //교통정보수집결과분석 통계 차트
    clctResultChart = Highcharts.chart('clct-result-chart', {
        chart: {
            type: 'line',
            height: 342,
            backgroundColor: {
                classNmae: 'dx-theme-background-color',
            },
            zoomType: 'x',
            events: {
                load: function() {
                }
            },
        },
        title: {
            text: null
        },
        xAxis: {
            categories: null,
            title: {
                text: xAxisTitle,
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                }
            },
            labels:{
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                }
            }
        },
        
        yAxis: {
            min: 0,
            title: {
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                },
                text: yAxisTitle,
            },
            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 = clctResultChart;
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance")
    
    
     //교통정보수집결과분석 통계 테이블
     clctResultTable = $(".clct-result-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        keyExpr :'prcn_dt',
        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:"엑셀 파일",
            },
        },
        columns:[
                    {
                        dataField    : "prcn_dt",
                        caption      : "가공일시",
                        alignment    : "center",
                        sortIndex    : 0, 
                        sortOrder    : "asc",
                    },
                    {
                        dataField    : "clct_tot",
                        caption      : "총수집개수",
                        format       : '#,###,##0',
                        alignment    : "center",
                       
                    },
                    {
                        dataField    : "MOCT01",
                        caption      : "민간정보",
                        format       : '#,###,##0',
                        alignment    : "center",
                    },
                    {
                        dataField    : "OPER01",
                        caption      : "운영자개입",
                        format       : '#,###,##0',
                        alignment    : "center",
                    },
                    {
                        dataField    : "DSRC01",
                        caption      : "DSRC-RSE",
                        format       : '#,###,##0',
                        alignment    : "center",
                    },
                    {
                        dataField    : "GITS01",
                        caption      : "경기도센터",
                        format       : '#,###,##0',
                        alignment    : "center",
                    },
                    {
                        dataField    : "VDS01",
                        caption      : "영상 VDS",
                        format       : '#,###,##0',
                        alignment    : "center",
                    },
        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        
    }).dxDataGrid("instance");
  
})


//구간별 데이터 세팅
function clctResultEvent() {
    let TO_DT      = null;
    let FROM_DT    = null;
    let updateData = {};
    
    if ( !validationCheck( clctResultStartDate, clctResultEndDate, clctResultStartTime, clctResultEndTime )) return false;
    FROM_DT = getDate( clctResultStartDate.option('value'), clctResultStartTime.option('value') );
    TO_DT = getDate( clctResultEndDate.option('value'), clctResultEndTime.option('value') );
    
    if( FROM_DT > TO_DT ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, clctResultStartDate);
        return false;
    };
    
    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;
    finalEvent( commonUri, updateData );
}

//테이블 및 차트 세팅
function finalEvent( uri, updateData ){
    clctResultData = [];
    xAxis      = [];

    //getData( uri, clctResultData, updateData );
    getDataAsync(uri, (jsonData)=>{
        clctResultData = jsonData;
    
        for(let key in series){
            series[key].data = [];
        }

        if ( clctResultData ){
            dataSorting(clctResultData, 'prcn_dt');

            clctResultData.map((item)=>{
                if(nullChecker(item.prcn_dt) !== ""){
                    item.prcn_dt = getParseDateTime(item.prcn_dt)
                    xAxis.push(item.prcn_dt)
                    for(let ii = 0 ; ii < series.length; ii++ ){
                        series[ii].data.push(item[series[ii].id])
                    }
                }
            })
        }
        
        clctResultTable.option( 'dataSource', clctResultData );
        clctResultTable.clearSelection();
        clctResultTable.option('focusedRowIndex', -1);

        clctResultChart.update({
            xAxis :{
                categories: xAxis
            },
            series:series
        })
        
        pageNation(clctResultChart, xAxis);
        
        alertConfirm('데이터 조회가 완료 되었습니다. [' + clctResultData.length + '건]')
    }, null, updateData);
}
