//우측 섹션 관련
let unitSystData      = [];
let unitSystTable     = null;
let unitSystChart     = null;

//좌측 섹션 관련
let unitSystStartDate = null;
let unitSystEndDate   = null;
let unitSystStartTime = null;
let unitSystEndTime   = null;
let unitSystSearchBtn = null;
let selectData        = [];

//차트 관련
let series           = [];
let xAxis            = [];
let yAxisTitle       = '개수';
let xAxisTitle       = '프로세스';

//공통 uri
let commonUri        = '/api/statistics/unit-syst-stts/';
const _pageName       = '프로세스상태 통계'


//기본 날짜 세팅
const strtDate = new Date().setDate(new Date().getDate()-1);
const endDate = new Date();

//chart series
series = [
        {
            id   : 'sts_tot',
            name : '전체',
            color: 'rgb(247, 163, 92)',
            data : [],
        },
        {
            id   : 'cnt_sps1',
            name : '실행중',
            color: 'rgb(124, 181, 236)',
            data : [],
        },
]

$(()=>{
  
    //검색시작일시 년월일
    unitSystStartDate =  $('.strt-date').dxDateBox({
        type                : 'date',
        value               : strtDate,
        width               : 130,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox('instance');
    
    //검색 시작일시 시간
    unitSystStartTime =  $('.strt-time').dxDateBox({
        type                : 'time',
        value               : 1645110000000,
        tabIndex            : 0,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    
    //검색종료일시 년월일
    unitSystEndDate =  $('.end-date').dxDateBox({
        type                : 'date',
        value               : endDate,
        width               : 130,
        height              : '28px',
        stylingMode         :'outlined',
        displayFormat       : 'yyyy-MM-dd',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)0000-00-00',
    }).dxDateBox('instance');
    
    //검색종료일시 시간
    unitSystEndTime =  $('.end-time').dxDateBox({
        type                : 'time',
        value               : 1645196399000,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');
    
    
    //상단 조회 버튼
    unitSystSearchBtn = $('.unit-syst-stts-search-btn').dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
        onClick(){
            fcltSttsEvent();
        }
    }).dxButton("instance")
   
    //차트 이지미 저장 버튼
    $(".export-button").dxButton({
        stylingMode : 'outlined',
        text        : '차트 저장',
        icon        : 'export',
        height      : '40px',
        width       : '110px',
        onClick(){
            if( unitSystData.length <= 0 || unitSystData[0].length <= 0 ){
                alertWarning("저장하실 차트 데이터가 없습니다.");
                return false;
            }

            confirmMessage(_pageName + " 차트를 파일로 저장 하시겠습니까?").done((yes)=>{
                if (yes){
                    unitSystChart.exportChart({
                        filename: _pageName + '_' + excellTime()
                    });
                }
            });
        }
    })

    $('.page-box > div').hover(function(){
        $(this).addClass('dx-menu-item dx-state-hover');
    },function(){
        $(this).removeClass('dx-menu-item dx-state-hover');
    })
    //차트 변경 버튼
    $(".chart-change").dxMenu({
        dataSource: chartDataSource,
        hideSubmenuOnMouseLeave: true,
        cssClass:'dx-button-mode-outlined',
        height: 40,
        showFirstSubmenuMode: {
            name: "onClick",
            delay: { show: 0, hide: 100 },
        },
        displayExpr: "name",
        submenuDirection: "auto",
        visible: true,
        onItemClick(info){
            const item = info.itemData;
            if(item.type){
                const dataSource = [...info.component.option('dataSource')]
                dataSource[0].name = item.name
                dataSource[0].icon = item.type
                info.component.option('dataSource', dataSource);
                unitSystChart.update({
                    chart: {
                        type: item.type,
                    }
                })
            }
        }
    }).dxMenu("instance");
    
    //시설물 통신단절 통계 차트
    unitSystChart = Highcharts.chart('unit-syst-stts-chart', {
        chart: {
            type: 'line',
            height: 342,
            backgroundColor: {
                classNmae: 'dx-theme-background-color',
            },
            zoomType: 'x',
            events: {
                load: function() {
                }
            },
        },
        title: {
            text: null
        },
        xAxis: {
            categories: null,
            title: {
                text: xAxisTitle,
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                }
            },
            labels:{
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                }
            }
        },
        
        yAxis: {
            min: 0,
            title: {
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                },
                text: yAxisTitle,
            },
            labels: {
                overflow: 'justify',
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                },
                format: '{value:,.0f}'
            },
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            },
            series: {
                lineWidth: 2,
                turboThreshold: 0,
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            floating: false,
            y: 50,
            borderWidth: 1,
            itemStyle:{
                color: $('.dx-theme-material-typography').css('color'),
            },
            backgroundColor: {
                className : 'dx-nav-item dx-theme-border-color',
            },
            shadow: true,
        },
        exporting : {
            enabled : false,
        },
        credits : {
            enabled : false
        },
        series : series
    });

    window.$chart = unitSystChart;
    
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance")
    
    
     //시설물 통신단절 통계 테이블
     unitSystTable = $(".unit-syst-stts-table").width('100%').height('100%').dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        selection: {
            mode: 'single',
        },
        keyExpr :'syst_id',
        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    : "syst_id",
                caption      : "프로세스 ID",
                alignment    : "center",
                sortIndex    : 0, 
                sortOrder    : "asc",
            },
            {
                dataField    : "syst_nm",
                caption      : "프로세스 명칭",
                alignment    : "center",
                cellTemplate(c,e){
                    c.css('text-align', 'left');
                    c.text(e.displayValue);
                }
                
            },
            {
                dataField    : "sts_tot",
                caption      : "전체",
                alignment    : "center",
                format       : "#,###,##0",
            },
            {
                dataField    : "cnt_sps1",
                caption      : "실행중",
                alignment    : "center",
                format       : "#,###,##0",
            },
            {
                dataField    : "run_rate",
                caption      : "가동율",
                alignment    : "center",
                cellTemplate(c,e){
                    const progressBar = $(`<div class="progress-bar">
                                            <div class="text">${e.displayValue.toFixed(1) + '%'}</div>
                                            <div class="prog-inside"></div>
                                            <div class='prog-outside'></div>
                                        </div>`);
                    $(progressBar).find('.prog-inside').css('width', e.displayValue.toFixed(1) + '%');
                    $(progressBar).find('.prog-outside').css('width', 100 - e.displayValue.toFixed(1) + '%');
                    return progressBar;
                },
            }
        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        
    }).dxDataGrid("instance");
  
})


