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

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

//공통
let commonUri            = '/api/cctv/history/stts-hs';
const _pageName           = 'CCTV 상태이력';

$(()=>{
    
    //검색시작일시 년월일
    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               : firstSettingTime,
        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")
   


    //상단 닫기 버튼
    $(".close-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              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'multiple',
            showCheckBoxesMode:"onClick"
        },
        headerFilter: {
            visible: true,
        },
        keyExpr : 'cctv_ctlr_id',
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:[
                    {
                        dataField    : "cctv_ctlr_id",
                        caption      : "제어기 ID",
                        alignment    : "center",
                        width        : 141,
                        sortIndex    : 0, 
                        sortOrder    : "asc",
                    },
                    {
                        dataField    : "istl_lctn_nm",
                        caption      : "설치 위치",
                        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,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'idx',
        scrolling               : {
            mode : 'virtual',
        },
        headerFilter: {
            visible: true,
        },
        export:{
            enabled : true,
            texts   : {
                exportAll:"엑셀 파일",
            },
        },
        sorting:{
            showSortIndexes: false,
        },
        columns:[
            {
                caption   : '기본 정보',
                alignment : 'center',
                columns   : [
                    {
                        dataField    : "cctv_ctlr_nmbr",
                        caption      : "관리번호",
                        alignment    : "center",
                        width        : 140,
                        cssClass     : 'p-n',
                        sortIndex    : 1,
                        sortOrder    : "asc",
                    },
                    {
                        dataField    : "cctv_ctlr_id",
                        caption      : "제어기 ID",
                        width        : 140,
                        cssClass     : 'p-n',
                        alignment    : "center",
                    },
                    {
                        dataField    : "istl_lctn_nm",
                        caption      : "설치 위치",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c,e){
                            c.addClass('p-nl');
                            c.text(e.displayValue)
                        }
                    },
                    {
                        dataField    : "crtn_dt",
                        caption      : "수집시각",
                        width        : 160,
                        alignment    : "center",
                        cssClass     : 'p-n',
                        sortIndex    : 2,
                        sortOrder    : 'asc',
                    },
                ]
            },
            {
                caption   : '통신',
                alignment : 'center',
                columns   : [
                    {
                        dataField    : "cmnc_stts_desc",
                        caption      : "통신 상태",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c,e){
                            sttsTemplate(c, e, e.data.cmnc_stts_cd);
                        }
                    },
                ]
            },
            {
                caption   : '제어기상태',
                alignment : 'center',
                columns   : [
                    {
                        dataField    : "cbox_door_stts_desc",
                        caption      : "문열림",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, e.data.cbox_door_stts_cd);
                        }
                    },
                    {
                        dataField    : "fan_stts_desc",
                        caption      : "팬",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, e.data.fan_stts_cd);
                        }
                    },
                    {
                        dataField    : "hetr_stts_desc",
                        caption      : "히터",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, e.data.hetr_stts_cd);
                        }
                    },
                    {
                        dataField    : "cbox_tmpr",
                        caption      : "함체온도",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, 'temp');
                        }
                    },
                    {
                        dataField    : "video_input_desc",
                        caption      : "Video 인정",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, e.data.video_input);
                        }
                    },
                    {
                        dataField    : "pan",
                        caption      : "PAN",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, e.data.pan);
                        }
                    },
                    {
                        dataField    : "tilt",
                        caption      : "TILT",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, e.data.tilt);
                        }
                    },
                    {
                        dataField    : "zoom",
                        caption      : "ZOOM",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, e.data.zoom);
                        }
                    },
                    {
                        dataField    : "focus",
                        caption      : "FOCUS",
                        alignment    : "center",
                        cssClass     : 'p-n',
                        cellTemplate(c, e){
                            sttsTemplate(c, e, e.data.focus);
                        }
                    }
                ]
            },
        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
    }).dxDataGrid('instance');
    
    fetchListData();
})

function fetchListData(){
    getDataAsync('/api/cctv/common/cctv-list', (jsonData)=>{
        hsListData = jsonData;
        hsListTalbe.option('dataSource', hsListData);
    });
}
 //구간별 데이터 세팅
 function hsEvent() {
     let TO_DT        = null;
     let FROM_DT      = null;
     let id           = "";
     const selectData = hsListTalbe.getSelectedRowsData();
     let updateData = {};
    
     switch (true) {

         case selectData <= 0 :
            alertWarning('CCTV가 선택 되지 않았습니다.<br>CCTV 목록에서 CCTV를 선택해주세요') 
            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') ):
            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].cctv_ctlr_nmbr + ",";
            }
            break;
     }
    
    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;
    updateData[ 'id' ]      = id.slice(0,-1);
    getDataAsync(commonUri, (jsonData)=>{
        hsData = jsonData;
        if( hsData.length > 0){
            let cnt = 0;
            hsData.map((item)=>{
                if (nullChecker(item.crtn_dt) !== "") {
                    item.crtn_dt = getParseDateTime(item.crtn_dt)
                }
                item.idx = cnt++;
           })
        }
        hsTable.option( 'dataSource', hsData );
        selResultMsg(hsData);
    }, null, updateData);
   
 }

 function sttsTemplate(c, e, code){
    let text   = e.displayValue;
    const cmncCd = e.data.cmnc_stts_cd;
    const check = cmncCd === code ? true : false;
    const nullVal = ['정보없음', 'UNKNOWN', 255, null, "-", undefined, ''];
    if (!check && cmncCd === 'CMS1') {
        c.text('-');
        c.addClass('gray');
    }
    else if (nullVal.includes(text)) {
        c.text('-');
        c.addClass('gray');
    }
    else {
        c.addClass(code);
        c.text(text);
    }
    return c;
 }