//우측 섹션 관련
let reptCngsData   = [];
let reptCngsTable      = null;

//좌측 섹션 관련
let reptCngsDate  = null;
let reptCngsSearchBtn  = null;
let reptCngsSelect     = null;
let dayTypeData    = [];


//공통 uri
let commonUri            = '/api/analysis/rept-cngs/';
const _pageName          = '반복정체구간 분석';
let OFFR_TYPE            = 'LINK';


//기본 날짜 세팅
const strtDate = new Date().setMonth(new Date().getMonth()-2);
const endDate = new Date().setMonth(new Date().getMonth()-1);

$(()=>{
    //검색시작일시 년월일
    reptCngsDate =  $('.strt-date').dxDateBox({
        type                : 'date',
        value               : strtDate,
        width               : 210,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy년 MM월',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000년 00월',
    }).dxDateBox('instance');
    
    //링크레벨구분
    reptCngsSelect = $('.rept-cngs-select').dxSelectBox({
        stylingMode     : 'outlined',
        dataSoruce      : null,
        displayExpr     : 'day_type_desc',
        valueExpr       : 'day_type_cd',
        value           : null,
        width           : 210,
        height          : 28,
        onItemClick(e){
            
        }
    }).dxSelectBox('instance');
    
    //상단 조회 버튼
    reptCngsSearchBtn = $('.rept-cngs-search-btn').dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
        onClick(){
            offrResultEvent();
        }
    }).dxButton("instance")
    
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance")
    
    
     //반복 정체 구간 분석 테이블
     reptCngsTable = $(".rept-cngs-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        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:"엑셀 파일",
            },
        },
        columns:[
                    {
                        dataField    : "day_type_nm",
                        caption      : "요일",
                        alignment    : "center",
                        sortIndex    : 0, 
                        sortOrder    : "asc",
                    },
                    {
                        dataField    : "stat_ym",
                        caption      : "기준월",
                        alignment    : "center",
                    },
                    {
                        dataField    : "ifsc_id",
                        caption      : "구간 ID",
                        alignment    : "center",
                    },
                    {
                        dataField    : "strt_nm",
                        caption      : "시점명",
                        alignment    : "center",
                    },
                    {
                        dataField    : "end_nm",
                        caption      : "종점명",
                        alignment    : "center",
                    },
                    {
                        dataField    : "cnfs_strt_hm",
                        caption      : "시작시각",
                        alignment    : "center",
                    },
                    {
                        dataField    : "cnfs_end_hm",
                        caption      : "종료시각",
                        alignment    : "center",
                    },
                    {
                        dataField    : "avrg_sped",
                        caption      : "평균속도",
                        alignment    : "center",
                    },
                    {
                        dataField    : "avrg_trvl_hh",
                        caption      : "통행시간(초)",
                        alignment    : "center",
                    },
                    {
                        dataField    : "dcsn_yn",
                        caption      : "확정여부",
                        alignment    : "center",
                    },
                    {
                        dataField    : "rept_cngs_sect_orgn_nm",
                        caption      : "판정구분",
                        alignment    : "center",
                    },
        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        
    }).dxDataGrid("instance");
});

function fetchSelectData(){
    getDataAsync(commonUri+'day-type', (jsonData)=>{
        dayTypeData = jsonData
        reptCngsSelect.option('dataSource', dayTypeData);
        setValue(reptCngsSelect, dayTypeData[0].day_type_cd)
    });
}

//조회 데이터 세팅
function offrResultEvent() {

    let DAY_TYPE_CD   = reptCngsSelect.option('value').day_type_cd
    let BASE_MN       = null;
    let updateData    = {};

    //월,시각 null값 체크
    if ( !validationCheck( reptCngsDate )) return false;
    
    BASE_MN = dateFormmater(new Date(reptCngsDate.option('value'))).substring(0,6);

    updateData[ 'DAY_TYPE_CD' ] = DAY_TYPE_CD;
    updateData[ 'BASE_MN' ]     = BASE_MN;
    finalEvent( commonUri, updateData );
}

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

    getData( uri, reptCngsData, updateData );
    
    if ( !(reptCngsData.length <= 0)){
        reptCngsData[0].map((item)=>{
            console.log(item)
            if(nullChecker(item.stat_ym) !== ""){
                item.stat_ym = getParseMonth(item.stat_ym)
            }
            if(nullChecker(item.cnfs_end_hm) !== ""){
                item.cnfs_end_hm = item.cnfs_end_hm.substring(0,2) + ":" + item.cnfs_end_hm.substring(2,4);
            }
            if(nullChecker(item.cnfs_strt_hm) !== ""){
                item.cnfs_strt_hm = item.cnfs_strt_hm.substring(0,2) + ":" + item.cnfs_strt_hm.substring(2,4);
            }
        })
        reptCngsTable.option( 'dataSource', reptCngsData[0] );
    }
    alertConfirm('데이터 조회가 완료 되었습니다. [' + reptCngsData[0].length + '건]')
    
}
