//input, btn 관련
let ifscId          = null;
let dayTypeCd       = null;
let cnfsStrtHm      = null;
let cnfsEndHm       = null;
let avrgSped        = null;
let avrgTrvlHh      = null;
let selLinkBtn      = null;
let unCnfmSelBtn    = null;
let unCnfmCaclBtn   = null;
let mngrBtn         = null;
let cnfmCnclBtn     = null;
let sectCnfmBtn     = null;
//테이블, uri, data
let commonUri          = '/api/manage/rept-cngs/sect';
let cdData             = [];
let sectCnfmTable      = null;
let sectCnfmData       = [];
let sectUnCnfmData     = [];
let sectUnCnfmTable    = null;

//pop-up

const listOption = 'width = 800, height = 900, top = 40, left = 500, resizable=yes, scrollbars=no';
const mapOption = 'width = 1700, height = 900, top = 40, left = 100, resizable=yes, scrollbars=no';
const _multiSelct    = false;
const _linkLevel     = 2;
const getParam = {
    MultiSelect: _multiSelct,
    LinkLevel: _linkLevel,
    LinkInfo    : [],
};

//운영자 등록 input
const newInputArr = [
    //서비스링크 ID
    ifscId = {
        box             : null,
        type            : 'text',
        column          : 'ifsc_id',
        max             : 10,
        width           : 120,
        alert           : '정보제공구간 ID',
    },
    //요일
    dayTypeCd = {
        box             : null,
        type            : 'select',
        column          : 'day_type_cd',
        displayExpr     : 'day_type_desc',
        width           : 140,
        alert           : '요일',
    },
    //혼잡 시작 시분
    cnfsStrtHm = {
        box             : null,
        type            : 'time',
        column          : 'cnfs_strt_hm',
        width           : 120,
        displayFormat   : 'HH시 mm분',
        value           : 1668139200000,
        interval        : 10,
        alert           : '혼잡 시작시분',
    },
    //혼잡 종료 시분
    cnfsEndHm = {
        box             : null,
        type            : 'time',
        column          : 'cnfs_end_hm',
        width           : 120,
        displayFormat  : 'HH시 mm분',
        value           : 1668142800000,
        interval        : 10,
        alert           : '혼잡 종료시분',
    },
    //평균 속도
    avrgSped = {
        box             : null,
        type            : 'number',
        column          : 'avrg_sped',
        max             : 999,
        width           : 90,
        alert           : '평균 속도',
    },
    //평균 통행시간(분)
    avrgTrvlHh = {
        box             : null,
        type            : 'number',
        column          : 'avrg_trvl_hh',
        max             : 999999,
        width           : 95,
        alert           : '평균 통행시간(분)',
    },
    //서비스 링크 구간 찾기 버튼
    selLinkBtn = {
        box             : null,
        type            : 'button',
        column          : 'sel-link-btn',
        text            : '제공 구간 선택',
        height          : 30,
        icon            : 'check',
        method          : function(){
            event.stopPropagation();
            let x = event.clientX - 5;
            let y = event.clientY - 60;
            $(".add-select-btn").css('display','flex');
            $(".add-select-btn").css('position','absolute');
            $(".add-select-btn").css('left',x);
            $(".add-select-btn").css('top',y);
        }
    },
    //확정하기 버튼
    unCnfmSelBtn = {
        box             : null,
        type            : 'button',
        column          : 'un-cnfm-sel-btn',
        text            : '확정하기',
        icon            : 'check',
        method          : function(){
            const selectedData = sectUnCnfmTable.getSelectedRowsData();

            if(selectedData.length <= 0) return alertWarning('선택된 예상 반복정체 구간이 없습니다.');

            let updateData = [];

            selectedData.map((item)=>{
                updateData.push({
                    cnfs_strt_hm : getSendDate(item.cnfs_strt_hm).substring(8, 12),
                    day_type_cd  : item.day_type_cd,
                    ifsc_id      : item.ifsc_id,
                    stat_ym      : getSendDate(item.stat_ym).substring(0, 6),
                });
            });
            

            confirmMessage('예상 반복정체 구간 정보를 확정 처리 하시겠습니까?').done((yes) => {
                if (yes === true) {
                    let result = putUpdate( commonUri + '/cnfm', updateData);

                    if(result > 0) {
                        alertConfirm('예상 반복정체 구간 정보가 확정 처리 되었습니다.')

                        getDataAsync(commonUri + '/un-cnfm', (jsonData) => fetchListData(jsonData, sectUnCnfmTable));
                    }

                }
            });
        }
    },
    //예상취소 버튼
    unCnfmCaclBtn = {
        box             : null,
        type            : 'button',
        column          : 'un-cnfm-cacl-btn',
        text            : '예상취소',
        icon            : 'close',
        method          : function(){
            cancleEvent(sectUnCnfmTable, sectUnCnfmData, '예상', '/cancel-pred', '/un-cnfm');
        }
    },
    //구간 등록 버튼
    sectCnfmBtn = {
        box             : null,
        type            : 'button',
        column          : 'sect-cnfm-btn',
        text            : '구간등록',
        icon            : 'check',
        method          : function(){
            let updateData      = []
            const ifscIdVal     =  getValue(ifscId.box);
            const dayTypeCdVal  =  getValue(dayTypeCd.box);
            const cnfsStrtHmVal =  getSendDate(new Date(new Date().setTime(getValue(cnfsStrtHm.box)))).substring(8,12);
            const cnfsEndHmVal  =  getSendDate(new Date(new Date().setTime(getValue(cnfsEndHm.box)))).substring(8,12);
            const avrgSpedVal   =  getValue(avrgSped.box);
            const avrgTrvlHhVal =  getValue(avrgTrvlHh.box);

            for(idx in newInputArr){
                const array = newInputArr[idx];
                if(array.type !== 'button' && nullChecker(getValue(array.box)) === ""){
                    alertWarning("입력되지 않은 항목이 있습니다. [" + array.alert + "]", null, array.box);
                    return false;
                }
            }

            if(cnfsStrtHmVal > cnfsEndHmVal) {
                cnfsStrtHm.box.focus();
                return alertWarning('혼잡 시작시분이 혼잡 종료시분 보다 큽니다.');
            }

            updateData.push({
                avrg_sped : avrgSpedVal  ,
                avrg_trvl_hh : avrgTrvlHhVal,
                cnfs_end_hm : cnfsEndHmVal ,
                cnfs_strt_hm : cnfsStrtHmVal,
                day_type_cd : dayTypeCdVal ,
                ifsc_id : ifscIdVal,
            });

            confirmMessage('반복 정체 구간 정보를 확정하시겠습니까?').done((yes)=>{
                if (yes) {
                    const result = postInsertUpdate(commonUri, updateData);

                    if (result > 0) {
                        alertConfirm('반복정체 구간 정보가 확정 처리 되었습니다.');

                        sectCnfmData = [];

                        getDataAsync(commonUri + '/cnfm', (jsonData)=>fetchListData(jsonData, sectCnfmTable));

                        $('.scnd-box').toggleClass('sect-toggle');
                        $('.hidden-sect').toggleClass('dpl-none');
                        inputInit();
                    }
                }
            })
        }
    },
    //운영자 등록 버튼
    mngrBtn = {
        box             : null,
        type            : 'button',
        column          : 'mngr-btn',
        text            : '운영자 등록',
        icon            : 'edit',
        method: function(){
            $('.scnd-box').toggleClass('sect-toggle');
            $('.hidden-sect').toggleClass('dpl-none');
            inputInit();
        }
    },
    //확정 취소 버튼
    cnfmCnclBtn = {
        box             : null,
        type            : 'button',
        column          : 'cnfm-cncl-btn',
        text            : '확정취소',
        icon            : 'close',
        method          : function(){
            sectCnfmData = cancleEvent(sectCnfmTable, sectCnfmData, '확정' ,'/cancel-cnfm', '/cnfm');
        }
    },
]


