const url               = new URL(window.location.href);
const _form             = url.searchParams.get("vms_form_id");
const _kind             = url.searchParams.get("trfc_situ_type_cd");
const _type             = url.searchParams.get("vms_type_cd");
const _vmsCtlrNmbr      = url.searchParams.get("vms_ctlr_nmbr");
const _phase            = Number(url.searchParams.get("phase"));
let   _popupMap         = null;
const _imageSrc         = window.opener.getImgSrc();
let _infoInsertBtn      = null;
let _tableSave          = null;
let _tableDelete        = null;
let _strtDt             = null;
let _endDt              = null;
let _strtTime           = null;
let _endTime            = null;
let _modalStrtDt        = null;
let _modalEndDt         = null;
let _modalStrtTime      = null;
let _modalEndTime       = null;
let _modalSave          = null;
let _dsplHHDataSource   = [];
let _useYnDataSource    = ['Y','N'];
let _formMap            = new Map();
const crudUri           = '/api/vms/schedule/common/batch'
let _formTable          = null;
let _listTable          = null;
let _saveState          = false;
const frontColumnNames  = ['frst','secd','thir','four'];

const _btnArr = [
    _infoInsertBtn = btnSettings('form-insert-btn', '적용', 'outlined', 'arrowleft', infoInsertEvent),
    _infoDeleteBtn = btnSettings('form-delete-btn', '삭제', 'outlined', 'arrowright', infoDeleteEvent),
    _tableSave     = btnSettings('table-save', '확인', 'outlined', 'save', infoSaveEvent),
    _tableDelete   = btnSettings('table-delete', '취소', 'outlined', 'close', closeEvent),
];

$(()=>{
    window.onunload = ()=>{
        window.opener.$('.pop-up-modal').addClass('dpl-none');
        if (_saveState === false) {
            const popupMap = window.opener.getPopupMap();
            popupMap.set(_phase, _popupMap);
        }
    }
    _btnArr.map((item)=>{
        item.box = $("." + item.class).dxButton({
            text         : item.text,
            stylingMode  : item.stylingMode,
            icon         : item.icon,
            onClick(){
                item.method();
            }
        }).dxButton("instance");
    })
    window.onkeydown = function() {
        var kcode = event.keyCode;
        if(kcode == 8 || kcode == 116) event.returnValue = false;
    }

    _formObjList = $(".form-obj-list").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        focusedRowEnabled       : true,
        keyExpr                 : 'obj_type',
        toolbar                 : {
            visible         : false,
        },
        selection               : {
            mode            : 'single',
        },
        paging                  : {
            enabled         : false,
            pageSize        : 1,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:[
            {
                dataField    : "obj_type",
                caption      : "객체유형",
                sortIndex    : 0,
                sortOrder    : 'asc',
                alignment    : "center",
                cssClass     : 'no-padding',
            },
            {
                dataField    : "vms_ifsc_id",
                caption      : "구간 ID",
                alignment    : "center",
                cssClass     : 'no-padding',
            },
            {
                dataField    : "vms_ifsc_nm",
                caption      : "구간명",
                alignment    : "center",
                allowEditing : false,
                cssClass     : 'no-padding',
                cellTemplate(c,e){
                    c.css('text-align','left');
                    c.text(e.displayValue)
                }
            },
            {
                dataField    : "dspl_strt_node_nm",
                caption      : "시점명",
                alignment    : "center",
                cssClass     : 'no-padding',
                cellTemplate(c,e){
                    c.css('text-align','left');
                    c.text(e.displayValue)
                }
            },
            {
                dataField    : "dspl_end_node_nm",
                caption      : "종점명",
                allowEditing : false,
                alignment    : "center",
                cssClass     : 'no-padding',
                cellTemplate(c,e){
                    c.css('text-align','left');
                    c.text(e.displayValue)
                }
            },
        ]
    }).dxDataGrid("instance");

    _trafficSectList = $(".traffic-sect-list").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        keyExpr                 : "vms_ifsc_id",
        sorting                 : {
            mode            : 'none',
        },
        noDataText              : '표출할 정보가 없습니다.',
        editing                 :{
            mode            : 'batch',
            allowUpdating   : true,
        },
        toolbar                 :{
            visible         : false,
        },
        selection               : {
            mode            : 'single',
        },
        paging                  : {
            enabled         : false,
            pageSize        : 1,
        },
        scrolling: {
            mode: 'standard',
        },
        headerFilter            : {
            visible : true,
        },
        columns:[
                    {
                        dataField    : "vms_ifsc_id",
                        caption      : "구간 ID",
                        allowEditing : false,
                        sortIndex    : 0,
                        cssClass     : 'no-padding',
                        sortOrder    : 'asc',
                        alignment    : "center",
                    },
                    {
                        dataField    : "vms_ifsc_nm",
                        caption      : "구간명",
                        allowEditing : false,
                        alignment    : "center",
                        cssClass     : 'no-padding',
                        cellTemplate(c,e){
                            c.css('text-align','left');
                            c.text(e.displayValue)
                        }
                    },
                    {
                        dataField    : "dspl_strt_node_nm",
                        caption      : "시점명",
                        alignment    : "center",
                        cssClass     : 'no-padding',
                        allowEditing : false,
                        cellTemplate(c,e){
                            c.css('text-align','left');
                            c.text(e.displayValue)
                        }
                    },
                    {
                        dataField    : "dspl_end_node_nm",
                        caption      : "종점명",
                        alignment    : "center",
                        cssClass     : 'no-padding',
                        cellTemplate(c,e){
                            c.css('text-align','left');
                            c.text(e.displayValue)
                        }
                    },
                    {
                        dataField    : "axis_yn",
                        caption      : "축",
                        alignment    : "center",
                        cssClass     : 'no-padding',
                    },
        ]
    }).dxDataGrid("instance").on('cellDblClick', (cell) => listDblClikcEvent(cell));

    fetchBaseData();

});
// 초기 데이터 로딩
async function fetchBaseData() {
    getDataAsync( '/api/vms/manager/vms-ifsc-rltn/' + _vmsCtlrNmbr, fetchTrafficSectListFunc);
    fetchFormImgFunc(_imageSrc);
    fetchFormObjList();
}

