//가운데 섹션 관련
let _autoData          = [];
let _autoTableList     = null;
let _dsplHHDataSource  = [];

//좌측 섹션 관련
let _listTable     = null;

//우측 섹션 관련
let _formTableList = null;
let _scheduleTabs  = null;
let _scheduleList  = null;

//공통
let _commonUri        = '/api/vms/schedule/auto/list';
let _scheduleAddBtn   = null;
let _scheduleDelBtn   = null;
let _scheduleSaveBtn  = null;
let _allVmsEditBtn    = null;
let _allVmsAddBtn     = null;
let _strtDt           = null;
let _endDt            = null;
let _strtTime         = null;
let _endTime          = null;
let _modalSaveBtn     = null;
let _allFormRecvState = false;
let _popupObj         = null;

// const scheduleTypeArr        = [
//     {
//         key  : 'traffic',
//         name : '교통정보'
//     },
//     {
//         key  : 'incident',
//         name : '돌발'
//     },
//     {
//         key  : 'event',
//         name : '공사/행사'
//     },
//     {
//         key  : 'notice',
//         name : '홍보'
//     },
//     {
//         key  : 'congest',
//         name : '정체정보'
//     },
//     {
//         key  : 'safety',
//         name : '재난안전'
//     },
// ]

let _updateData   = {
    dspl_cngs_yn        : null,
    dspl_end_hh         : null,
    dspl_hh             : 0,
    dspl_strt_hh        : null,
    four_img_ifsc_id    : null,
    four_vms_ifsc_id    : null,
    frst_img_ifsc_id    : null,
    frst_vms_ifsc_id    : null,
    phase               : 0,
    sch_week1           : null,
    sch_week2           : null,
    sch_week3           : null,
    sch_week4           : null,
    sch_week5           : null,
    sch_week6           : null,
    sch_week7           : null,
    secd_img_ifsc_id    : null,
    secd_vms_ifsc_id    : null,
    strm_addr           : null,
    symb_lib_nmbr       : null,
    thir_img_ifsc_id    : null,
    thir_vms_ifsc_id    : null,
    use_yn              : null,
    vms_ctlr_nmbr       : 0,
    vms_form_id         : 0,
    vms_sch_form_type   : 0,
    vms_sch_type        : "A",
};

let _contentMap        = new Map();

let _vmsTypeData       = [];
let _vmsListMap        = new Map();
let _comboVmsType      = null;
let _vmsFormMap        = new Map();
let _vmsSchduleMap     = new Map();
let _popupImageInfoMap = new Map();

//사용 버튼들
const _btnBoxArr  = [
    _scheduleSaveBtn = {
        column      : 'sch-save-btn',
        box         : null,
        icon        : 'save',
        text        : '스케줄 저장',
        method      : scheduleSaveEvent,
    },
    _allVmsEditBtn = {
        column      : 'all-vms-edit-btn',
        box         : null,
        icon        : 'edit',
        text        : '전체 VMS 편집',
        method      : allEditPopup,
    },
    _allVmsAddBtn = {
        column      : 'all-vms-add-btn',
        box         : null,
        icon        : 'plus',
        text        : '전체 VMS 등록',
        method      : allSavePopup,
    },

]

const dateArr = [
    _strtDt = {
        box              : null,
        class            : 'strt-date',
        type             : 'date',
        value            : new Date(),
        displayFormat    : 'yyyy-MM-dd',
        width            : 140,
        stylingMode      : 'outlined',
        invalid          : '0000-00-00',
    },
    _endDt = {
        box              : null,
        class            : 'end-date',
        type             : 'date',
        value            : new Date(),
        displayFormat    : 'yyyy-MM-dd',
        width            : 140,
        stylingMode      : 'outlined',
        invalid          : '0000-00-00',
    },
    _strtTime = {
        box              : null,
        class            : 'strt-time',
        type             : 'time',
        value            : firstSettingTime,
        interval         : 10,
        displayFormat    : 'HH:mm',
        width            : 100,
        stylingMode      : 'outlined',
        invalid          : '00:00',
    },
    _endTime = {
        box              : null,
        class            : 'end-time',
        type             : 'time',
        value            : endSettingTime,
        interval         : 10,
        displayFormat    : 'HH:mm',
        width            : 100,
        stylingMode      : 'outlined',
        invalid          : '00:00',
    },

]
let addBtn  = null;
let delBtn  = null;
let upBtn   = null;
let downBtn = null;
const btnArr = [
    {
        position    : 'add-btn',
        icon        : 'arrowleft',
        text        : '추가',
        method      : addEvent,
    },
    {
        position    : 'del-btn',
        icon        : 'arrowright',
        text        : '삭제',
        method      : delEvent,
    },
    {
        position    : 'up-btn',
        icon        : 'spinup',
        text        : '위로',
        method      : upMoveEvent,
    },
    {
        position    : 'down-btn',
        icon        : 'spindown',
        text        : '아래로',
        method      : downMoveEvent,
    }
]
for(let ii = 3; ii < 11; ii++){
    _dsplHHDataSource.push(ii);
}

