//우측 섹션 관련
let incidentData      = [];
let incidentTable     = null;
let incidentChart     = null;

//구간별 사용 박스
let typtSelect        = null;
let drngSelect        = null;
let incidentStartDate = null;
let incidentEndDate   = null;
let incidentSearchBtn = null;

//차트 관련
let series           = [];
let xAxis            = [];

//공통 uri
let commonUri        = '/api/statistics/incident/';
let firstUri         = 'type';
let secUri           = 'dd';
//기본 날짜 세팅
const strtDate = new Date().setDate(new Date().getDate()-1);
const endDate = new Date();

let toggle = {
    sect : ['link_id','f_name','t_name'],
    type : ['incd_type_cd']
}

const _pageName = '돌발상황 통계';

//chart series
series = [
        {
            id   : 'incd_ocrr_num',
            name : '돌발발생건수',
            color: 'rgb(124, 181, 236)',
            data : [],
        },
        {
            id   : 'ftlt_pnum',
            name : '사망자수',
            color: 'red',
            data : [],
        },
        {
            id   : 'injr_pnum',
            name : '부상자수',
            color: 'rgb(247, 163, 92)',
            data : [],
        },
        {
            id   : 'prpr_dmge_amt',
            name : '재산피해금액',
            color: 'rgb(247, 263, 92)',
            data : [],
        },
]

$(()=>{
    $('.page-box > div').hover(function(){
        $(this).addClass('dx-menu-item dx-state-hover');
    },function(){
        $(this).removeClass('dx-menu-item dx-state-hover');
    })
    //통계 구분 셀렉트박스
    typtSelect = $('.type-select')
        .dxSelectBox({
            items: ['유형별 통계', '구간별 통계'],
            width: 215,
            height: 28,
            stylingMode: 'outlined',
            value: '유형별 통계',
            onItemClick(e) {
                console.log(e);
                if (incidentTable.option('dataSource').length > 0 ){
                    incidentTable.option('dataSource', []);
                    for (let obj of series) {
                        obj.data = [];
                    }
                    incidentChart.update({
                        series : series,
                    })
                    
                } 
                switch (e.itemData) {
                    case '유형별 통계':
                        //컬럼 toggle
                        for (let ii = 0; ii < toggle.type.length; ii++) {
                            showColumn(incidentTable, toggle.type[ii]);
                        }
                        for (let ii = 0; ii < toggle.sect.length; ii++) {
                            hideColumn(incidentTable, toggle.sect[ii]);
                        }
                        //유형
                        firstUri = 'type';
                        break;
                    case '구간별 통계':
                        //컬럼 toggle
                        for (let ii = 0; ii < toggle.sect.length; ii++) {
                            showColumn(incidentTable, toggle.sect[ii]);
                        }
                        for (let ii = 0; ii < toggle.type.length; ii++) {
                            hideColumn(incidentTable, toggle.type[ii]);
                        }
                        //구간
                        firstUri = 'sect';
                        break;
                    default:
                        break;
                }
            },
        })
        .dxSelectBox('instance');

    //통계 단위 셀렉트 박스
    drngSelect = $('.drng-select')
        .dxSelectBox({
            items: ['일간 통계', '월간 통계', '년간 통계'],
            width: 215,
            height: 28,
            stylingMode: 'outlined',
            value: '일간 통계',
            onItemClick(e) {
                switch (e.itemData) {
                    case '일간 통계':
                        //uri 설정 및 포맷 변경
                        secUri = 'dd';
                        incidentStartDate.option('displayFormat', 'yyyy년 MM월 dd일');
                        incidentEndDate.option('displayFormat', 'yyyy년 MM월 dd일');
                        break;
                    case '월간 통계':
                        secUri = 'mn';
                        incidentStartDate.option('displayFormat', 'yyyy년 MM월');
                        incidentEndDate.option('displayFormat', 'yyyy년 MM월');
                        break;
                    case '년간 통계':
                        secUri = 'yy';
                        incidentStartDate.option('displayFormat', 'yyyy년');
                        incidentEndDate.option('displayFormat', 'yyyy년');
                        break;
                    default:
                        break;
                }
            },
        })
        .dxSelectBox('instance');

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

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

    //상단 조회 버튼
    incidentSearchBtn = $('.incident-search-btn')
        .dxButton({
            stylingMode: 'outlined',
            text: '조회',
            icon: 'refresh',
            width: '80px',
            onClick() {
                incidentEvent(firstUri, secUri);
            },
        })
        .dxButton('instance');

    //차트 이지미 저장 버튼
    $('.export-button').dxButton({
        stylingMode: 'outlined',
        text: '차트 저장',
        icon: 'export',
        height: '40px',
        width: '110px',
        onClick() {
            if (incidentData.length <= 0 || incidentData[0].length <= 0) {
                alertWarning('저장하실 차트 데이터가 없습니다.');
                return false;
            }

            confirmMessage("돌발상황 통계 차트를 파일로 저장 하시겠습니까?").done((yes)=>{
                if (yes){
                    incidentChart.exportChart({
                        filename:
                            typtSelect.option('value') +
                            ' - ' +
                            drngSelect.option('value') +
                            '(' +
                            dateFormmater(new Date(incidentChart.xAxis[0].categories[0])) +
                            ' - ' +
                            dateFormmater(new Date(incidentChart.xAxis[0].categories[incidentChart.xAxis[0].categories.length - 1])) +
                            ')_' +
                            excellTime(),
                    });
                }
            });
         
        },
    });

    //차트 변경 버튼
    $('.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);
                    incidentChart.update({
                        chart: {
                            type: item.type,
                        },
                    });
                }
            },
        })
        .dxMenu('instance');

    //가공데이터 차트
    incidentChart = Highcharts.chart('incident-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: '통계시각',
                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: '발생건수(량)',
            },
            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 = incidentChart;
    //상단 닫기 버튼
    $('.cancle-button')
        .dxButton({
            text: '닫기',
            icon: 'close',
            height: '30px',
            width: '80px',
            stylingMode: 'outlined',
            onClick() {
                window.close();
            },
        })
        .dxButton('instance');

    //돌발상황 통계 테이블
    incidentTable = $('.incident-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: ['stat_dt_fmt', 'incd_type_cd'],
            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: 'stat_dt_fmt',
                    caption: '통계시각',
                    alignment: 'center',
                    sortIndex: 0,
                    sortOrder: 'asc',
                },
                {
                    dataField: 'incd_type_cd',
                    caption: '돌발유형',
                    alignment: 'center',
                    lookup: {
                        dataSource: [
                            {
                                incd_type_cd: 1,
                                incd_type_cd_desc: '사고',
                            },
                            {
                                incd_type_cd: 2,
                                incd_type_cd_desc: '공사',
                            },
                            {
                                incd_type_cd: 3,
                                incd_type_cd_desc: '행사',
                            },
                            {
                                incd_type_cd: 4,
                                incd_type_cd_desc: '기상',
                            },
                        ],
                        displayExpr: 'incd_type_cd_desc',
                        valueExpr: 'incd_type_cd',
                    },
                },
                {
                    dataField    : 'link_id',
                    caption      : '구간 ID',
                    alignment    : 'center',
                    dataType     : 'string',
                    visible      : false,
                },
                {
                    dataField: 'f_name',
                    caption: '시점명',
                    alignment: 'center',
                    visible: false,
                    cellTemplate(c,e) {
                        alignTemplate(c, e, 'left');
                    }
                },
                {
                    dataField: 't_name',
                    caption: '종점명',
                    alignment: 'center',
                    visible: false,
                    cellTemplate(c, e) {
                        alignTemplate(c, e, 'left');
                    }
                },
                {
                    dataField    : 'incd_ocrr_num',
                    caption      : '돌발발생건수',
                    alignment    : 'center',
                    format       : "#,###,##0",
                },
                {
                    dataField    : 'ftlt_pnum',
                    caption      : '사망자수',
                    alignment    : 'center',
                    format       : "#,###,##0",
                },
                {
                    dataField    : 'injr_pnum',
                    caption      : '부상자수',
                    alignment    : 'center',
                    format       : "#,###,##0",
                },
                {
                    dataField    : 'prpr_dmge_amt',
                    caption      : '재산피해금액(백만원)',
                    alignment    : 'center',
                    format       : "#,###,##0",
                },
            ],
            onExporting(e) {
               gridExcellExporting(e, _pageName);
            },
        })
        .dxDataGrid('instance');
})


