"use strict";
let ifscData       = [];
let ifscMakeUpData = [];
let ifscTable      = null;
const _apiUri      = "/api/database/ifsc";
const _pageName    = '정보제공구간 정보';
let _selectedIfsc  = null;

$(()=>{
    $("body").append(modalDiv);
    $(".modal-title").prepend($("<div>정보제공구간 정보 수정</div>"));
    $(".modal-background").css("display",'none');
    //편집 버튼
    $(".edit-btn").dxButton({
        text:'수정',
        icon:'edit',
        stylingMode:'outlined',
        onClick(){
            if (ifscTable.getSelectedRowsData().length > 0) {
                let selectVal = ifscTable.getSelectedRowsData()[0];
                $(".modal-background").css("display", 'flex');
                modalContent.updateData('링크_ID', selectVal.ifsc_id);
                modalContent.updateData('명칭', selectVal.ifsc_nm);
                modalContent.updateData('시점명', selectVal.strt_nm);
                modalContent.updateData('종점명', selectVal.end_nm);
            }
        }
    })
    //상단 조회 버튼
    $(".search-button").dxButton({
        text:'조회',
        icon:'refresh',
        stylingMode:'outlined',
        height:'30px',
        width: '80px',
        onClick(){
            fetchListData();
        }
    })
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    })
    //모달창 x 버튼
    $(".modal-cancle").dxButton({
        icon:'close',
        stylingMode:'text',
        onClick(){
            $(".modal-background").css("display",'none');
        }
    })
    //모달창 저장
    $(".modal-save-Btn").dxButton({
        stylingMode:'outlined',
        text:'저장',
        icon:'save',
        onClick(){
            const ifsc_id     = modalContent.option().formData.ID;
            const ifsc_nm     = modalContent.option().formData.명칭;
            const strt_nm     = modalContent.option().formData.시점명;
            const end_nm      = modalContent.option().formData.종점명;
            const fronContent = '정보제공구간 ID : ' + ifsc_id + '<br>';
            const validationArr = [
                [ifsc_nm, '명칭', 'ifsc_nm'],
                [strt_nm, '시점명', 'strt_nm'],
                [end_nm,  '종점명', 'end_nm'],
            ]
            const selectedData = ifscTable.getSelectedRowsData()[0];
            let sameCnt = 0;
            for (let validation of validationArr) {
                const empty = nullChecker(validation[0]) === "";
                if (empty) {
                    return alertWarning(fronContent + validation[1] +"을 입력해주세요.", null, modalContent.getEditor(validation[1]));
                }
                else if (getByteLength(validation[0]) > 100) {
                    return alertWarning(fronContent + validation[1] +"을 100바이트 이내로 입력해주세요.", null, modalContent.getEditor(validation[1]));
                }
                if (selectedData[validation[2]] === validation[0]) {
                    sameCnt++;
                }
            }
            if (sameCnt === 3) {
                return alertWarning(fronContent + "변경 된 사항이 없습니다.", null);
            }
            confirmMessage(fronContent + _pageName + "를 수정하시겠습니까?").done((yes) => {
                if (yes === true) {
                    const updateData = {
                        ifsc_nm: ifsc_nm,
                        strt_nm: strt_nm,
                        end_nm: end_nm,
                    }
                    
                    let result = putUpdate( _apiUri + '/name/' + ifsc_id, updateData);
                    
                    if ( result > 0 ) {
                        fetchListData();
                        $(".modal-background").css("display","none");
                        alertConfirm(fronContent + "<br>" + _pageName + "를 수정하였습니다.");
                    }
                }
            });

        },
    });
    
    //모달창 취소 버튼
    $(".modal-cancle-Btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        icon:'close',
        onClick(){
            $(".modal-background").css("display",'none');
        },
    });

    //모달 폼
    const modalContent = $('.modal-content')
        .dxForm({
            formData: null,
            minColWidth: 200,
            labelLocation: 'left',
            items: [
                {
                    caption: '정보제공구간 정보',
                    itemType: 'group',
                    colCount: 2,
                    items: [
                        {
                            dataField: 'ID',
                            disabled: true,
                            editorOptions: {
                                width: '160px',
                                stylingMode: 'outlined',
                            },
                        },
                        {
                            dataField: '명칭',
                            editorOptions: {
                                width: '160px',
                                stylingMode: 'outlined',
                            },
                        },
                    ],
                },
                {
                    itemType: 'group',
                    colCount: 2,
                    items: [
                        {
                            dataField: '시점명',
                            editorOptions: {
                                width: '160px',
                                stylingMode: 'outlined',
                            },
                        },
                        {
                            dataField: '종점명',
                            editorOptions: {
                                width: '160px',
                                stylingMode: 'outlined',
                            },
                        },
                    ],
                },
            ],
        })
        .dxForm('instance');
    
    //ifsc 테이블
    ifscTable = $(".ifsc-table").width('100%').height('100%').dxDataGrid({
            dataSource              : null,
            allowColumnReordering   : true,
            showColumnLines         : true,
            allowColumnResizing     : true,
            showBorders             : true,
            rowAlternationEnabled   : true,
            columnAutoWidth         : true,
            focusedRowEnabled       : true,
            noDataText              : '표출할 정보가 없습니다.',
            keyExpr                 : 'ifsc_id',
            selection: {
               mode: 'single',
            },
            filterRow: {
                visible: true,
                applyFilter: "auto",
                showOperationChooser:false,
            },
            headerFilter: {
                visible: true,
            },
            grouping: {
                autoExpandAll: true,
            },
            paging :{
                pageSize : 1000,
            },
            groupPanel:{
                visible: true,
                emptyPanelText:"그룹 지을 항목을 여기에 끌어다 놓으세요"
            },
            export:{
                enabled: true,
                texts: {
                    exportAll:"엑셀 파일",
                },
            },
            onExporting(e){
                gridExcellExporting(e, _pageName);
            },
            columns:[
                {
                    dataField:"ifsc_id",
                    caption:"ID",
                    alignment:"center",
                    dataType : 'string',
                    width:'100px',
                    sortIndex: 0, 
                    sortOrder: "asc"
                },
                {
                    dataField:"ifsc_nm",
                    caption:"명칭",
                    alignment:"center",
                    cellTemplate(c,e){
                        let result = nullChecker(e.displayValue);
                        return  $('<div style="text-align: left;">'+result+'</div>')
                    }
                },
                {
                    dataField:"drct_desc",
                    caption:"방향",
                    alignment:"center",
                    cellTemplate(c,e){
                        let result = nullChecker(e.displayValue);
                        return  $('<div style="text-align: left;">'+result+'</div>')
                    }
                },
                {   
                    dataField:"f_node_id",
                    caption:"시작노드ID",
                    alignment:"center",
                },
                {
                    dataField:"t_node_id",
                    caption:"종료노드ID",
                    alignment:"center",
                },
                {
                    dataField:"strt_nm",
                    caption:"시점명",
                    alignment:"center",
                    cellTemplate(c,e){
                        let result = nullChecker(e.displayValue);
                        return  $('<div style="text-align: left;">'+result+'</div>')
                    }
                },
                {
                    dataField:"end_nm",
                    caption:"종점명",
                    alignment:"center",
                    cellTemplate(c,e){
                        let result = nullChecker(e.displayValue);
                        return  $('<div style="text-align: left;">'+result+'</div>')
                    }
                },
                {
                    dataField:"sect_lngt",
                    caption:"길이",
                    alignment:"center",
                },
                {
                    dataField:"sect_grad_desc",
                    caption:"구간등급코드",
                    alignment:"center",
                    cellTemplate(c,e){
                        let result = nullChecker(e.displayValue);
                        return  $('<div style="text-align: left;">'+result+'</div>')
                    }
                },
                {
                    dataField:"rmrk",
                    caption:"비고",
                    alignment:"center",
                },
                {
                    dataField:"extr_cnct_sect_yn",
                    caption:"외부연계",
                    alignment:"center",
                },
                
            ],
            onRowClick(e){
                ifscMakeUpData=[];
                if (_selectedIfsc === null || _selectedIfsc !== e.data.ifsc_id) {
                    _selectedIfsc = e.data.ifsc_id
                    getData("/api/database/ifsc/rltn/" + e.data.ifsc_id, ifscMakeUpData);
                    console.log(ifscMakeUpData);
                    ifscMakeupTable.option("dataSource",ifscMakeUpData[0]);
                    ifscMakeupTable.clearSelection();
                    ifscMakeupTable.option('focusedRowIndex', -1);
                }
            },
            onRowDblClick(e){
                modalContent.updateData('ID', e.data.ifsc_id);
                modalContent.updateData('명칭', e.data.ifsc_nm);
                modalContent.updateData('시점명', e.data.strt_nm);
                modalContent.updateData('종점명', e.data.end_nm);
                $(".modal-background").css("display",'flex');
            }
    }).dxDataGrid("instance");

    //ifsc 구간 테이블
    const ifscMakeupTable=$(".ifsc-makeup-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'ord',
        selection : {
            mode: 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter : {
            visible : true,
        },
        grouping : {
            autoExpandAll : true,
        },
        groupPanel : {
            visible : true,
            emptyPanelText : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        export : {
            enabled : true,
            texts   : {
                exportAll : "엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, '링크정보');
        },
        columns:[
            {
                dataField:"ord",
                caption:"순서",
                alignment:"center",
                sortIndex: 0, 
                sortOrder: "asc"
            },
            {
                dataField:"link_id",
                caption:"링크 ID",
                alignment:"center",
                dataType : 'string',
            },
            {
                dataField:"from_node",
                caption:"시작노드",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            {
                dataField:"to_node",
                caption:"종료노드",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            {   
                dataField:"link_leng",
                caption:"길이",
                alignment:"center",
            },
            {
                dataField:"road_name",
                caption:"도로명",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            {
                dataField:"road_no",
                caption:"도로번호",
                alignment:"center",
            },
            {
                dataField:"road_rank_desc",
                caption:"도로등급",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            },
            {
                dataField:"road_type_desc",
                caption:"도로유형",
                alignment:"center",
            },
            {
                dataField:"lanes",
                caption:"차로수",
                alignment:"center",
            },
            {
                dataField:"sect_grad_desc",
                caption:"구간등급코드",
                alignment:"center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left; padding-left: 10px;">'+result+'</div>')
                }
            }
        ],
          
    }).dxDataGrid("instance");
    fetchListData();
})

function fetchListData(){
    getDataAsync(_apiUri, (jsonData)=>{
        ifscTable.option('dataSource', jsonData);
    })
}