$(()=>{
    /**
     * 화면 딜레이를 줄이기 위해 데이터가 많은 홍보 폼을 먼저 로딩해서 메모리에 올려 놓자.
     */
    window.addEventListener("keydown", (e) => {
        if(e.key === 'F5'){
            _popupObj.close();
        }
    });

    //모달창 바디에 넣기
    $("body").append(modalDiv);
    $(".modal-title").prepend($("<div>VMS 폼 표출기간 설정</div>"));
    $(".modal-background").css("display",'none');
    $(".modal-content").append($(`
        <div></div>
        <div class="date-box">
            <div>
                <div>표출 시작 시각</div>
                <div>
                    <div class="strt-date"></div>
                </div>
                <div>
                    <div class="strt-time"></div>
                </div>
            </div>
            <div>
                <div>표출 종료 시각</div>
                <div>
                    <div class="end-date"></div>
                </div>
                <div>
                    <div class="end-time"></div>
                </div>
            </div>
        </div>
        `)
    )

    btnArr.map((item)=>{
        const btn = item.btn = new dxBtn($("." + item.position), item.text, item.icon, 'outlined', 95, null, false, true);
        btn.onClick(item.method);
    })

    //모달 x 버튼
    _modalCancleBtn = $(".modal-cancle").dxButton({
        stylingMode:'text',
        icon:'close',
        onClick(){
            modalCancleEvent();
        }
    })

    //모달 저장 버튼
    _modalSaveBtn = $(".modal-save-Btn").dxButton({
        stylingMode:'outlined',
        text:'확인',
        icon:'check',
    }).dxButton('instance');

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


    _btnBoxArr.map((item)=>{
        item.box = $("." + item.column).dxButton({
            stylingMode : 'outlined',
            icon        : item.icon,
            text        : item.text,
        }).dxButton("instance");
        item.box.on('click', ()=> item.method());
    })

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

    _comboVmsType = $('.type-select').dxSelectBox({
        dataSource  : null,
        displayExpr : 'vms_type_desc',
        valueExpr   : 'vms_type_cd',
        width       : 250,
        height      : 30,
        stylingMode : 'outlined',
        onItemClick(e){
            const vmsTypeCd     = e.itemData.vms_type_cd;
            const vmsTypeWidth  = e.itemData.vms_wdth;
            const tapType       = _scheduleTabs.option('selectedItems')[0].type;
            vmsTypeComboboxClick(vmsTypeCd, vmsTypeWidth, tapType);
        }
    }).dxSelectBox('instance');

    dateArr.map((item)=>{
        item.box = $("." + item.class).dxDateBox({
            value         : item.value,
            type          : item.type,
            width         : item.width,
            stylingMode   : 'outlined',
            displayFormat : item.displayFormat,
            interval      : item.interval,
            invalidDateMessage  : '형식에 맞게 입력해주세요. ex)' + item.invalid,
        }).dxDateBox("instance");
    })
    //자동 스케줄 목록
    _scheduleList = $('.auto-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : ['vms_ctlr_nmbr','phase'],
        wordWrapEnabled         : true,
        editing                 : {
            confirmDelete : false,
            mode : 'batch',
            allowUpdating : true,
        },
        toolbar                 : {
            visible : false,
        },
        scrolling               : {
            mode : 'standard',
        },
        selection: {
            mode: 'single',
        },
        paging: {
            enabled: true,
            pageSize: 1000,
        },
        sorting  : {
            showSortIndexes : false,
            mode            : 'none',
        },
        columns:[
            {
                dataField    : "vms_form_id",
                caption      : "폼 ID",
                alignment    : "center",
                width        : 50,
                cssClass     : 'no-padding',
                allowEditing : false,
            },
            {
                dataField    : "vms_form_imag",
                caption      : "폼 레이아웃",
                alignment    : "center",
                cssClass     : 'no-padding',
                allowEditing : false,
                cellTemplate(c,e){
                    const imgSrc = 'data:image/png;base64,'+ e.displayValue;
                    const image = $('<img class="img" src="' + imgSrc + '">');
                    return c.append(image);
                }
            },
            {
                dataField    : "phase",
                caption      : "페이즈",
                visible      : false,
                sortIndex    : 0,
                sortOrder    : 'asc',
                alignment    : "center",
                cssClass     : 'no-padding',
                allowEditing : false,
            },
            {
                dataField    : "dspl_hh",
                caption      : "표출(초)",
                alignment    : "center",
                width        : 70,
                lookup       : {
                    dataSource : _dsplHHDataSource,
                },
                cssClass     : 'no-padding',
            },
            {
                dataField    : "dspl_strt_hh",
                caption      : "시작 시각",
                alignment    : "center",
                cssClass     : 'no-padding',
                dataType     : 'datetime',
                format       : 'yyyy-MM-dd HH:mm',
                allowEditing : false,
            },
            {
                dataField    : "dspl_end_hh",
                caption      : "종료 시각",
                alignment    : "center",
                cssClass     : 'no-padding',
                dataType     : 'datetime',
                format       : 'yyyy-MM-dd HH:mm',
                allowEditing : false,
            },
            {
                dataField    : "use_yn",
                caption      : "사용",
                alignment    : "center",
                width        : 60,
                cssClass     : 'no-padding',
                lookup       : {
                    dataSource: ['Y','N'],
                }
            },
        ],
        onFocusedRowChanged(e){
            e.component.selectRowsByIndexes(e.rowIndex);
        },
    }).dxDataGrid('instance').on('cellDblClick', (cell)=> scheduleListDblClick(cell));
    
    //VMS 목록
    _listTable = $(".list-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'vms_ctlr_nmbr',
        selection: {
            mode                : 'single',
            showCheckBoxesMode  : "onClick"
        },
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:[
            {
                dataField    : "vms_ctlr_nmbr",
                caption      : "번호",
                alignment    : "center",
                cssClass     : 'no-padding',
                width        : '70'
            },
            {
                dataField    : "vms_ctlr_id",
                caption      : "VMS ID",
                alignment    : "center",
                width        : 110,
                cssClass     : 'no-padding',
            },
            {
                dataField    : "vms_nm",
                caption      : "VMS 명칭",
                alignment    : "center",
                cssClass     : 'no-padding',
                width        : 140,
                cellTemplate(c,e){
                    c.css('text-align','left');
                    c.text(e.displayValue)
                }
            },
        ],
        onRowClick(e){
            const scheduleType = _scheduleTabs.option('selectedItems')[0].type;
            fetchVmsSchedule(e.data.vms_ctlr_nmbr, e.data.vms_nm, scheduleType, getValue(_comboVmsType));
        },
    }).dxDataGrid("instance");
    
    //우측 교통정보, 홍보 폼 탭
    _scheduleTabs = $('.auto-tabs').width('100%').height('100%').dxTabPanel({
        dataSource:[
            {
                id      : 0,
                name    : '교통정보',
                type    : 'traffic',
                table   : null,
            },
            {
                id      : 3,
                name    : '홍보',
                type    : 'notice',
                table   : null,
            },
        ],
        selectIndex:0,
        loop:false,
        animationEnabled: true,
        swipeEnabled: false,
        itemTitleTemplate: function(e){
            return $('<div>'+e.name+'</div>')
        },
        itemTemplate: function(e, idx, c){
            c.css({width:'100%', height:'100%', padding: '2px'});
            c.html($(`
                <div class='${e.type}'></div>
            `));
            //전체 폼 목록(교통정보, 홍보)
            e.table = $('.'+e.type).width('100%').height('100%').dxDataGrid({
                dataSource              : null,
                allowColumnReordering   : true,
                showColumnLines         : true,
                showBorders             : true,
                allowColumnResizing     : true,
                rowAlternationEnabled   : true,
                columnAutoWidth         : true,
                focusedRowEnabled       : true,
                keyExpr                 : 'vms_form_id',
                noDataText              : '표출할 정보가 없습니다.',
                scrolling               : {
                    mode : 'standard',
                },
                selection: {
                    mode: 'single',
                },
                paging: {
                    enabled: true,
                    pageSize: 1000,
                },
                sorting  : {
                    showSortIndexes : false,
                    mode            : 'none',
                },
                columns:[
                    {
                        dataField    : "vms_form_id",
                        caption      : "폼 ID",
                        alignment    : "center",
                        width        : 80,
                        cssClass     : 'no-padding',
                        sortIndex    : 0,
                        sortOrder    : 'asc',
                    },
                    {
                        dataField    : "vms_form_imag",
                        caption      : "폼 레이아웃",
                        alignment    : "center",
                        cssClass     : 'no-padding',
                        cellTemplate(c,e){
                            c.css('padding','3px')
                            const imgSrc = 'data:image/png;base64,'+ e.displayValue
                            return c.append($('<img src="'+imgSrc+'">'));
                        }
                    },
                ],
            }).dxDataGrid('instance');
            return c;
        },
        onSelectionChanged(tab){
            tabSelectionChange(tab);
        },
    }).dxTabPanel('instance');

   fetchBaseData();
})

