//우측 섹션 관련
let fcltSttsData      = [];
let fcltSttsTable     = null;
let fcltSttsChart     = null;

//좌측 섹션 관련
let fcltSttsSelect    = null;
let fcltSttsStartDate = null;
let fcltSttsEndDate   = null;
let fcltSttsStartTime = null;
let fcltSttsEndTime   = null;
let fcltSttsSearchBtn = null;
let selectData        = [];

//차트 관련
let series           = [];
let xAxis            = [];
let yAxisTitle       = '장애수';
let xAxisTitle       = '시설물';

//공통 uri
let commonUri        = '/api/statistics/fclt-stts';
const _pageName       = '시설물통신단절 통계'

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

//chart series
series = [
    {
        id   : 'cnt_tot',
        name : '합계',
        color: 'rgb(124, 181, 236)',
        data : [],
    },
    {
        id   : 'cnt_cms1',
        name : '장애수',
        color: 'red',
        data : [],
    },
    {
        id   : 'cnt_cms2',
        name : '알수없음',
        color: 'rgb(247, 163, 92)',
        data : [],
    },
]

$(()=>{

    //시설물 구분 셀렉트박스
    fcltSttsSelect = $('.fclt-stts-select').dxSelectBox({
        dataSource  : null,
        width       : 215,
        height      : 28,
        valueExpr   : 'fclt_cd',
        displayExpr : 'fclt_nm',
        stylingMode : "outlined",
    }).dxSelectBox('instance');

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

    //검색 시작일시 시간
    fcltSttsStartTime =  $('.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');

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

    //검색종료일시 시간
    fcltSttsEndTime =  $('.end-time').dxDateBox({
        type                : 'time',
        value               : 1645196399000,
        width               : 75,
        interval            : 10,
        height              : '28px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox('instance');


    //상단 조회 버튼
    fcltSttsSearchBtn = $('.fclt-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( fcltSttsData.length <= 0 || fcltSttsData[0].length <= 0 ){
                alertWarning("저장하실 차트 데이터가 없습니다.");
                return false;
            }

            confirmMessage(_pageName + " 차트를 파일로 저장 하시겠습니까?").done((yes)=>{
                if (yes){
                    fcltSttsChart.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);
                fcltSttsChart.update({
                    chart: {
                        type: item.type,
                    }
                })
            }
        }
    }).dxMenu("instance");

    //시설물 통신단절 통계 차트
    fcltSttsChart = Highcharts.chart('fclt-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 = fcltSttsChart
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance");

    //시설물 통신단절 통계 테이블
    fcltSttsTable = $(".fclt-stts-table").width('100%').height('100%').dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        keyExpr :'fclt_nmbr',
        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    : "fclt_nmbr",
                caption      : "ID",
                alignment    : "center",
                sortIndex    : 0,
            },
            {
                dataField    : "fclt_id",
                caption      : "시설물 ID",
                alignment    : "center",
                width        : 130,
            },
            {
                dataField    : "fclt_nm",
                caption      : "시설물 명칭",
                alignment    : "center",
                cellTemplate(c, e){
                    c.css('text-align', 'left');
                    c.text(nullChecker(e.displayValue));
                }
            },
            {
                dataField    : "cnt_cms1",
                caption      : "장애수",
                alignment    : "center",
                format       : "#,###,##0",
                width        : 120,
            },
            {
                dataField    : "cnt_cms2",
                caption      : "알수없음",
                alignment    : "center",
                format       : "#,###,##0",
                width        : 120,
            },
            {
                dataField    : "cnt_tot",
                caption      : "합계",
                alignment    : "center",
                format       : "#,###,##0",
                width        : 120,
            },

        ],
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },

    }).dxDataGrid("instance");
    fetchComboData();
})

function fetchComboData(){
    getDataAsync( commonUri + '/type', recvComboFunc);
}
function recvComboFunc(jsonData){
    fcltSttsSelect.option('dataSource', jsonData);
    if (jsonData.length > 0) {
        setValue(fcltSttsSelect, jsonData[0].fclt_cd);
    }
}

/**
 * @TODO CCTV 조회 API 확인
 */
//구간별 데이터 세팅
function fcltSttsEvent() {
    let TO_DT      = null;
    let FROM_DT    = null;
    let updateData = {};

    if ( !validationCheck( fcltSttsStartDate, fcltSttsEndDate, fcltSttsStartTime, fcltSttsEndTime )) return false;
    FROM_DT = getDate( fcltSttsStartDate.option('value'), fcltSttsStartTime.option('value') );
    TO_DT = getDate( fcltSttsEndDate.option('value'), fcltSttsEndTime.option('value') );

    if( FROM_DT > TO_DT ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, fcltSttsStartDate);
        return false;
    };

    if (Number(FROM_DT) + 100000000 <= Number(TO_DT)) {
        return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, fcltSttsEndDate);
    }
    updateData[ 'FCLT_CD' ] = fcltSttsSelect.option('value');
    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;
    finalEvent( commonUri, updateData );
}

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

    getDataAsync(uri, (jsonData)=>{
        fcltSttsData = jsonData;

        series[0].data = [];
        series[1].data = [];
        series[2].data = [];

        if (fcltSttsData) {
            fcltSttsData.sort((a,b)=>{
                return a.fclt_nmbr - b.fclt_nmbr
            });

            fcltSttsData.map((item)=>{
                xAxis.push(item.fclt_nm)
                series[0].data.push(item[series[0].id])
                series[1].data.push(item[series[1].id])
                series[2].data.push(item[series[2].id]);
            });

            fcltSttsTable.option( 'dataSource', fcltSttsData );
            fcltSttsTable.clearSelection();
            fcltSttsTable.option('focusedRowIndex', -1);

            fcltSttsChart.update({
                xAxis :{
                    categories: xAxis
                },
                series:series
            });

            pageNation(fcltSttsChart, xAxis);

            alertConfirm('데이터 조회가 완료 되었습니다. [' + fcltSttsData.length + '건]');
        }
    }, null, updateData);
}