function fetchFormObjList(){
    const popupMap      = window.opener.getPopupMap();

    console.log(popupMap);
    const formObjData   = popupMap.get(_phase);
    _popupMap = new Map();

    formObjData.forEach((obj, key)=>{
        _popupMap.set(key, {...obj});
    });

    const dataSource    = [];
    for(idx in frontColumnNames){
        const frontNm = frontColumnNames[idx];
        if(formObjData.get(frontNm + '_vms_ifsc')){
            dataSource.push(formObjData.get(frontNm + '_vms_ifsc'));
        }
    }
    for(idx in frontColumnNames){
        const frontNm = frontColumnNames[idx];
        if(formObjData.get(frontNm + '_img_ifsc')){
            dataSource.push(formObjData.get(frontNm + '_img_ifsc'));
        }
    }
    _formObjList.option('dataSource', dataSource);
}

//버튼 박스 세팅
function btnSettings(classNm, text, stylingMode, icon, method){
    const btn = {
        box              : null,
        class            : classNm,
        icon             : icon,
        text             : text,
        stylingMode      : stylingMode,
        method           : method,
    }
    return btn;
};

function fetchTrafficSectListFunc(jsonData){
    _trafficSectList.option('dataSource', jsonData);
}


//_form table 데이터 수신
function fetchFormImgFunc(imgSrc){
    if(imgSrc){
        $('.form-image').attr('src', 'data:image/png;base64,' + imgSrc);
    }
};