// 초기 데이터 로딩
function fetchBaseData() {
    getDataAsync('/api/vms/common/vms-type', recvVmsTypeFunc);
}


// VMS TYPE 데이터 수신
function recvVmsTypeFunc(jsonData) {
    _vmsTypeData = jsonData;
    _vmsTypeData.map((item)=>{
        item.vms_type_desc = item.vms_type_desc + ' (' + item.vms_wdth + 'x' + item.vms_hght + ')';
    });
    _comboVmsType.option('dataSource', _vmsTypeData);

    if (_vmsTypeData.length > 0 ) {
        const defaultVmsTypeCd = _vmsTypeData[0].vms_type_cd;
        _comboVmsType.option('value', defaultVmsTypeCd);
    }
    getDataAsync('/api/vms/common/vms-list', recvVmsListFunc);
}

// VMS LIst 데이터 수신
function recvVmsListFunc(jsonData) {
    dataSorting(jsonData, 'vms_ctlr_nmbr');
    jsonData.forEach((obj) => {
        let vmsObjs = _vmsListMap.get(obj.vms_type_cd);
        if (!vmsObjs) {
            vmsObjs = new Array();
            _vmsListMap.set(obj.vms_type_cd, vmsObjs);
            _vmsFormMap.set(obj.vms_type_cd, new Map());
        }
        vmsObjs.push(obj);
    });

    if (jsonData.length > 0) {
        const selectedItems = _scheduleTabs.option('selectedItems');
        vmsTypeComboboxClick(_vmsTypeData[0].vms_type_cd, _vmsTypeData[0].vms_wdth, selectedItems[0].type);
    }
}

