let clctAnalysisData      = [];
let clctAnalysisStupData  = [];
let clctAnalysisTable     = null;
let clctAnalysisChart     = null;
let searchBtn             = null;
let clctAnalysisUri       = '/api/history/clct-analysis';
let strtDateBox           = null;
let strtTimeBox           = null;
let endDateBox            = null;
let endTimeBox            = null;
let textSearchBtn         = null;
let endDate               = new Date().setDate(new Date().getDate()-1);
let startDate             = new Date().setDate(new Date().getDate()-1);
let linkTable             = null;
let linkData              = [];
let columns               = [];
const _pageName           = '수집데이터 분석';
const _linkData           = _trafficMap.get('link');
const _linkFormatData     = [];

if(_linkData.length > 0){
    _linkData.map((item, idx)=>{
        _linkFormatData.push({...item});
        _linkFormatData[idx].list = item.link_id + " : " + item.from_node + " - > " + item.to_node;
    })
}

$(()=>{

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

    //검색시작일시 시간
    strtTimeBox = $(".strt-time").dxDateBox({
        type                : 'time',
        value               : 1645110000000,
        width               : '90px',
        height              : '25px',
        stylingMode         : 'outlined',
        displayFormat       : 'HH:mm',
        invalidDateMessage  : '형식에 맞게 입력해주세요. ex)00:00',
    }).dxDateBox("instance");

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

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


    //상단 조회 버튼
    searchBtn = $(".search-button").dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        width: '80px',
        onClick(){
            if (!validationCheck( strtDateBox, endDateBox, strtTimeBox, endTimeBox)) return false;
            let FROM_DT  = getDate(strtDateBox.option("value"),strtTimeBox.option("value"))
            let TO_DT    = getDate(endDateBox.option("value"),endTimeBox.option("value"))
            let idArr = "";

            if ( FROM_DT > TO_DT ) {
                alertWarning('검색 시작 시각이 검색 종료 시각보다 큽니다.', null, strtDateBox);
                return false;
            }
            if (Number(FROM_DT) + 100000000 <= Number(TO_DT)) {
                return alertWarning( '검색 기간을 1개월 이내로 입력해주세요.', null, endDateBox);
            }
            if (linkTable.getSelectedRowsData().length > 0){
                linkTable.getSelectedRowsData().map((item)=>{
                    idArr += item.link_id+",";
                })
                idArr = idArr.slice(0,-1)
            }
            else {
                alertWarning('링크 목록을 선택해 주세요.');
                return false;
            }

            let updateData = {
                FROM_DT : FROM_DT,
                TO_DT   : TO_DT,
                ids     : idArr,
            }

            clctAnalysisData = [];
            //getData('/api/history/clct-analysis', clctAnalysisData, updateData);
            getDataAsync('/api/history/clct-analysis', (jsonData)=>{
                clctAnalysisData = jsonData;
                if(clctAnalysisData.length > 0){
                    clctAnalysisData.map((item)=>{
                        if(item.prcn_dt)item.prcn_dt = new Date( getParseDateTime(item.prcn_dt) );
                    })
                }
                clctAnalysisTable.option('dataSource',clctAnalysisData);
                clctAnalysisTable.clearSelection();
                clctAnalysisTable.option('focusedRowIndex', -1);
                alertConfirm('데이터 조회가 완료되었습니다.['+clctAnalysisData.length+'건]')
            }, null, updateData);
        }
    }).dxButton("instance");


    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance");

    //링크 테이블
    linkTable = $(".link-table").width('100%').height('100%').dxDataGrid({
        dataSource              : _linkFormatData,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : 'link_id',
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode               : 'multiple',
            allowSelectAll     : false,
            showCheckBoxesMode :"onClick"
        },
        scrolling: {
            mode: 'virtual',
        },
        searchPanel: {
            visible: true,
        },
        grouping:{
            contextMenuEnabled : true,
        },
        columns:[
            {
                dataField:"road_name",
                caption:"도로명",
                sortIndex: 0,
                sortOrder: "asc",
                autoExpandGroup:false,
                groupIndex:0,
            },
            {
                dataField:"list",
                caption:"구간",
            }
        ],
        onContentReady(e){
            e.component.clearSelection();
            e.component.option('focusedRowIndex', -1);
        },
    }).dxDataGrid("instance");

    fetchBaseData();
})

function fetchBaseData(){
    getDataAsync("/api/history/clct-analysis/clct-syst-stup", recvColumnData);
}

function recvColumnData(jsonData) {
    clctAnalysisStupData = jsonData;
    columns.push(
        {
            dataField    : "road_name",
            caption      : "구간명",
            alignment    : "center",
            allowEditing : false,
            sortIndex    : 1,
            sortOrder    : "asc",
            cellTemplate(c,e) {
                c.css('text-align', 'left');
                c.text(e.displayValue);
            }
        },
        {
            dataField    : "link_id",
            caption      : "링크 ID",
            dataType     : 'string',
            alignment    : "center",
        },
        {
            dataField    : "from_node",
            caption      : "시점명",
            alignment    : "center",
            cellTemplate(c,e) {
                c.css('text-align', 'left');
                c.text(e.displayValue);
            }
        },
        {
            dataField    : "to_node",
            caption      : "종점명",
            alignment    : "center",
            cellTemplate(c,e) {
                c.css('text-align', 'left');
                c.text(e.displayValue);
            }
        },
        {
            dataField    : "prcn_dt",
            caption      : "가공 일시",
            dataType     : 'datetime',
            format       : 'yyyy-MM-dd HH:mm:ss',
            alignment    : "center",
            sortIndex    : 2,
            sortOrder    : "asc",
        },
    )

    if(clctAnalysisStupData.length > 0){
        for ( let ii = 0; ii < clctAnalysisStupData.length; ii++ ){
            columns.push({
                dataField    : clctAnalysisStupData[ii].clct_syst_cd,
                caption      : clctAnalysisStupData[ii].clct_syst_nm,
                alignment    : "center",
                format       : "#,###,##0",
            })
        }
    }
    makeTable();
}

function makeTable() {
    //수집데이터 분석 테이블
    clctAnalysisTable = $(".clct-analysis-table").width('100%').height('100%').dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        sorting                 : {
            showSortIndexes : false,
        },
        keyExpr                 : ['link_id', 'prcn_dt'],
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        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:"엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        columns : columns
    }).dxDataGrid("instance");
}