//구간별 데이터 세팅
function incidentEvent( front, end ) {
    let TO_DT      = null;
    let FROM_DT    = null;
    let updateData = {};
    let timeFormatLength = null;
    
    if ( !validationCheck( incidentStartDate, incidentEndDate )) return false;
    //조건 체크에 따른 시간 포맷
    switch (end) {
        case 'dd' :
            FROM_DT = dateFormmater(new Date(incidentStartDate.option('value')));
            TO_DT   = dateFormmater(new Date(incidentEndDate.option('value')));
            if (Number(FROM_DT) + 100 <= Number(TO_DT)) {
                return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, incidentEndDate);
            }
            timeFormatLength = 10;
            break;
        case 'mn' :
            FROM_DT = dateFormmater(new Date(incidentStartDate.option('value'))).substring(0, 6);
            TO_DT   = dateFormmater(new Date(incidentEndDate.option('value'))).substring(0, 6);
            timeFormatLength = 7;
            break;
        case 'yy' :
            FROM_DT = dateFormmater(new Date(incidentStartDate.option('value'))).substring(0, 4);
            TO_DT   = dateFormmater(new Date(incidentEndDate.option('value'))).substring(0, 4);
            timeFormatLength = 4;
            break;
        default:
            break;
    };
    
    
    if( FROM_DT > TO_DT ){
        alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, incidentStartDate);
        return false;
    };
   

    updateData[ 'FROM_DT' ] = FROM_DT;
    updateData[ 'TO_DT' ]   = TO_DT;

    finalEvent( commonUri + front + '/' + end, updateData, timeFormatLength );
}

//테이블 및 차트 세팅
function finalEvent( uri, updateData, timeFormatLength ){
    incidentData = [];
    xAxis        = [];
    //getData( uri, incidentData, updateData );
    getDataAsync(uri, (jsonData)=>{
        incidentData = jsonData;
        for (let obj of series) {
            obj.data = [];
        }
        let formatData = [];
        incidentData.map((item)=>{
            if (item.stat_dt && item.stat_dt.length >= 4) {
                item.stat_dt = getParseDateTime(item.stat_dt).substring(0, timeFormatLength);
            }
            if (item.incd_type_cd !== '소계'){
                formatData.push(item);
                xAxis.push(item.stat_dt);

                for (let ii = 0; ii < series.length; ii++) {
                    series[ii].data.push(Number(item[series[ii].id]));
                }
            }
        })
    
        incidentTable.option( 'dataSource', formatData );
        incidentTable.clearSelection();
        incidentTable.option('focusedRowIndex', -1);

        incidentChart.update({
            xAxis : {
                categories: xAxis
            },
            series : series,
            tooltip: {
                formatter: function () {
                    return this.x + '<br>'+this.series.name + " : " + this.y;
                }
            },
        });

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