//VMS TYPE 콤보박스 선택 이벤트
function vmsTypeComboboxClick(vmsTypeCd, vmsTypeWidth, scheduleType) {
    let formTableList = _scheduleTabs.option('selectedItem').table;
    _scheduleTabs.option('dataSource').map((item)=>{
        if (item.table) {
            item.table.option('dataSource', null);
        }
    });

    //리스트 불러오기
    const vmsTypeList = _vmsListMap.get(vmsTypeCd);

    //리스트 테이블 세팅
    _listTable.option('dataSource', vmsTypeList);
    _listTable.refresh().then(()=>{
        _listTable.option('focusedRowIndex', 0);
        _listTable.selectRows(_listTable.getKeyByRowIndex(0));
    })


    //자동 스케줄 리스트 세팅
    formTableList.option('columns[1].width', vmsTypeWidth + 10);
    formTableList.option('focusedRowIndex', -1);
    formTableList.clearSelection();
    _scheduleList.option('columns[1].width', vmsTypeWidth + 10);

    //폼 테이블 리스트 세팅
    _scheduleList.option('focusedRowIndex', -1);
    _scheduleList.clearSelection();

    _popupImageInfoMap = new Map();

    if (vmsTypeList) {
        fetchVmsSchedule(vmsTypeList[0].vms_ctlr_nmbr, vmsTypeList[0].vms_nm, scheduleType, vmsTypeCd);
    }
    fetchVmsForm(vmsTypeCd, scheduleType);
}

//폼 데이터 수신
function fetchVmsForm(vmsTypeCd, scheduleType) {
    const vmsFormList = _vmsFormMap.get(vmsTypeCd);
    if (vmsFormList.size === 0 || !vmsFormList.get(scheduleType)) {
        getDataAsync('/api/vms/schedule/common/form/' + scheduleType + '/' + vmsTypeCd, fillVmsForm, [vmsTypeCd, scheduleType]);
    }
    else{
        let formTableList = _scheduleTabs.option('selectedItem').table;
        formTableList.option('dataSource', vmsFormList.get(scheduleType));
    }
}

//폼 데이터 세팅
function fillVmsForm(jsonData, arguments) {
    const vmsTypeCd     = arguments[0];
    const scheduleType  = arguments[1];
    _vmsFormMap.get(vmsTypeCd).set(scheduleType, jsonData);
    let formTableList = _scheduleTabs.option('selectedItem').table;
    if (!formTableList.option('dataSource')){
        formTableList.option('dataSource', jsonData);
    }
}

//스케줄 데이터 수신 및 테이블 세팅
function fetchVmsSchedule(vms_ctlr_nmbr, vms_nm, scheduleType, vmsTypeCd){
    _scheduleList.option('editing.allowUpdating', false);
    _scheduleList.option('editing.allowUpdating', true);
    _scheduleList.option('focusedRowIndex', -1);
    _scheduleList.clearSelection();

    _popupImageInfoMap = new Map();

    $('.title').text(vms_nm);

    getDataAsync(_commonUri + '/' + vms_ctlr_nmbr, recvScheduleFunc, [vmsTypeCd, vms_ctlr_nmbr, scheduleType], null, true);
}

//스케줄 데이터 맵 저장 및 테이블 세팅
function recvScheduleFunc(jsonData){
    const scheduleData = dateFommat(jsonData);
    dataSorting(scheduleData, 'phase');
    _scheduleList.option('dataSource', scheduleData);
}

//우측 추가 버튼 이벤트
function addEvent(scheduleType){
    const formTableList = _scheduleTabs.option('selectedItem').table;
    const formData      = formTableList.getSelectedRowsData();
    if (scheduleType === 'safety' && _scheduleList.option('dataSource').length > 0){
        return alertWarning('재난 안전 스케줄 설정<br>재난안전 스케줄은 VMS 당 하나만 설정 가능합니다.<br>기존 스케줄을 삭제 후에 작업하십시오.')
    }
    else if (formData.length > 0) {
        modalDateBtnInit();
        $(".modal-background").css('display','flex');
        _modalSaveBtn.off('click');
        _modalSaveBtn.on('click', () => scheduleListAddForm(scheduleType));
        return
    }
    else{
        return alertWarning(_contentMap.get(scheduleType).get('name') + ' 폼 목록에서 스케줄 정보를 선택해주세요');
    }
}

