//우측 섹션 관련
let hsData       = [];

//좌측 섹션 관련
let hsListTalbe      = null;
let hsStartDate      = null;
let hsEndDate        = null;
let hsStartTime      = null;
let hsEndTime        = null;
let hsSearchBtn      = null;

//공통
let commonUri            = '/api/vms/history/stts';
const _pageName           = 'VMS 상태이력';

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

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

    //상단 조회 버튼
    hsSearchBtn = $('.traf-hs-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")
 
    
     //소통정보 이력분석 테이블
     hsListTalbe = $(".hs-list-talbe").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        headerFilter: {
            visible: true,
        },
        selection: {
            mode: 'multiple',
            showCheckBoxesMode:"onClick"
        },
        keyExpr : 'vms_ctlr_nmbr',
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:[
                    {
                        dataField    : "vms_ctlr_id",
                        caption      : "VMS ID",
                        width        : 105,
                        alignment    : "center",
                    },
                    {
                        dataField    : "vms_nm",
                        caption      : "VMS 명칭",
                        alignment    : "center",
                        cellTemplate(c,e){
                            c.css('text-align','left');
                            c.text(e.displayValue)
                        }
                    },
        ],
      
        
    }).dxDataGrid("instance");

    hsTable = $('.history-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : ['vms_ctlr_nmbr','crtn_dt'],
        noDataText              : '표출할 정보가 없습니다.',
        scrolling               : {
            mode : 'standard',
        },
        headerFilter: {
            visible: true,
        },
        paging: {
            enabled: true,
            pageSize: 1000,
        },
        export:{
            enabled : true,
            texts   : {
                exportAll:"엑셀 파일",
            },
        },
        sorting:  {
            showSortIndexes : false,
        },
        columns:[
            {
                caption   : 'VMS 정보',
                alignment : 'center',
                columns   : [
                    {
                        dataField    : "vms_ctlr_nmbr",
                        caption      : "번호",
                        alignment    : "center",
                        cssClass     : 'pad-ctrl',
                        width        : 100,
                        sortIndex    : 1, 
                        sortOrder    : "asc",
                    },
                    {
                        dataField    : "vms_ctlr_id",
                        caption      : "VMS ID",
                        width        : 110,
                        alignment    : "center",
                    },
                    {
                        dataField    : "vms_nm",
                        caption      : "VMS 명칭",
                        alignment    : "center",
                        cellTemplate(c,e){
                            c.css('text-align','left');
                            c.text(e.displayValue)
                        }
                    }
                ]
            },
            {
                caption   : '통신',
                alignment : 'center',
                columns   : [
                    {
                        dataField    : "crtn_dt",
                        caption      : "수집시각",
                        alignment    : "center",
                        sortIndex    : 2, 
                        sortOrder    : "asc",
                    },
                    {
                        dataField    : "cmnc_stts_desc",
                        caption      : "통신 상태",
                        alignment    : "center",
                        width        : 115,
                        cellTemplate(c,e){
                            return  state(c, e, 'cmnc_stts_cd');
                        }
                    },
                ]
            },
            {
                caption   : '모듈',
                alignment : 'center',
                visible   : false,
                columns   : [
                    {
                        dataField    : "pwer_stts_desc",
                        caption      : "전원상태",
                        width        : 110,
                        alignment    : "center",
                        cellTemplate(c,e){
                            return  state(c, e, 'pwer_stts_cd');
                        }
                    },
                ]
            },
            {
                caption   : '함체',
                alignment : 'center',
                columns   : [
                    {
                        dataField    : "cbox_door_stts_desc",
                        caption      : "도어",
                        width        : 85,
                        alignment    : "center",
                        cellTemplate(c,e){
                            return  state(c, e, 'cbox_door_stts_cd');
                        }
                    },
                    {
                        dataField    : "fan_stts_desc",
                        caption      : "팬상태",
                        width        : 110,
                        alignment    : "center",
                        cellTemplate(c,e){
                            return  state(c, e, 'fan_stts_cd');
                        }
                    },
                    {
                        dataField    : "hetr_stts_desc",
                        caption      : "히터상태",
                        width        : 110,
                        alignment    : "center",
                        cellTemplate(c,e){
                            return  state(c, e, 'hetr_stts_cd');
                        }
                    },
                    {
                        dataField    : "cbox_tmpr",
                        caption      : "온도",
                        width        : 85,
                        alignment    : "center",
                        cellTemplate(c, e) {
                            return  state(c, e, 'cbox_tmpr');
                        }
                    },
                    {
                        dataField    : "brgh_val",
                        caption      : "화면휘도",
                        width        : 110,
                        alignment    : "center",
                        cellTemplate(c,e){
                            return  state(c, e, 'brgh_val');
                        }
                    },
                ]
            },
        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
    }).dxDataGrid('instance');
    fetchBaseData();
})
function fetchBaseData(){
    getDataAsync('/api/vms/common/vms-list', (jsonData) => hsListTalbe.option('dataSource', jsonData));
}
 //구간별 데이터 세팅
 function hsEvent() {
     let TO_DT        = null;
     let FROM_DT      = null;
     let id           = "";
     const selectData = hsListTalbe.getSelectedRowsData();
     let updateData = {};
    
     switch (true) {

         case selectData <= 0 :
            alertWarning('VMS가 선택 되지 않았습니다.<br>VMS 목록에서 VMS를 선택해주세요');
            return false;

         case !validationCheck( hsStartDate, hsEndDate, hsStartTime, hsEndTime ) :
            return false;

         case getDate( hsStartDate.option('value'), hsStartTime.option('value') ) > getDate( hsEndDate.option('value'), hsEndTime.option('value') ):
            hsStartDate.focus();
            alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, hsStartDate);
            return false;

         default:

            FROM_DT = getDate( hsStartDate.option('value'), hsStartTime.option('value') );
            TO_DT = getDate( hsEndDate.option('value'), hsEndTime.option('value') );
            for( idx in selectData){
                id += selectData[idx].vms_ctlr_nmbr + ",";
            }
            break;
     }
    
    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;
    updateData[ 'id' ]      = id.slice(0,-1)
    hsData = [];

    getDataAsync(commonUri, (jsonData)=>{
        hsData = jsonData;
        if ( hsData.length > 0) {
            hsData.map((item)=>{
                if (nullChecker(item.crtn_dt) !== "") {
                    item.crtn_dt = getParseDateTime(item.crtn_dt)
                }
           })
        }
        hsTable.option( 'dataSource', hsData );
        hsTable.option( 'paging', {
                pageIndex : 0,
        })
        alertConfirm('데이터 조회가 완료 되었습니다. [' + hsData.length + '건]')
        console.log(hsData);
    }, null, updateData);
 }

 