$(()=>{
    $('body').on('click', function(){
        $(".add-select-btn").css('display', 'none');
    })

    //추가 버튼 목록에서 선택
    $(".add-select-btn > div:nth-child(1)").on('click', function(){
        event.stopPropagation();
        event.preventDefault();
        window.open('./rept-cngs-popup-link.html','목록 구간', listOption);
        $(".add-select-btn").css('display', 'none');
    });

    //추가 버튼 맵에서 선택
    $(".add-select-btn > div:nth-child(2)").on('click', function(){
        event.stopPropagation();
        event.preventDefault();
        window.open('./rept-cngs-popup-map.html','지도 구간', mapOption);
        $(".add-select-btn").css('display', 'none');
    });
    hoverClass('.add-select-btn div');

    $(".search-btn").dxButton({
        stylingMode : 'outlined',
        text        : '조회',
        icon        : 'refresh',
        onClick(){
            fetchBaseData();
        }
    }).dxButton('instance');

    $(".close-btn").dxButton({
        stylingMode:'outlined',
        text:'닫기',
        icon:'close',
        onClick(){
            window.close();
        }
    }).dxButton('instance');

    inputInit();

    sectUnCnfmTable    = $('.sect-un-cnfm-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        noDataText              : '표출할 정보가 없습니다.',
        columnAutoWidth         : true,
        selection: {
            mode: 'single',
        },
        paging:{
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible: true,
        },
        grouping: {
            autoExpandAll: true,
        },
        groupPanel:{
            visible: true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        columns:[
            {
                dataField : "ifsc_id",
                caption   : "정보제공구간 ID",
                dataType  : 'string',
                alignment : "center",
            },
            {
                dataField : "ifsc_nm",
                caption   : "명칭",
                alignment : "center",
                cellTemplate(c,e){
                    return alignTemplate(c, e, 'left');
                }
            },
            // {
            //     dataField : "incd_orgn_desc",
            //     caption   : "방향",
            //     alignment : "center",
            // },
            {
                dataField : "strt_nm",
                caption   : "시정명",
                alignment : "center",
                cellTemplate(c,e){
                    return alignTemplate(c, e, 'left');
                }
            },
            {
                dataField : "end_nm",
                caption   : "종점명",
                alignment : "center",
                cellTemplate(c,e){
                    return alignTemplate(c, e, 'left');
                }
            },
            {
                dataField : "stat_ym",
                caption   : "통계 년월",
                alignment : "center",
                dataType  : "date",
                format    : "yyyy년 MM월"
            },
            {
                dataField : "day_type_desc",
                caption   : "요일",
                alignment : "center",
            },
            {
                dataField : "cnfs_strt_hm",
                caption   : "혼잡 시작시분",
                alignment : "center",
                dataType  : "time",
                format    : "HH:mm"
            },
            {
                dataField : "cnfs_end_hm",
                caption   : "혼잡 종료시분",
                alignment : "center",
                dataType  : "time",
                format    : "HH:mm"
            },
            {
                dataField : "avrg_sped",
                caption   : "평균속도",
                alignment : "center",
            },
            {
                dataField : "avrg_trvl_hh",
                caption   : "평균 통행시간(초)",
                alignment : "center",
                format    : "#,##0",
            },
            {
                dataField : "dcsn_yn",
                caption   : "확정 여부",
                alignment : "center",
            },
            {
                dataField : "crtn_ymd",
                caption   : "생성 일자",
                alignment : "center",
                dataType  : "date",
                format    : "yyyy-MM-dd"
            },
            // {
            //     dataField : "incd_strt_dt",
            //     caption   : "생성자",
            //     alignment : "center",
            // },
        ]
    }).dxDataGrid('instance');

    sectCnfmTable = $('.sect-cnfm-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        paging:{
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible: true,
        },
        grouping: {
            autoExpandAll: true,
        },
        groupPanel:{
            visible: true,
            emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        columns:[
            {
                dataField : "ifsc_id",
                caption   : "정보제공구간 ID",
                dataType  : 'string',
                alignment : "center",
            },
            {
                dataField : "ifsc_nm",
                caption   : "명칭",
                alignment : "center",
                cellTemplate(c,e){
                    c.css('text-align','left');
                    c.text(e.displayValue)
                }
            },
            // {
            //     dataField : "incd_orgn_desc",
            //     caption   : "방향",
            //     alignment : "center",
            // },
            {
                dataField : "strt_nm",
                caption   : "시정명",
                alignment : "center",
            },
            {
                dataField : "end_nm",
                caption   : "종점명",
                alignment : "center",
            },
            {
                dataField : "stat_ym",
                caption   : "통계 년월",
                alignment : "center",
                dataType  : "date",
                format    : "yyyy-MM"
            },
            {
                dataField : "day_type_desc",
                caption   : "요일",
                alignment : "center",
            },
            {
                dataField : "cnfs_strt_hm",
                caption   : "혼잡 시작시분",
                alignment : "center",
                dataType  : "datetime",
                format    : "HH:mm"
            },
            {
                dataField : "cnfs_end_hm",
                caption   : "혼잡 종료시분",
                alignment : "center",
                dataType  : "datetime",
                format    : "HH:mm"
            },
            {
                dataField : "avrg_sped",
                caption   : "평균속도",
                alignment : "center",
            },
            {
                dataField : "avrg_trvl_hh",
                caption   : "평균 통행시간(초)",
                alignment : "center",
            },
            {
                dataField : "dcsn_yn",
                caption   : "확정 여부",
                alignment : "center",
            },
            {
                dataField : "crtn_ymd",
                caption   : "생성 일자",
                alignment : "center",
                dataType  : "date",
                format    : "yyyy-MM-dd"
            },
            // {
            //     dataField : "incd_strt_dt",
            //     caption   : "생성자",
            //     alignment : "center",
            // },
        ]
    }).dxDataGrid('instance');

    fetchBaseData();
    fetchCodeData();
})