//우측 삭제 버튼 이벤트
function delEvent(){
    const key = _scheduleList.getSelectedRowKeys();
    if (key.length > 0) {
        const idx = _scheduleList.getRowIndexByKey(key[0]);
        _scheduleList.deleteRow(idx);
        _scheduleList.saveEditData();
        _scheduleList.refresh().then(()=>{
            if(_scheduleList.option('focusedRowIndex') !== idx){
                _scheduleList.option('focusedRowIndex', -1);
            };
            _scheduleList.selectRowsByIndexes(idx);
            _scheduleList.refresh();
        });
        return
    }
    return alertWarning('자동 스케줄 목록에서 스케줄 정보를 선택해주세요');
}

//전체 VMS 등록 버튼 이벤트
function allSavePopup(){
    const formTableList = _scheduleTabs.option('selectedItem').table;
    const type = _scheduleTabs.option('selectedItem').id;
    const formData = formTableList.getSelectedRowsData();

    if(formData.length > 0){
        $('.pop-up-modal').removeClass('dpl-none');
        _popupObj = window.open('./auto-tot-insert-pop-up.html'
            + '?vms_form_id=' + formData[0].vms_form_id
            + '&vms_type_cd=' + formData[0].vms_type_cd
            + '&trfc_situ_type_cd=' + type,
            + 'VMS 일괄 등록', 'width=1200, height=800, top=89.5, left=360');
        _popupObj.onbeforeunload = ()=>{
            $('.pop-up-modal').addClass('dpl-none');
        }
        return
    }
    return alertWarning('VMS 스케줄 일괄 관리<br>등록되어 있는 스케줄 폼을 목록에서 먼저 선택하세요');
}

//전체 VMS 편집 버튼 이벤트
function allEditPopup(){
    const scheduleData = _scheduleList.getSelectedRowsData();
    console.log(scheduleData);
    if(scheduleData.length > 0){
        $('.pop-up-modal').removeClass('dpl-none');
        _popupObj = window.open('./auto-tot-edit-pop-up.html'
            + '?vms_form_id='
            + scheduleData[0].vms_form_id
            + '&vms_type_cd='
            + getValue(_comboVmsType)
            + '&trfc_situ_type_cd='
            + scheduleData[0].vms_sch_form_type,
            + 'VMS 일괄 편집', 'width=1200, height=800, top=89.5, left=360');
        _popupObj.onbeforeunload = ()=>{
            $('.pop-up-modal').addClass('dpl-none');
        }
        return
    }
    return alertWarning('VMS 스케줄 일괄 관리<br>등록되어 있는 스케줄 폼을 목록에서 먼저 선택하세요');
}

//_scheduleList 데이터 초기화
function scheduleTableListRefresh(){
    let data = [];
    const scheduleType = _scheduleTabs.option('selectedItems')[0].type;
    const vms_ctlr_nmbr = _listTable.getSelectedRowsData()[0].vms_ctlr_nmbr

    getData(_commonUri + '/' + vms_ctlr_nmbr, data);
    if (data.length > 0) {
        data = dateFommat(data[0]);
        _scheduleList.option('dataSource', data);
        _scheduleList.option('focusedRowIndex', -1);
        _scheduleList.clearSelection();
    }
}

//스케줄 저장 이벤트
function scheduleSaveEvent(){
    const vmsNum = _listTable.getSelectedRowsData()[0].vms_ctlr_nmbr;
    confirmMessage('VMS : ' + vmsNum + '<br>선택한 VMS의 자동 스케줄 정보를 등록 하시겠습니까?').done((yes) => {
        if (yes === true) {
            let result   = 0;
            _scheduleList.saveEditData();
            const dataSource = _scheduleList.option('dataSource');
            const insertUpdateData = [];
            dataSorting(dataSource, 'phase');
            if (dataSource.length > 0) {
                dataSource.map((item, idx)=>{
                    let data = {...item}
                    let updateData = {};
                    if (data.dspl_strt_hh) data.dspl_strt_hh = getSendDate(data.dspl_strt_hh);
                    if (data.dspl_end_hh)  data.dspl_end_hh  = getSendDate(data.dspl_end_hh);
                    data.phase = idx+1;
                    for (let key in _updateData) {
                        if(data[key] ===  undefined) {
                            updateData[key] = _updateData[key];
                            continue
                        };
                        updateData[key] = data[key];
                    }
                    insertUpdateData.push(updateData);
                });
                result = postInsertUpdate('/api/vms/schedule/common/' + vmsNum, insertUpdateData);
            }
            else {
                let data = [];
                getData(_commonUri + '/' + vmsNum , data);
                if (data[0].length > 0) {
                    result = deleteDataIds('/api/vms/schedule/common/batch', data[0]);
                }
            }

            if (result > 0) {
                scheduleTableListRefresh();
                _popupImageInfoMap = new Map();
                return alertConfirm('VMS 자동 스케줄 관리<br>VMS 자동 스케줄 정보를 등록 하였습니다.');
            }
        }
    });

}

