/**
 * @TODO DSRC 상태 이력 조회 날짜 받는 파라미터가 없음
 */
//우측 섹션 관련
let sttsData           = [];
let sttsTable          = null;

//좌측 섹션 관련
let sttsListTable      = null;
let sttsListData       = [];
let sttsStartDate      = null;
let sttsEndDate        = null;
let sttsStartTime      = null;
let sttsEndTime        = null;
let sttsSearchBtn      = null;

//공통
let commonUri        = '/api/rse/tb_rse_ctlr_stts_hs';
const _pageName       = 'DSRC-제어기 상태 이력';
const pageMsg        = 'DSRC-제어기'
const _cdMap         = new Map();

//기본 날짜 세팅
getData('/api/rse/tb_rse_ctlr', sttsListData);
$(()=>{
    //검색시작일시 년월일
    sttsStartDate =  $('.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');

    //검색 시작일시 시간
    sttsStartTime =  $('.strt-time').dxDateBox({
        type                : 'time',
        value               : firstSettingTime,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    
    //검색종료일시 년월일
    sttsEndDate =  $('.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');
    
    //검색종료일시 시간
    sttsEndTime =  $('.end-time').dxDateBox({
        type                : 'time',
        value               : endSettingTime,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    

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

    sttsTable = $('.stts-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : ['rse_ctlr_nmbr', 'crtn_dt'],
        scrolling               : {
            mode : 'virtual',
        },
        headerFilter: {
            visible: true,
        },
        sorting: {
            showSortIndexes:false,
        },
        export:{
            enabled : true,
            texts   : {
                exportAll:"엑셀 파일",
            },
        },
        columns:[
            {
                caption   : 'DSRC 정보',
                alignment : 'center',
                cssClass  : 'padding-ctrl',
                columns   : [
                    {
                        dataField    : "rse_ctlr_nmbr",
                        caption      : "관리번호",
                        alignment    : "center",
                        sortOrder    : 'asc',
                        sortIndex    : 1,
                    },
                    {
                        dataField    : "rse_ctlr_id",
                        caption      : "제어기 ID",
                        alignment    : "center",
                    },
                    {
                        dataField    : "istl_lctn_nm",
                        caption      : "명칭",
                        alignment    : "center",
                        cellTemplate(c,e) {
                            alignTemplate(c, e, 'left');
                        }
                    },
                    {
                        dataField    : "coll_cnt",
                        caption      : "수집건수",
                        alignment    : "center",
                        width        : 100,
                        visible      : false,
                    },
                ]
            },
            {
                caption   : '통신',
                alignment : 'center',
                columns   : [
                    {
                        dataField    : "crtn_dt",
                        caption      : "수집시각",
                        alignment    : "center",
                        format       : "yyyy-MM-dd HH:mm:ss",
                        dataType     : 'datetime',
                        sortOrder    : 'asc',
                        sortIndex    : 2,
                    },
                    {
                        dataField    : "cmnc_stts_desc",
                        caption      : "통신",
                        alignment    : "center",
                        width        : 100,
                        cellTemplate(c,e){
                            return getSttsClass(e.data.cmnc_stts_cd, e.displayValue, c);
                        }
                    },
                    {
                        dataField    : "miss_stts_yn",
                        caption      : "결측 여부",
                        alignment    : "center",
                        width        : 100,
                        visible      : false,
                    },
                ]
            },
            {
                caption   : '제어기 상태',
                alignment : 'center',
                visible   : false,
                columns   : [
                    {
                        dataField : 'cntl_devc_stts',
                        caption   : '제어 장치',
                        alignment : 'center',
                        width     : 100,
                        lookup : {
                            dataSource : [],
                            valueExpr  : 'cmmn_cd',
                            displayExpr : 'cmmn_cd_kor_nm',
                        },
                        visible      : false,
                    },
                    {
                        dataField    : "cbox_door_stts_desc",
                        caption      : "함체문",
                        alignment    : "center",
                        visible      : false,
                        width        : 100,
                        cellTemplate(c,e){
                            return state(c, e, 'cbox_door_stts_cd');
                        }
                    },
                    {
                        dataField    : "front_door_stts_desc",
                        caption      : "앞문",
                        alignment    : "center",
                        width        : 100,
                        cellTemplate(c,e){
                            return state(c, e, 'front_door_stts_cd');
                        }
                    },
                    {
                        dataField    : "back_door_stts_desc",
                        caption      : "뒷문",
                        alignment    : "center",
                        width        : 100,
                        cellTemplate(c,e){
                            return state(c, e, 'back_door_stts_cd');
                        }
                    },
                    {
                        dataField    : "fan_stts_desc",
                        caption      : "팬",
                        alignment    : "center",
                        width        : 100,
                        cellTemplate(c,e){
                            return state(c, e, 'fan_stts_cd');
                        }
                    },
                    {
                        dataField    : "hetr_stts_desc",
                        caption      : "히터",
                        alignment    : "center",
                        width        : 100,
                        cellTemplate(c,e){
                            return state(c, e, 'hetr_stts_cd');
                        }
                    },
                    {
                        dataField    : "cbox_hmdt",
                        caption      : "함체 습도",
                        alignment    : "center",
                        width        : 100,
                        cellTemplate(c,e){
                            return state(c, e, 'cbox_hmdt');
                        }
                    },
                    {
                        dataField    : "cbox_tmpr",
                        caption      : "함체 온도",
                        alignment    : "center",
                        width        : 100,
                        cellTemplate(c,e){
                            return state(c, e, 'cbox_tmpr');
                        }
                    },
                    {
                        dataField    : "rtu_stts_desc",
                        caption      : "RTU",
                        alignment    : "center",
                        width        : 100,
                    },
                ]
            },
        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
    }).dxDataGrid('instance');
    fetchCdData();
})
    function cdTemplate(c, e, cd) { 
        const code = e.displayValue;
        let text = "-";
        console.log(code);
        if (nullChecker(code) !== "") {
            const paramMap = _cdMap.get(cd);
            console.log(paramMap);
            if (paramMap) {
                text = paramMap.get(code);
                if (cd === 'CMS') {
                    c.addClass(code);
                }
            }
        }
        c.text(text);
        return c;
    }
    function fetchCdData(){
        const codeUri = '/api/database/code/cmmn-cd/';
        const cdParams = [
            'CMS',
            'ATN',
            'RSS',
            'WRK',
        ]
        for (let param of cdParams) {
            getDataAsync(codeUri + encodeURIComponent(param), recvCdData, param);
        }
    }
    function recvCdData(jsonData, param){
        if (jsonData.length > 0) {
            _cdMap.set(param, new Map());
            const paramMap = _cdMap.get(param);
            jsonData.map((obj)=>{
                paramMap.set(obj.cmmn_cd, obj.cmmn_cd_kor_nm)
            })
        }
    }
 //구간별 데이터 세팅
 function hsEvent() {
     let TO_DT        = null;
     let FROM_DT      = null;
     let id           = "";
     const selectData = sttsListTable.getSelectedRowsData();
     let updateData = {};
     switch (true) {

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

         case !validationCheck( sttsStartDate, sttsEndDate, sttsStartTime, sttsEndTime ) :
            return false;

         case getDate( sttsStartDate.option('value'), sttsStartTime.option('value') ) > getDate( sttsEndDate.option('value'), sttsEndTime.option('value') ):
            sttsStartDate.focus();
            alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, sttsStartDate);
            return false;

         default:

            FROM_DT = getDate( sttsStartDate.option('value'), sttsStartTime.option('value') );
            TO_DT = getDate( sttsEndDate.option('value'), sttsEndTime.option('value') );
            for( idx in selectData){
                id += selectData[idx].rse_ctlr_nmbr + ",";
            }
            break;
     }
    
    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;
    updateData[ 'id' ]      = id.slice(0,-1)
    sttsData = [];
    console.log(updateData);
    getDataAsync( commonUri, (jsonData)=>{
        sttsData = jsonData;
        console.log(sttsData);
        if ( sttsData.length > 0) {
            sttsData.map((item)=>{
                if(nullChecker(item.crtn_dt) !== ""){
                    item.crtn_dt = getParseDateTime(item.crtn_dt)
                }
           });
        }

        sttsTable.option( 'dataSource', sttsData );
        selResultMsg(sttsData);
    }, null, updateData );
    
 }

 function getSttsClass(sttsCd, text, container, cmnc_stts_cd) {
    //container.css('padding','2px');
    //container.css('height','1px');
    let classNm = sttsCd;
    let textVal = text;
    if (sttsCd === null || sttsCd === undefined || sttsCd === 255 || cmnc_stts_cd === 'CMS1' || cmnc_stts_cd === 'CMS2') {
        classNm = 'gray';
        textVal = '-';
    }
    container.addClass(classNm);
    container.text(textVal);
    return container;
}