function fetchBaseData(){
    //반복 정체 구간 전체 조회 - 현재 미확정 데이터 수신
    getDataAsync(commonUri + '/un-cnfm', (jsonData) => fetchListData(jsonData, sectUnCnfmTable));

    //반복 정체 구간 전체 조회 - 현재 확정 데이터 수신
    getDataAsync(commonUri + '/cnfm', (jsonData) => fetchListData(jsonData, sectCnfmTable));
}

function fetchCodeData(){
    //날짜 유형 데이터 수신
    getDataAsync('/api/analysis/ptrn-data/day-type', (jsonData)=>{
        cdData = jsonData;
        dayTypeCd.box.option('dataSource', cdData);
        if (cdData.length > 0) {
            setValue(dayTypeCd.box, cdData[0].day_type_cd);
        }
    });
}

function fetchListData(jsonData, table){
    dataSorting(jsonData, 'ifsc_id');
    let listData = jsonData;
    if (listData.length > 0) {
        listData = dataFormmat(listData);
    }
    table.option('dataSource', listData);
}

function inputInit(){
    newInputArr.map((item)=>{
        switch (item.type) {
            case 'text':
                item.box = $("." + item.column).dxTextBox({
                    width       : item.width,
                    height      : 30,
                    stylingMode : 'outlined',
                    readOnly    : item.readOnly,
                    value       : item.value,
                    maxLength   : item.max,
                    placeholder : item.placeholder,
                }).dxTextBox('instance');
                break;
            case 'time':
                item.box = $("." + item.column).dxDateBox({
                    width                 : item.width,
                    stylingMode           : 'outlined',
                    height                : 30,
                    type                  : item.type,
                    readOnly              : item.readOnly,
                    interval              : item.interval,
                    displayFormat         : item.displayFormat,
                    value                 : item.value,
                    invalidDateMessage    : '형식에 맞게 입력해주세요. ex)OO시 OO분'
                }).dxDateBox('instance');
                break;
            case 'select':
                item.box = $("." + item.column).dxSelectBox({
                    width          : item.width,
                    stylingMode    : 'outlined',
                    height         : 30,
                    displayExpr    : item.displayExpr,
                    valueExpr      : item.column,
                }).dxSelectBox('instance');
                break;
            case 'number':
                item.box = $("." + item.column).dxNumberBox({
                    stylingMode     : 'outlined',
                    showSpinButtons : true,
                    width           : item.width,
                    height          : 30,
                    mode            : 'text',
                    max             : item.max,
                    min             : 0,
                }).dxNumberBox('instance');
                item.box.on('valueChanged',(e)=>{
                    if(e.value === null){
                        setValue(e.component, '0');
                    }
                })
                break;
            case 'check':
                item.box = $("." + item.column).dxCheckBox({
                    stylingMode     : 'outlined',
                    text            : item.text,
                }).dxCheckBox('instance');
                break;
            case 'button':
                item.box = $("." + item.column).dxButton({
                    stylingMode : 'outlined',
                    height      : 31,
                    text        : item.text,
                    icon        : item.icon,
                    onClick(){
                        item.method();
                    }
                })
                break;
            default:
                break;
        }
    })



}