//모달 저장 이벤트 - defaultTableList 홍보 폼 추가
function scheduleListAddForm(){

    const formTableList = _scheduleTabs.option('selectedItem').table;

    if (!validationCheck( _strtDt.box, _endDt.box, _strtTime.box, _endTime.box )) return false;

    const dspl_strt_hh = modalTimeFommat(_strtDt, _strtTime);
    const dspl_end_hh  = modalTimeFommat(_endDt, _endTime);

    if (dspl_strt_hh > dspl_end_hh) {
        return alertWarning('시작 시각이 종료 시각보다 큽니다.');
    }

    const formData = formTableList.getSelectedRowsData();

    const dataSource = _scheduleList.option('dataSource');
    const phase = dataSource.length > 0 ? dataSource[dataSource.length-1].phase + 1 : 1;
    console.log(formData);
    dataSource.push({
        dspl_cngs_yn      : 'Y',
        dspl_end_hh       : dspl_end_hh,
        dspl_hh           : 4,
        dspl_strt_hh      : dspl_strt_hh,
        sch_week1         : '111111111111111111111111',
        sch_week2         : '111111111111111111111111',
        sch_week3         : '111111111111111111111111',
        sch_week4         : '111111111111111111111111',
        sch_week5         : '111111111111111111111111',
        sch_week6         : '111111111111111111111111',
        sch_week7         : '111111111111111111111111',
        four_img_ifsc_id  : 0,
        four_vms_ifsc_id  : 0,
        frst_img_ifsc_id  : 0,
        frst_vms_ifsc_id  : 0,
        strm_addr         : null,
        symb_lib_nmbr     : null,
        phase             : phase,
        secd_img_ifsc_id  : 0,
        secd_vms_ifsc_id  : 0,
        thir_img_ifsc_id  : 0,
        thir_vms_ifsc_id  : 0,
        vms_sch_form_type : _scheduleTabs.option('selectedItems')[0].id,
        use_yn            : 'N',
        vms_ctlr_nmbr     : _listTable.getSelectedRowsData()[0].vms_ctlr_nmbr,
        vms_form_id       : formData[0].vms_form_id,
        vms_form_imag     : formData[0].vms_form_imag,
        vms_form_type_cd  : formData[0].vms_form_type_cd,
        vms_sch_type      : 'A',
    });
    dataSorting(dataSource, 'phase');
    _scheduleList.option('dataSource', dataSource);
    $(".modal-background").css("display","none");
    formTableList.clearSelection();
    formTableList.option('focusedRowIndex', -1);
}

//모달 저장 이벤트 - defaultTableList 시각 변경
function scheduleListEditTime(cell){
    const table      = cell.component;
    const key        = cell.key;
    const idx        = table.getRowIndexByKey(key);
    let dspl_strt_hh = null;
    let dspl_end_hh  = null;
    let dateValArr   = dateValidation(_strtDt, _endDt, _strtTime, _endTime, dspl_strt_hh, dspl_end_hh);

    if(!dateValArr) return false;

    //모달 창 닫기
    $(".modal-background").css("display","none");
    table.cellValue(idx, 'dspl_strt_hh', dateValArr.dspl_strt_hh);
    table.cellValue(idx, 'dspl_end_hh', dateValArr.dspl_end_hh);
}

//모달 닫기 이벤트
function modalCancleEvent(){
    $(".modal-background").css("display",'none');
}

//모달 데이트 박스 값 초기화
function modalDateBtnInit(){
    setValue(_strtDt.box, new Date());
    setValue(_endDt.box, new Date('2099-12-31'));
    setValue(_strtTime.box, firstSettingTime);
    setValue(_endTime.box,  endSettingTime);
}

