//우측 섹션 관련
let dtctData           = [];
let dtctTable          = null;

//좌측 섹션 관련
let dtctListTable      = null;
let dtctListData       = [];
let dtctStartDate      = null;
let dtctEndDate        = null;
let dtctStartTime      = null;
let dtctEndTime        = null;
let dtctSearchBtn      = null;

//공통
let commonUri        = '/api/vds/history/dtct-clct-hs';
const _pageName      = 'VDS-검지기 원시수집 이력';
const pageMsg        = 'VDS-검지기'

$(()=>{
    
    //검색시작일시 년월일
    dtctStartDate =  $('.strt-date').dxDateBox({
        type                : 'date',
        value               : new Date().setDate(new Date().getDate()-1),
        width               : 130,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox('instance');

    //검색 시작일시 시간
    dtctStartTime =  $('.strt-time').dxDateBox({
        type                : 'time',
        value               : firstSettingTime,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    
    //검색종료일시 년월일
    dtctEndDate =  $('.end-date').dxDateBox({
        type                : 'date',
        value               : new Date().setDate(new Date().getDate()-1),
        width               : 130,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox('instance');
    
    //검색종료일시 시간
    dtctEndTime =  $('.end-time').dxDateBox({
        type                : 'time',
        value               : endSettingTime,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    

    //상단 조회 버튼
    dtctSearchBtn = $('.traf-dtct-search-btn').dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
        onClick(){
            hsEvent();
        }
    }).dxButton("instance")
   


    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance")
 
    
     //소통정보 이력분석 테이블
     dtctListTable = $(".dtct-list-talbe").width('100%').height('100%').dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        headerFilter: {
            visible: true,
        },
        selection: {
            mode: 'multiple',
            showCheckBoxesMode:"onClick"
        },
        keyExpr : ['vds_dtct_id', 'istl_lane'],
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:[
            {
                dataField    : "vds_ctlr_nmbr",
                caption      : "제어기",
                alignment    : "center",
                groupIndex   : 0,
                groupCellTemplate(c,e){
                    if (e.data) {
                        let data = e.data;
                        if (data.items.length > 0) {
                            c.text('VDS : [' + e.value + '] ' + e.data.items[0].vds_nm);
                        }
                        else {
                            c.text('VDS : [' + e.value + ']');
                        }
                    }
                }
            },
            {
                dataField    : "vds_dtct_nmbr",
                caption      : "검지기 번호",
                alignment    : "center",
            },
            {
                dataField    : "vds_dtct_nm",
                caption      : "검지기 명",
                alignment    : "center",
                cellTemplate(c,e){
                    c.css('text-align','left');
                    c.text(e.displayValue)
                }
            },
            {
                dataField   : "dtct_type_desc",
                caption     : "검지기 유형",
                alignment   : "center",
            },
            {
                dataField    : "istl_lane",
                caption      : "설치차로",
                alignment    : "center",
            },
        ],
      
        
    }).dxDataGrid("instance");

    dtctTable = $('.dtct-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : ['vds_dtct_nmbr', 'clct_dt'],
        scrolling               : {
            mode : 'virtual',
        },
        headerFilter: {
            visible: true,
        },
        export:{
            enabled : true,
            texts   : {
                exportAll:"엑셀 파일",
            },
        },
        sorting : {
            showSortIndexes : false,
        },
        columns:[
            
                {
                    dataField    : "vds_ctlr_id",
                    caption      : "제어기ID",
                    alignment    : "center",
                    sortIndex    : 1,
                    sortOrder    : "asc",
                    alignment    : "center",
                },
                {
                    dataField    : "vds_dtct_nmbr",
                    caption      : "검지기 ID",
                    alignment    : "center",
                },
                {
                    dataField   : "dtct_type_desc",
                    caption     : "검지기 유형",
                    alignment   : "center",
                },
                {
                    dataField    : "vds_nm",
                    caption      : "검지기 명",
                    alignment    : "center",
                    cellTemplate(c,e){
                        c.css('text-align','left');
                        c.text(e.displayValue)
                    }
                },
                {
                    dataField    : "clct_dt",
                    caption      : "수집일자",
                    alignment    : "center",
                    sortIndex    : 2, 
                    sortOrder    : "asc",
                },
                {
                    dataField    : "tfvl",
                    caption      : "교통량(대)",
                    alignment    : "center",
                    format       : "#,###,##0",
                },
                {
                    dataField    : "avrg_ocpy_rate",
                    caption      : "평균 점유율(%)",
                    alignment    : "center",
                },
                {
                    dataField    : "sped",
                    caption      : "평균속도(km/h)",
                    alignment    : "center",
                },
            ],
            onExporting(e){
                gridExcellExporting(e, _pageName);
            },
    }).dxDataGrid('instance');

    fetchBaseData();
})

function fetchBaseData(){
    let infoData = [];
    let vdsListData = [];
    getData('/api/vds/manager/info', infoData);
    getData('/api/Vds/manager/dtct', vdsListData);
    
    if (infoData[0].length > 0) {
        dataSorting(infoData[0],'vds_ctlr_nmbr');
    }
    if (vdsListData[0].length > 0) {
        dataSorting(vdsListData[0],'vds_dtct_nmbr');
    }

    if (infoData[0].length > 0 && vdsListData[0].length > 0) {
        vdsListData[0].map((item)=>{
            infoData[0].map((obj)=>{
                if (item.vds_ctlr_nmbr === obj.vds_ctlr_nmbr) {
                    item.vds_nm = obj.vds_nm;
                }
            })
        });
    }
    dtctListTable.option('dataSource', vdsListData[0]);
}

 //구간별 데이터 세팅
 function hsEvent() {
     let TO_DT        = null;
     let FROM_DT      = null;
     let id           = "";
     const selectData = dtctListTable.getSelectedRowsData();
     let updateData = {};
     switch (true) {

         case selectData <= 0 :
            notSelectMsg(pageMsg);
            return false;

         case !validationCheck( dtctStartDate, dtctEndDate, dtctStartTime, dtctEndTime ) :
            return false;

         case getDate( dtctStartDate.option('value'), dtctStartTime.option('value') ) > getDate( dtctEndDate.option('value'), dtctEndTime.option('value') ):
            dtctStartDate.focus();
            alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, dtctStartDate);
            return false;

         default:
            FROM_DT = getDate( dtctStartDate.option('value'), dtctStartTime.option('value') );
            TO_DT = getDate( dtctEndDate.option('value'), dtctEndTime.option('value') );
            for( idx in selectData){
                id += selectData[idx].vds_dtct_nmbr + ",";
            }
            break;
     }
    
    updateData = {
        FROM_DT : FROM_DT,
        TO_DT   : TO_DT,
        id      : id.slice(0,-1),
    };
    dtctData = [];
    getDataAsync( commonUri, (jsonData)=>{
        dtctData = jsonData;
        if ( dtctData.length > 0 ) {
            dtctData.map((item)=>{
                if(nullChecker(item.clct_dt) !== ""){
                    item.clct_dt = getParseDateTime(item.clct_dt);
                }
            })
        }

        dtctTable.option( 'dataSource', dtctData );
        selResultMsg(dtctData);
    }, null, updateData );
 }
