let _chart;
let _list;
let ixrNm;
let date;
let cmprDate;
let searchBtn;
const categories = ['A', 'B', 'C', 'D', 'E', 'F', 'FF'];
let xAxis = [];
for (let ii = 0; ii < 24; ii++) {
    xAxis.push(ii);
}
let _ixrUri = "/api/scrs/tb_sc_ixr_mngm";
let ixrData = [];

$(()=>{
    const closeBtn = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', 80, 30, false, true ); 
    closeBtn.onClick(()=>window.close());
    ixrNm = new dxSelect($('.cros-name'), 'outlined', 250, 30, 'ixr_nm', 'ixr_id', false, 'ixr_id', '교차로명');
    date = new dxDate($('.date'), 'yyyy-MM-dd', '일자', 120, 30, 'date', null, 'date');
    date.setValue(new Date());
    cmprDate = new dxDate($('.cmpr-date'), 'yyyy-MM-dd', '비교일자', 120, 30, 'date', null, 'cmpr_date');
    cmprDate.setValue(new Date());
    searchBtn = new dxBtn($('.search-btn'), '조회', 'refresh', 'outlined', 80, 32, false, true ); 
    drawChart();

    searchBtn.onClick(setChartData);
    _list = $('.list').width('100%').height('100%').dxDataGrid({
        dataSource : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        headerFilter: {
            visible: true,
        },
        selection  : {
            mode :'multiple',
            showCheckBoxesMode  : "onClick"
        },
        keyExpr : ['ixr_id', 'clct_dt'],
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:  [
            {
                caption   : "기본 정보",
                alignment : "center",
                columns : [
                    {
                        dataField : "ixr_nm",
                        caption   : '교차로명',
                        alignment : 'center',
                    },

                    {
                        dataField : "clct_dt",
                        caption   : '시간',
                        alignment : 'center',
                    },

                ]
            },
            {
                caption   : nowTime().substring(0,10),
                alignment : "center",
                columns : [
                    {
                        dataField : "base_tfvl",
                        caption   : '교통량(대)',
                        alignment : 'center',
                    },
                    {
                        dataField : "base_dely_hh",
                        caption   : '지체시간(초)',
                        alignment : 'center',
                    },
                    {
                        dataField : "base_srvc_lvl",
                        caption   : 'LOS',
                        alignment : 'center',
                    },
                ]
            },
            {
                caption   : nowTime().substring(0,10),
                alignment : "center",
                columns : [
                    {
                        dataField : "comp_tfvl",
                        caption   : '교통량(대)',
                        alignment : 'center',
                    },
                    {
                        dataField : "comp_dely_hh",
                        caption   : '지체시간(초)',
                        alignment : 'center',
                    },
                    {
                        dataField : "comp_srvc_lvl",
                        caption   : 'LOS',
                        alignment : 'center',
                    },
                ]
            },
        ],
    }).dxDataGrid('instance');

    getData(_ixrUri + '/list', ixrData);
    if (ixrData[0] && ixrData[0].length > 0) {
        dataSorting(ixrData[0], 'ixr_id');
        ixrNm.setValue(ixrData[0][0].ixr_id);
    }
    ixrNm.setDataSource(ixrData[0]);
})

function drawChart(){
    _chart  = Highcharts.chart('chart', {
        chart: {
            zoomType: 'xy',
            height : 300,
            backgroundColor: {
                classNmae: 'dx-theme-background-color dx-theme-border-color',
                marginBottom: 100,
            },
        },
        title: {
          text: '',
        },
        xAxis: [{
              categories: xAxis,
              crosshair: true,
              labels: {
                style: {
                  color:  $('.dx-theme-material-typography').css('color')
                }
              },
        }],
        yAxis: [{ // Primary yAxis
            labels: {
                style: {
                color:  $('.dx-theme-material-typography').css('color')
                }
            },
            title: {
                text: '교통량(대)',
                style: {
                color:  $('.dx-theme-material-typography').css('color')
                }
            }
        }, 
        { // Secondary yAxis
            title: {
                text: '서비스수준(LOS)',
                style: {
                color:  $('.dx-theme-material-typography').css('color'),
                }
            },
            labels: {
                style: {
                color:  $('.dx-theme-material-typography').css('color'),
                },
            },
            categories : categories,
            opposite: true,
        }],
        tooltip: {
            shared: true
        },
        legend: {
            align: 'center',
            verticalAlign: 'bottom',
            itemStyle:{
                color: $('.dx-theme-material-typography').css('color'),
            },
            backgroundColor: {
                className : 'dx-nav-item dx-theme-border-color',
            }
        },
        series: [
            {
                name: '교통량',
                type: 'column',
                yAxis: 0,
                data: [],
                color: 'gray',
                maxPointWidth: 100,
            }, 
            {
                name: '교통량',
                type: 'column',
                sub : '비교',
                yAxis: 0,
                data: [],
                maxPointWidth: 100,
            }, 
            {
                name: '서비스수준 ( LOS )',
                type: 'line',
                yAxis: 1,
                data: [],
                color : 'green',
            },
            {
                name: '서비스수준 ( LOS )',
                type: 'line',
                yAxis: 1,
                data: [],
                color : 'orange',
            }
        ],
        exporting: {
            enabled: false,
        },
        credits: {
            enabled: false
        },
        tooltip: {
            formatter: function () {
                let name = this.series.name;
                let dt = name.substring(0,name.indexOf('('));
                if (this.series.name.indexOf('( LOS )') > -1) {
                    let rank = this.series.yAxis.categories[this.y];
                    if (this.y >= 0){
                        return '<b>패턴정보조회</b><br>'
                            + '일시 : <b>' 
                            + dt 
                            + ' '
                            + this.x 
                            + ':00</b><br>'
                            + '서비스수준(LOS) : <b>' 
                            + rank
                            + '</b>';
                    }
                }
                else  {
                    return '<b>패턴정보조회</b><br>'
                        + '일시 : <b>'
                        + dt 
                        + ' '
                        + this.x 
                        + ':00</b><br>'
                        + '교통량 : <b>'
                        + this.y
                        + ' 대</b>';
                }
            }
          }
      });
      window.$chart = _chart;
}