function infoSaveEvent(){
    let popupMap = window.opener.getPopupMap();
    let popupData = popupMap.get(_phase);
    let infoCnt = 0;
    let imgCnt = 0;
    _formObjList.option('dataSource').forEach(function(item){
        if(item.obj_type.indexOf('단') > -1){
            console.log(frontColumnNames[infoCnt]+ '_vms_ifsc');
            popupData.set(frontColumnNames[infoCnt] + '_vms_ifsc', item);
            infoCnt++;
        }
        else{
            console.log(frontColumnNames[imgCnt] + '_img_ifsc');
            popupData.set(frontColumnNames[imgCnt] + '_img_ifsc', item);
            imgCnt++;
        }
    });
    _saveState = true;
    console.log('infoSaveEvent : ',popupMap);
    window.opener.fetchEditImageData($('.form-image').attr('src').substring(22, $('.form-image').attr('src').length), popupMap);
    
    window.close();
}

function closeEvent(){
    const popupMap = window.opener.getPopupMap();
    popupMap.set(_phase, _popupMap);
    window.close();
}

//적용 버튼 이벤트
function infoInsertEvent(){
    const formObjKeys = _formObjList.getSelectedRowKeys();
    const trafficListData = _trafficSectList.getSelectedRowsData();
    if(formObjKeys.length <= 0) {
        return alertWarning('폼 객체 목록에서 객체 유형을 선택해주세요');
    }
    if(trafficListData <= 0) {
        return alertWarning('정보 구간 목록에서 정보 구간을 선택해주세요');
    }
    const selectedIdx = _formObjList.getRowIndexByKey(formObjKeys[0]);

    _formObjList.cellValue(selectedIdx, 'vms_ifsc_id', trafficListData[0].vms_ifsc_id);
    _formObjList.cellValue(selectedIdx, 'vms_ifsc_nm', trafficListData[0].vms_ifsc_nm);
    _formObjList.cellValue(selectedIdx, 'dspl_strt_node_nm', trafficListData[0].dspl_strt_node_nm);
    _formObjList.cellValue(selectedIdx, 'dspl_end_node_nm', trafficListData[0].dspl_end_node_nm);
    _formObjList.saveEditData();
    
    const formUpdateData = {};
    const formDataSource = _formObjList.option('dataSource');
    for(let idx in formDataSource){
        const data = formDataSource[idx];
        if(data.obj_type.indexOf('단') > -1){
            formUpdateData[frontColumnNames[idx] + '_vms_ifsc_id'] = data.vms_ifsc_id;
        }
    }
    postImageChange( '/api/vms/schedule/auto/list/traffic/draw/' + _vmsCtlrNmbr + '/' + _form , formUpdateData, fechFormRecvFunc);
};

function fechFormRecvFunc(jsonData){
    if(jsonData){
        $('.form-image').attr('src', 'data:image/png;base64,' + jsonData.vms_form_imag);
    }
}

function infoDeleteEvent(){
    const formObjKeys = _formObjList.getSelectedRowKeys();
    if(formObjKeys.length <= 0) {
        return alertWarning('폼 객체 목록에서 객체 유형을 선택해주세요');
    }
    const selectedIdx = _formObjList.getRowIndexByKey(formObjKeys[0]);
    _formObjList.cellValue(selectedIdx, 'vms_ifsc_id', '');
    _formObjList.cellValue(selectedIdx, 'vms_ifsc_nm', '');
    _formObjList.cellValue(selectedIdx, 'dspl_strt_node_nm', '');
    _formObjList.cellValue(selectedIdx, 'dspl_end_node_nm', '');
    _formObjList.saveEditData();

    const formUpdateData = {};
    const formDataSource = _formObjList.option('dataSource');
    
    for(idx in formDataSource){
        const data = formDataSource[idx];
        if(data.obj_type.indexOf('단') > -1){
            formUpdateData[frontColumnNames[idx] + '_vms_ifsc_id'] = data.vms_ifsc_id;
        }
    }

    postImageChange( '/api/vms/schedule/auto/list/traffic/draw/' + _vmsCtlrNmbr + '/' + _form , formUpdateData, fechFormRecvFunc);

}
