//우측 섹션 관련
let offerResultData       = [];
let offerResultTable      = null;
let offerResultChart      = null;

//좌측 섹션 관련
let prcnResultStartDate  = null;
let prcnResultEndDate    = null;
let prcnResultStartTime  = null;
let prcnResultEndTime    = null;
let prcnResultSearchBtn  = null;
let prcnResultLinkSelect = null;

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

//공통 uri
let commonUri            = '/api/analysis/offr-result/';
const _pageName          = '교통정보제공결과 분석';
let OFFR_TYPE            = 'LINK';


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

//chart series
series = [
        {
            id   : 'ltc1_cnt',
            name : '원할',
            color: '#2aeb2a',
            data : [],
        },
        {
            id   : 'ltc2_cnt',
            name : '지체',
            color: '#e7be1b',
            data : [],
        },
        {
            id   : 'ltc3_cnt',
            name : '정체',
            color: 'red',
            data : [],
        },
        {
            id   : 'ltc0_cnt',
            name : '정보없음',
            color: 'gray',
            data : [],
        },
]

$(()=>{
    
    //검색시작일시 년월일
    prcnResultStartDate =  $('.strt-date').dxDateBox({
        type                : 'date',
        value               : strtDate,
        width               : 130,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox('instance');
    
    //검색 시작일시 시간
    prcnResultStartTime =  $('.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');
    
    //검색종료일시 년월일
    prcnResultEndDate =  $('.end-date').dxDateBox({
        type                : 'date',
        value               : endDate,
        width               : 130,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox('instance');
    
    //검색종료일시 시간
    prcnResultEndTime =  $('.end-time').dxDateBox({
        type                : 'time',
        value               : 1645196399000,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    
    //링크레벨구분
    prcnResultLinkSelect = $('.link-levl-select').dxSelectBox({
        stylingMode     : 'outlined',
        items           : ['링크 ( 1레벨 )','정보제공구간 ( 2레벨 )','도로 ( 3레벨 )','VMS'],
        value           : '링크 ( 1레벨 )',
        width           : 215,
        height          : 28,
        onItemClick(e){
            switch (e.itemData) {
                case '링크 ( 1레벨 )':
                    OFFR_TYPE = 'LINK';
                    break;
                case '정보제공구간 ( 2레벨 )':
                    OFFR_TYPE = 'IFSC';
                    break;
                case '도로 ( 3레벨 )':
                    OFFR_TYPE = 'ROAD';
                    break;
                case 'VMS':
                    OFFR_TYPE = 'VMS';
                    break;
                default:
                    break;
            }
        }
    }).dxSelectBox('instance');

    //상단 조회 버튼
    prcnResultSearchBtn = $('.offr-result-search-btn').dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
        onClick(){
            offrResultEvent();
        }
    }).dxButton("instance")
   
    //차트 이지미 저장 버튼
    $(".export-button").dxButton({
        stylingMode : 'outlined',
        text        : '차트 저장',
        icon        : 'export',
        height      : '40px',
        width       : '110px',
        onClick(){
            if( offerResultData.length <= 0 || offerResultData[0].length <= 0 ){
                alertWarning("저장하실 차트 데이터가 없습니다.");
                return false;
            }
            confirmMessage(_pageName + " 차트를 파일로 저장 하시겠습니까?").done((yes)=>{
                if (yes){
                    offerResultChart.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);
                offerResultChart.update({
                    chart: {
                        type: item.type,
                    }
                })
            }
        }
    }).dxMenu("instance");
    
    //교통정보 제공결과분석 통계 차트
    offerResultChart = Highcharts.chart('offr-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 = offerResultChart;
    
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance")
    
    
     //교통정보 제공결과분석 통계 테이블
     offerResultTable = $(".offr-result-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 :'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    : "tot_cnt",
                        caption      : "총링크수",
                        format       : "#,###,##0",
                        alignment    : "center",
                    },
                    {
                        dataField    : "offr_cnt",
                        caption      : "생성수",
                        format       : "#,###,##0",
                        alignment    : "center",
                    },
                    {
                        dataField    : "ltc1_cnt",
                        caption      : "원활",
                        format       : "#,###,##0",
                        alignment    : "center",
                    },
                    {
                        dataField    : "ltc2_cnt",
                        caption      : "지체",
                        format       : "#,###,##0",
                        alignment    : "center",
                    },
                    {
                        dataField    : "ltc3_cnt",
                        caption      : "정체",
                        format       : "#,###,##0",
                        alignment    : "center",
                    },
                    {
                        dataField    : "ltc0_cnt",
                        caption      : "정보없음",
                        format       : "#,###,##0",
                        alignment    : "center",
                    },
        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        
    }).dxDataGrid("instance");
  
})


//구간별 데이터 세팅
function offrResultEvent() {
    let TO_DT      = null;
    let FROM_DT    = null;
    let updateData = {};
    
    if ( !validationCheck( prcnResultStartDate, prcnResultEndDate, prcnResultStartTime, prcnResultEndTime )) return false;
    FROM_DT = getDate( prcnResultStartDate.option('value'), prcnResultStartTime.option('value') );
    TO_DT = getDate( prcnResultEndDate.option('value'), prcnResultEndTime.option('value') );
    
    if( FROM_DT > TO_DT ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, prcnResultStartDate);
        return false;
    };
    
    updateData[ 'FROM_DT' ]    = FROM_DT;
    updateData[ 'TO_DT' ]      = TO_DT;
    updateData[ 'OFFR_TYPE' ] = OFFR_TYPE ;
    finalEvent( commonUri, updateData );
    console.log(updateData)
}

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

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

        if( offerResultData ){
            dataSorting(offerResultData, 'prcn_dt');
            offerResultData.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])
                    }
                }
            })
        }
        
        offerResultTable.option( 'dataSource', offerResultData );

        offerResultTable.clearSelection();

        offerResultTable.option('focusedRowIndex', -1);

        offerResultChart.update({
            xAxis :{
                categories: xAxis
            },
            series:series
        })
        
        pageNation(offerResultChart, xAxis);

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