//스케줄 테이블 리스트 더블 클릭 이벤트
function scheduleListDblClick(cell){
    if (cell.column) {
        const scheduleData = cell.data;
        switch (cell.column.name) {
            case 'dspl_hh':
                break;
            case 'use_yn':
                break;
            case 'vms_form_imag':
                console.log(scheduleData);
                if (scheduleData.vms_sch_form_type !== 0) return false;
                if (scheduleData.vms_form_type_cd < 11 || scheduleData.vms_form_type_cd > 14) {
                    return alertWarning('VMS 교통정보 폼 구간 설정<br>도형식 배경소통정보 폼은 폼관리 화면에서 설정 가능합니다.');
                }

                if (scheduleData) {
                    console.log(scheduleData);
                    const phase          = scheduleData.phase;
                    const vmsFormId      = scheduleData.vms_form_id;
                    const vmsCtlrNmbr    = scheduleData.vms_ctlr_nmbr;
                    const vmsFormTypeCd  = scheduleData.vms_form_type_cd;
                    const vmsSchFormType = scheduleData.vms_sch_form_type;
                    if(!_popupImageInfoMap.get(phase)){
                        _popupImageInfoMap.set(phase, new Map());
                        getDataAsync( '/api/vms/schedule/auto/form/ifsc/'
                            + vmsCtlrNmbr + '/'
                            + vmsSchFormType + '/'
                            + phase,
                            fetchPopupData, [vmsFormTypeCd, vmsFormId, phase]);
                    }
                    console.log('팝업 진행시',_popupImageInfoMap.get(phase));

                    $('.pop-up-modal').removeClass('dpl-none');
                    _popupObj = window.open('./auto-form-edit-pop-up.html'
                        + '?vms_form_id=' + vmsFormId
                        + '&vms_type_cd=' + getValue(_comboVmsType)
                        + '&vms_ctlr_nmbr=' + vmsCtlrNmbr
                        + '&trfc_situ_type_cd=' + vmsSchFormType
                        + '&vms_form_type_cd=' + vmsFormTypeCd
                        + '&phase=' + phase,
                        + 'VMS 일괄 편집', 'width=1200, height=650, top=165, left=360');
                    return
                }
                alertWarning('VMS 스케줄 일괄 관리<br>등록되어 있는 스케줄 폼을 목록에서 먼저 선택하세요');
                break;
            default:
                setValue(_strtDt.box, scheduleData.dspl_strt_hh);
                setValue(_strtTime.box, scheduleData.dspl_strt_hh.getTime());
                setValue(_endDt.box, scheduleData.dspl_end_hh);
                setValue(_endTime.box, scheduleData.dspl_end_hh.getTime());
                $(".modal-background").css('display','flex');
                _modalSaveBtn.off('click');
                _modalSaveBtn.on('click', () => scheduleListEditTime(cell));
                break;
        }

    }

}

function getPopupMap(){
    return _popupImageInfoMap;
}

function fetchPopupData(jsonData, arguments){
    console.log('popupData', jsonData);
    if(!jsonData || jsonData.length <= 0) return false;

    const vmsFormTypeCd = arguments[0];
    const vmsFormId     = arguments[1];
    const phase         = arguments[2]
    const objData       = [];


    const popupIdxMap = _popupImageInfoMap.get(phase);
    getData('/api/vms/form/manage/object/' + vmsFormId, objData);
    console.log('objData', objData);

    let trafficCnt = 0;
    if(objData.length > 0){
        const typeCd = [17,27,37,47];

        objData[0].map((item)=>{
            if (typeCd.includes(item.vms_form_object_type_cd)) trafficCnt++;
        })
    }

    const clmnFrtNm      = ['frst','secd','thir','four'];
    const clmnTypeNm     = '단 소통정보';
    const trafficImg     = '소통정보이미지';
    const columns = {
        axis_yn: null,
        dspl_end_node_nm: null,
        dspl_strt_node_nm: null,
        road_nm: null,
        spot_nm: null,
        vms_ifsc_id: null,
        vms_ifsc_nm: null,
    }
    console.log(vmsFormTypeCd);
    for(let ii = 0; ii <= (Number(vmsFormTypeCd) - 11); ii++){
        if(jsonData[clmnFrtNm[ii] + '_vms_ifsc']){
            jsonData[clmnFrtNm[ii] + '_vms_ifsc']['obj_type'] = (Number(ii) + 1) + clmnTypeNm;
            const objRow = {...jsonData[clmnFrtNm[ii] + '_vms_ifsc']};
            popupIdxMap.set(clmnFrtNm[ii] + '_vms_ifsc', objRow);
        }
        else{
            let objRow = {};
            objRow = {...columns};
            objRow['obj_type'] = (Number(ii) + 1) + clmnTypeNm;
            popupIdxMap.set(clmnFrtNm[ii] + '_vms_ifsc', objRow);

        }
    }

    for(let ii = 0; ii < trafficCnt; ii++){
        if(jsonData[clmnFrtNm[ii] + '_img_ifsc']){
            jsonData[clmnFrtNm[ii] + '_img_ifsc']['obj_type'] = trafficImg + (ii + 1) ;
            const objRow = {...jsonData[clmnFrtNm[ii] + '_img_ifsc']};
            popupIdxMap.set(clmnFrtNm[ii] + '_img_ifsc', objRow);
        }
        else{
            let objRow = {};
            objRow = {...columns};
            objRow['obj_type'] = trafficImg + (ii + 1);
            popupIdxMap.set(clmnFrtNm[ii] + '_img_ifsc', objRow);
        }
    }
    console.log('팝업맵',_popupImageInfoMap);
}

//선택된 로우 이미지 소스 가져오기
function getImgSrc(){
    const scheduleData = _scheduleList.getSelectedRowsData();
    if (scheduleData.length > 0){
        return scheduleData[0].vms_form_imag
    }
}

//날짜 유효성 체크
function dateValidation( _strtDt, _endDt, strttm, endtm, dspl_strt_hh, dspl_end_hh){
    //유효성 검사 - 널체크
    if(!validationCheck( _strtDt.box, _endDt.box, strttm.box, endtm.box )) return false;

    //유효성 검사 - 시간 크기 검사
    dspl_strt_hh = modalTimeFommat(_strtDt, strttm);
    dspl_end_hh  = modalTimeFommat(_endDt, endtm);
    if(dspl_strt_hh > dspl_end_hh){
        _strtDt.box.focus();
        alertWarning('시작 시각이 종료 시각보다 큽니다.', null, _strtDt.box);
        return false;
    }
    return {dspl_strt_hh, dspl_end_hh};
}