function dataFormmat(data){
    data.map((item)=>{
        if(item.crtn_ymd)item.crtn_ymd = new Date(getParseDate(item.crtn_ymd));
        if(item.stat_ym)item.stat_ym = new Date(getParseMonth(item.stat_ym));
        if(item.cnfs_strt_hm)item.cnfs_strt_hm = new Date(nowTime().substring(0,11) + item.cnfs_strt_hm.substring(0,2) + ':'+ item.cnfs_strt_hm.substring(2,4) + ':' +'00');
        if(item.cnfs_end_hm)item.cnfs_end_hm = new Date(nowTime().substring(0,11) + item.cnfs_end_hm.substring(0,2) + ':'+ item.cnfs_end_hm.substring(2,4) + ':' +'00');
    })
    return data;
}

function cancleEvent(table, data, msg, uri, tbUri){

    const selectedData = table.getSelectedRowsData();
    if(selectedData.length <= 0) return alertWarning('선택된 ' + msg + ' 반복정체 구간이 없습니다.');

    let delData = [];
    selectedData.map((item)=>{
        delData.push({
            cnfs_strt_hm : getSendDate(item.cnfs_strt_hm).substring(8, 12),
            day_type_cd  : item.day_type_cd,
            ifsc_id      : item.ifsc_id,
            stat_ym      : getSendDate(item.stat_ym).substring(0, 6),
        })
    })
    confirmMessage(msg + ' 반복정체 구간 정보를 삭제 하시겠습니까?').done((yes)=>{
        if (yes) {
            let result = deleteDataIds( commonUri + uri, delData);

            if (result > 0) {

                delResultMsg(msg + ' 반복정체 구간');

                getDataAsync(commonUri + tbUri, (jsonData) => fetchListData(jsonData, table));
            }
        }
    })


}

function getParams(){
    const id = getValue(ifscId.box)
    getParam.LinkInfo = [];
    if(id){
        getParam.LinkInfo.push({
            link_color : 1,
            id : id,
        });
    }
    return getParam;
}

function inserLinkText(popupData){
    setValue(ifscId.box, popupData[0].id);
}

function getIfscData(){
    return _trafficMap.get('ifsc');
}

function getTrafficMap(){
    return _trafficMap;
}