let updateData      = [];
let _listTable      = null;
const _pageName     = '교차로교통량 통계';
const _apiUri       = '/api/database/cmtr-grad-clsf';
let _searchBtn      = null;
let _strtDt         = null;
let _endDt          = null;
let _strtTime       = null;
let _endTime        = null;
let _chart          = null;
let series          = null;
let typeData        = null;
let _type           = null;
series = [
    {
        id   : 'strt',
        name : '직진',
        color: 'rgb(124, 181, 236)',
        data : [],
    },
    {
        id   : 'left',
        name : '좌회전',
        color: 'rgb(255,128,128)',
        data : [],
    },
    {
        id   : 'right',
        name : '우회전',
        color: 'rgb(128,255,128)',
        data : [],
    },
    {
        id   : 'uturn',
        name : '유턴',
        color: 'rgb(247, 163, 92)',
        data : [],
    },
]
typeData = [
    {
        type_cd   : '5m',
        type_desc : '5 분',
    },
    {
        type_cd   : '15m',
        type_desc : '15 분',
    },
    {
        type_cd   : '30m',
        type_desc : '30 분',
    },
    {
        type_cd   : 'hh',
        type_desc : '1 시간',
    },
    {
        type_cd   : 'dd',
        type_desc : '일',
    },
]
$(()=>{

    //교차로 교통량 테이블
    _listTable = $(".list-table").width('100%').height('100%').dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : ['cmtr_grad_cd','sect_grad_desc'],
        focusedRowEnabled       : true,
        scrolling: {
            mode: "standard",
        },
        paging: {
            enabled: true,
            pageSize: 1000,
        },
        selection: {
            mode: 'single',
        },
        headerFilter: {
            visible: true,
        },
        grouping: {
            autoExpandAll: true,
            contextMenuEnabled : true,
        },
        groupPanel:{
            visible: false,
            allowColumnDragging : true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요",
        },
        export:{
            enabled: true,
            texts: {
                exportAll:"엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        columns:[
            {
                caption   : "교차로 정보",
                alignment : 'center',
                columns : [
                    {
                        dataField    : "cros_nmbr",
                        caption      : "No",
                        alignment    : "center",
                        allowEditing : false,
                    },
                    {
                        dataField    : "cros_nm",
                        caption      : "교차로",
                        alignment    : "center",
                        allowEditing : false,
                    },
                    {
                        dataField    : "camera",
                        caption      : "카메라",
                        alignment    : "center",
                        allowEditing : false,
                    },
                ]
            },
            {
                caption   : "수집",
                alignment : "center",
                columns   : [
                    {
                        dataField    : "clct_dt",
                        caption      : "수집시각",
                        alignment    : "center",
                        allowEditing : false,
                    },
                    {
                        dataField     : "lane",
                        caption       : "차선",
                        alignment     : "center",
                        visible       : false,
                    },
                    {
                        dataField     : "trvl",
                        caption       : "교통량",
                        alignment     : "center",
                    },
                    {
                        dataField     : "strt",
                        caption       : "직진",
                        alignment     : "center",
                    },
                    {
                        dataField     : "left",
                        caption       : "좌회전",
                        alignment     : "center",
                    },
                    {
                        dataField     : "right",
                        caption       : "우회전",
                        alignment     : "center",
                    },
                    {
                        dataField     : "uturn",
                        caption       : "유턴",
                        alignment     : "center",
                    },
                ],
            },
            {
                caption   : "직진",
                alignment : "center",
                columns   : [
                    {
                        dataField    : "strt.small",
                        caption      : "소형",
                        alignment    : "center",
                        allowEditing : false,
                    },
                    {
                        dataField     : "strt.big",
                        caption       : "대형",
                        alignment     : "center",
                    },
                    {
                        dataField     : "strt.bus",
                        caption       : "버스",
                        alignment     : "center",
                    },
                ],
            },
            {
                caption   : "좌회전",
                alignment : "center",
                columns   : [
                    {
                        dataField    : "left.small",
                        caption      : "소형",
                        alignment    : "center",
                        allowEditing : false,
                    },
                    {
                        dataField     : "left.big",
                        caption       : "대형",
                        alignment     : "center",
                    },
                    {
                        dataField     : "left.bus",
                        caption       : "버스",
                        alignment     : "center",
                    },
                ],
            },
            {
                caption   : "우회전",
                alignment : "center",
                columns   : [
                    {
                        dataField    : "right.small",
                        caption      : "소형",
                        alignment    : "center",
                        allowEditing : false,
                    },
                    {
                        dataField     : "right.big",
                        caption       : "대형",
                        alignment     : "center",
                    },
                    {
                        dataField     : "right.bus",
                        caption       : "버스",
                        alignment     : "center",
                    },
                ],
            },
            {
                caption   : "유턴",
                alignment : "center",
                columns   : [
                    {
                        dataField    : "uturn.small",
                        caption      : "소형",
                        alignment    : "center",
                        allowEditing : false,
                    },
                    {
                        dataField     : "uturn.big",
                        caption       : "대형",
                        alignment     : "center",
                    },
                    {
                        dataField     : "uturn.bus",
                        caption       : "버스",
                        alignment     : "center",
                    },
                ],
            },
        ],
        onRowClick(e){
        },
        onRowDblClick(e){
        },
        onRowUpdated(e){
            updateData.push(e.data);
        }

    }).dxDataGrid("instance");

    //차트 유형 변경 메뉴
    $(".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);
                _chart.update({
                    chart: {
                        type: item.type,
                    }
                })
            }
        }
    }).dxMenu("instance");

    //닫기 버튼
    const coloseBtn = new dxBtn($(".close-button"), '닫기', 'close', 'outlined', 80, 30, false, true);
    coloseBtn.onClick(()=>window.close());
    
    //구분
    _type = new dxSelect($('.type'), 'outlined', 100, 28, 'type_desc', 'type_cd' , false);
    _type.setDataSource(typeData);
    _type.setValue('5m');
    //교차로
    new dxSelect($('.cross-id'), 'outlined', 200, 28, '', '' , false);
    new dxSelect($('.cross-nm'), 'outlined', 250, 28, '', '' , false);
    new dxSelect($('.camera'), 'outlined', 250, 28, '', '' , false);
    
    //조회 버튼
    new dxBtn($('.search-button'), '조회', 'refresh', 'outlined', null, null, false, true);
    
    //검색 기간
    _strtDt   = new dxDate($('.strt-dt'), 'yyyy년 MM월 dd일', '검색기간 시작 년월일', 150, 30, 'datetime', null);
    _strtDt.setValue(getBefAftDay(-1));
    _endDt    = new dxDate($('.end-dt'), 'yyyy년 MM월 dd일', '검색기간 종료 년월일', 150, 30, 'datetime', null);
    _endDt.setValue(new Date());
    _strtTime = new dxNumber($('.strt-time'), 'outlined', 80, 30, 1, 59, true, new Date().getHours(), 'strt-time', '00', false);
    _endTime  = new dxNumber($('.end-time'), 'outlined', 80, 30, 1, 59, true, new Date().getHours(), 'end-time', '00', false);
    
    //차로별 체크
    new dxCheck($('.lane'), '차로별', false, false, null);
    
    //차트 이미지 저장 버튼
    const exportBtn = new dxBtn($(".export-button"), '차트 저장', 'export', 'outlined', 110, 40, false, true);
    exportBtn.onClick(chartDownImage);

    //차트
    _chart = Highcharts.chart('chart', {
        chart: {
            type: 'line',
            backgroundColor: {
                classNmae: 'dx-theme-background-color dx-theme-border-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: {
                text :'교통량',
                style:{
                    color: $('.dx-theme-material-typography').css('color'),
                }
            },
            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 = _chart;
    sectionResize( $('.n-resize'), $('.bottom-sect'), $('.chart-container'), $('.list-box'), ()=>{
        _listTable.refresh();
        _chart.reflow();
    });
    //fetchListData();
})

function chartDownImage(){
    const data = _listTable.option('dataSource');
    if ( data.length <= 0 || data[0].length <= 0 ) {
            alertWarning("저장하실 차트 데이터가 없습니다.");
            return false;
    }
    confirmMessage("소통 정보 통계 차트를 파일로 저장 하시겠습니까?").done((yes)=>{
        if (yes){
            _chart.exportChart({
                filename: '교차로 교통량 통계 ( ' + filename + ' ) ' + excellTime()
            });
        }
    })
}
//소통등급 리스트 정보 수신
function fetchListData(){
    getDataAsync(_apiUri, (jsonData)=>{_listTable.option('dataSource', jsonData)});
}


//마우스 드래그 리사이즈 함수
function sectionResize(position, parent, position1, position2, callBackFunc) {
    const dragBorder = position;
    dragBorder.on('mousedown', function(event){
        let clientY = event.clientY;
        dragBorder.on("dragstart", function(event){
            const dropPosition = parent;
            let whVal1 = position1.height();
            
            dropPosition.on('dragover', function(event){
                event.preventDefault();
            })
            
            dropPosition.on('drop',function(event){
                event.preventDefault();
                let moveVal = null;
                let position1Val = null;
                moveVal = event.clientY - clientY;
                position1Val = whVal1 - moveVal;
                position1.css('height', position1Val + 'px');
                position2.css('height', 'calc(100% - '+ (position1Val + 11) + 'px)');
                dragBorder.off('dragstart');
                dropPosition.off('dragover');
                dropPosition.off('drop');
                if (callBackFunc) {
                    callBackFunc();
                }
            })
        });
    })

    dragBorder.on('dblclick',()=>{
        const firstVal1 = 346;
        position1.css('height', firstVal1);
        position2.css('height', 'calc(100% - 357px)');
        if (callBackFunc) {
            callBackFunc();
        }
    })
}