//탭 클릭 시 내용 변경 이벤트
function tabSelectionChange(tab){
    const vmsTypeCd      = getValue(_comboVmsType);
    const addedTab       = tab.addedItems[0];
    const scheduleType   = addedTab.type;
    _popupImageInfoMap   = new Map();

    fetchVmsForm(vmsTypeCd, scheduleType);
}

//스케줄 데이터 수신 맵 객체 저장
function recvVmsScheduleFunc(jsonData, arguments){
    if(jsonData){
        jsonData = dateFommat(jsonData);
    }
}

//데이트 포맷
function dateFommat(data){
    data.map((item)=>{
        if(item.dspl_strt_hh)item.dspl_strt_hh  = new Date( getParseDateTime(item.dspl_strt_hh) );
        if(item.dspl_end_hh) item.dspl_end_hh  = new Date( getParseDateTime(item.dspl_end_hh) );
    });
    return data;
}


//폼 데이터 전체 맵 저장 이벤트
function recvFormFunc(jsonData, arguments){
    _vmsFormMap.get(arguments[0]).set(arguments[1], jsonData);
};

//스케줄 위로 버튼 이벤트
let isMoveUp = true;
function upMoveEvent(){
    if (!isMoveUp) {
        return;
    }
    const key = _scheduleList.getSelectedRowKeys();
    const dataSource = [..._scheduleList.option('dataSource')];

    const selectRowIdx  = _scheduleList.getRowIndexByKey(key[0]);
    const changeRowIdx = selectRowIdx - 1;
    if (key.length > 0 && changeRowIdx >= 0) {
        isMoveUp = false;
        let selectData  = {...dataSource[selectRowIdx]};
        let changeData = {...dataSource[changeRowIdx]};

        const keys = Object.keys(selectData);
        for (let idx in keys) {
            const key = keys[idx];
            if ( key !== 'vms_ctlr_nmbr' && key !== 'phase') {
                dataSource[selectRowIdx][key] = changeData[key];
                dataSource[changeRowIdx][key] = selectData[key];
            }
        }
        _scheduleList.option('dataSource', dataSource);
        _scheduleList.refresh().done(function(){
            _scheduleList.selectRowsByIndexes(changeRowIdx);
            _scheduleList.option('focusedRowIndex', changeRowIdx);
            console.log(_scheduleList.option('dataSource'));
            isMoveUp = true;
        });
    }
}

//스케줄 아래로 버튼 이벤트
let isMoveDown = true;
function downMoveEvent(){
    if (!isMoveDown) {
        return;
    }
    const key = _scheduleList.getSelectedRowKeys();
    const dataSource = [..._scheduleList.option('dataSource')];

    const selectRowIdx  = _scheduleList.getRowIndexByKey(key[0]);
    const changeRowIdx = selectRowIdx + 1;
    if(key.length > 0 && changeRowIdx < dataSource.length){
        isMoveDown = false;
        let selectData  = {...dataSource[selectRowIdx]};
        let changeData = {...dataSource[changeRowIdx]};

        const keys = Object.keys(selectData);
        for (let idx in keys) {
            const key = keys[idx];
            if ( key !== 'vms_ctlr_nmbr' && key !== 'phase') {
                dataSource[selectRowIdx][key] = changeData[key];
                dataSource[changeRowIdx][key] = selectData[key];
            }
        }
        _scheduleList.option('dataSource', dataSource);
        _scheduleList.refresh().done(function(){
            _scheduleList.selectRowsByIndexes(changeRowIdx);
            _scheduleList.option('focusedRowIndex', changeRowIdx);
            isMoveDown = true;
        });
    }
}

//팝업 이미지데이터 세팅 이벤트
function fetchEditImageData(imgSrc, objMap){
    console.log('fetchEditImageData', objMap);
    const tabData = _scheduleTabs.option('selectedItem');
    if(tabData){
        const selectedKeys = _scheduleList.getSelectedRowKeys();
        if(selectedKeys.length > 0){
            const selectedRow        = _scheduleList.getRowIndexByKey(selectedKeys[0]);
            const phase              = _scheduleList.getSelectedRowsData()[0].phase;
            const scheduledataSource = [..._scheduleList.option('dataSource')];
            const cnt = 0;
            if(objMap.size > 0){
                objMap.get(phase).forEach((value, key)=>{
                    scheduledataSource[selectedRow][key + '_id'] = value.vms_ifsc_id;
                });

                scheduledataSource[selectedRow].vms_form_imag = imgSrc;
                _scheduleList.option('dataSource', scheduledataSource);
                _popupImageInfoMap.set(phase, objMap.get(phase));
            }
        }
    }
}