//구간별 데이터 세팅
function fcltSttsEvent() {
    let TO_DT      = null;
    let FROM_DT    = null;
    let updateData = {};
    
    if ( !validationCheck( unitSystStartDate, unitSystEndDate, unitSystStartTime, unitSystEndTime )) return false;
    FROM_DT = getDate( unitSystStartDate.option('value'), unitSystStartTime.option('value') );
    TO_DT = getDate( unitSystEndDate.option('value'), unitSystEndTime.option('value') );
    
    if( FROM_DT > TO_DT ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, unitSystStartDate);
        return false;
    };
  
    if (Number(FROM_DT) + 100000000 <= Number(TO_DT)) {
        return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, unitSystEndDate);
    }
    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;
    finalEvent( commonUri, updateData );
}

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

    //getData( uri, unitSystData, updateData );
    getDataAsync(uri, (jsonData)=>{
        unitSystData = jsonData;
        
        series[0].data = [];
        series[1].data = [];
        
        unitSystData.map((item)=>{
            xAxis.push(item.syst_nm)
            series[0].data.push(item[series[0].id])
            series[1].data.push(item[series[1].id])
        });
        
        unitSystTable.option( 'dataSource', unitSystData );
        unitSystTable.clearSelection();
        unitSystTable.option('focusedRowIndex', -1);
        
        unitSystChart.update({
                xAxis :{
                categories: xAxis
            },
            series:series
        });
        
        pageNation(unitSystChart, xAxis);
        
        alertConfirm('데이터 조회가 완료 되었습니다. [' + unitSystData.length + '건]');
    }, null, updateData);
}