function setChartData(){
    if (ixrNm.isNull()) {
        return alertWarning(ixrNm.label + "을 선택 해주세요.", null, ixrNm);
    }
    const dateArr = [date, cmprDate];
    for (let input of dateArr) {
        if (input.isValidation()) {
            return alertWarning("날짜 형식에 맞게 입력해주세요.", null, input);
        }
        else if (input.isNull()) {
            return alertWarning( input.label + "를 입력해주세요.", null, input);
        }
    }
    const ixrIdVal  = ixrNm.getValue();
    const dateVal   = date.getSendDateValue().substring(0,8);
    const cmprDtVal = cmprDate.getSendDateValue().substring(0,8);
    const updateData = {
        ixr_id : ixrIdVal,
        COMP_DT : cmprDtVal,
        BASE_DT : dateVal,
    }
    let yAxis1 = [];
    let yAxis2 = [];
    let yAxis3 = [];
    let yAxis4 = [];
    // let data = [
    //     {
    //         ixr_id    : '10001',
    //         ixr_nm    : '평택 사거리',
    //         base_tfvl : 24,
    //         comp_tfvl : 58,
    //         base_srvc_lvl : 1,
    //         comp_srvc_lvl : 0,
    //         clct_dt : '20221212000000',
    //     },
    //     {
    //         ixr_id    : '10001',
    //         ixr_nm    : '평택 사거리',
    //         base_tfvl : 39,
    //         comp_tfvl : 24,
    //         base_srvc_lvl : 2,
    //         comp_srvc_lvl : 3,
    //         clct_dt : '20221212000010',
    //     },
    //     {
    //         ixr_id    : '10001',
    //         ixr_nm    : '평택 사거리',
    //         base_tfvl : 12,
    //         comp_tfvl : 8,
    //         base_srvc_lvl : 4,
    //         comp_srvc_lvl : 2,
    //         clct_dt : '20221212000020',
    //     },
    // ]
    // data.map((item)=>{
    //     item.clct_dt = getParseDateTime(item.clct_dt);
    //     xAxis.push(item.clct_dt);
    //     yAxis1.push(item.base_tfvl);
    //     yAxis2.push(item.comp_tfvl);
    //     yAxis3.push(item.base_srvc_lvl);
    //     yAxis4.push(item.comp_srvc_lvl);
    // });
    // _list.option( 'dataSource', data );
    let currentDt = getParseDate(dateFormmater(date.nowVal()));
    let cmprDt    = getParseDate(dateFormmater(cmprDate.nowVal()));
    _list.option('columns[1].caption',currentDt);
    _list.option('columns[2].caption',cmprDt);
    getDataAsync('', (jsonData)=>{
        if ( jsonData ) {
            jsonData.map((item)=>{
                if(nullChecker(item.clct_dt) !== ""){
                    item.clct_dt = getParseDateTime(clct_dt)
                    xAxis.push(item.clct_dt);
                    yAxis1.push(item.base_tfvl);
                    yAxis2.push(item.comp_tfvl);
                    yAxis3.push(item.base_srvc_lvl);
                    yAxis4.push(item.comp_srvc_lvl);
                }
            })
        }

        _list.option( 'dataSource', jsonData );
        _chart.update({
            series: [
                {
                    name: currentDt + ' ( 교통량 )',
                    data: yAxis1
                },
                {
                    name: cmprDt + ' ( 교통량 )',
                    data: yAxis2
                },
                {
                    name : currentDt + ' ( LOS )',
                    data: yAxis3
                },
                {
                    name : cmprDt + ' ( LOS )',
                    data: yAxis4
                },
            ]
        })
    }, null, updateData);
    
    // _chart.update({
    //     series: [
    //         {
    //             name: currentDt + ' ( 교통량 )',
    //             data: yAxis1
    //         },
    //         {
    //             name: cmprDt + ' ( 교통량 )',
    //             data: yAxis2
    //         },
    //         {
    //             name : currentDt + ' ( LOS )',
    //             data: yAxis3
    //         },
    //         {
    //             name : cmprDt + ' ( LOS )',
    //             data: yAxis4
    //         },
    //     ]
    // })
}