let _updateData    = {
    dspl_end_hh         : null,
    dspl_hh             : 0,
    dspl_strt_hh        : null,
    phase               : 0,
    use_yn              : null,
    vms_ctlr_nmbr       : 0,
    vms_form_id         : 0,
    vms_sch_form_type   : null,
    vms_sch_type        : null,
};

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");


let _formSave          = null;
let _tableSave         = 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();
let _listMap           = new Map();
const _commonUri       = '/api/vms/schedule/common/vms-list/add';
let _formTable         = null;
let _listTable         = null;

for(let ii = 3; ii < 11; ii++){
    _dsplHHDataSource.push(ii);
}

const dateArr = [
    _strtDt         = dateSettings('strt-date', 'date', 140, new Date(), 'yyyy-MM-dd', 'outlined', null, '0000-00-00'),
    _endDt          = dateSettings('end-date', 'date', 140, new Date('2099-12-31'), 'yyyy-MM-dd', 'outlined', null, '0000-00-00'),
    _strtTime       = dateSettings('strt-time', 'time', 100, firstSettingTime, 'HH:mm', 'outlined', 10, '00:00'),
    _endTime        = dateSettings('end-time', 'time', 100, endSettingTime, 'HH:mm', 'outlined', 10, '00:00'),
    _modalStrtDt    = dateSettings('modal-strt-date', 'date', 140, new Date(), 'yyyy-MM-dd', 'outlined', null, '0000-00-00'),
    _modalEndDt     = dateSettings('modal-end-date', 'date', 140, new Date('2099-12-31'), 'yyyy-MM-dd', 'outlined', null, '0000-00-00'),
    _modalStrtTime  = dateSettings('modal-strt-time', 'time', 100, firstSettingTime, 'HH:mm', 'outlined', 10, '00:00'),
    _modalEndTime   = dateSettings('modal-end-time', 'time', 100, endSettingTime, 'HH:mm', 'outlined', 10, '00:00'),
]


const selectBoxArr = [
    dsplHH = selectSettings('dspl_hh', _dsplHHDataSource, 100, 4, 'outlined'),
    useYn = selectSettings('use_yn', _useYnDataSource, 100, 'Y', 'outlined'),
];

const btnArr = [
    _formSave    = btnSettings('form-save', '선택한 VMS에 동일 내용으로 저장', 'outlined', 'save', sameContentSaveEvent),
    _tableSave   = btnSettings('table-save', '선택한 VMS에 개별 내용으로 저장', 'outlined', 'save', seperateContentSaveEvent),
    _modalSave   = btnSettings('modal-save-Btn', '저장', 'outlined', 'save'),
    _modalX      = btnSettings('modal-cancle', '', '', 'close', modalCancleEvent),
    _modalCancle = btnSettings('modal-cancle-Btn', '닫기', 'outlined', 'close', modalCancleEvent),
]

$(()=>{
    window.onunload = ()=>{
        window.opener.$('.pop-up-modal').addClass('dpl-none');
    }
     //모달창 바디에 넣기
     $("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="modal-strt-date"></div>
             </div>
             <div>
                 <div class="modal-strt-time"></div>
             </div>
         </div>
         <div>
             <div>표출 종료 시각</div>
             <div>
                 <div class="modal-end-date"></div>
             </div>
             <div>
                 <div class="modal-end-time"></div>
             </div>
         </div>
     </div>`)
     );

    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");
    });
    
    selectBoxArr.map((item)=>{
        item.box = $("." + item.class).dxSelectBox({
            dataSource    : item.dataSource,
            width         : item.width,
            value         : item.value,
            stylingMode   : 'outlined'
        }).dxSelectBox("instance");
    });

    btnArr.map((item)=>{
        item.box = $("." + item.class).dxButton({
            text         : item.text,
            stylingMode  : item.stylingMode,
            icon         : item.icon,
        }).dxButton("instance");

        if(item.method)item.box.on('click',()=>item.method());
    })

    _formTable = $('.form-table').width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        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",
                        cssClass     : 'no-padding',
                    },
                    {
                        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");
   
    _listTable = $(".list-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : ['vms_ctlr_nmbr', 'vms_ctlr_id', 'phase'],
        editing                 :{
            mode            : 'batch',
            allowUpdating   : true,
        },
        toolbar                 :{
            visible         : false,
        },
        selection               : {
            mode            : 'multiple',
        },
        paging                  : {
            enabled         : false,
            pageSize        : 1,
        },
        scrolling: {
            mode: 'standard',
        },
        headerFilter            : {
            visible : true,
        },
        columns:[
                    {
                        dataField    : "vms_ctlr_nmbr",
                        caption      : "번호",
                        allowEditing : false,
                        sortIndex    : 0,
                        sortOrder    : 'asc',
                        alignment    : "center",
                    },
                    {
                        dataField    : "vms_ctlr_id",
                        caption      : "VMS ID",
                        allowEditing : false,
                        alignment    : "center",
                    },
                    {
                        dataField    : "vms_nm",
                        caption      : "VMS 명칭",
                        alignment    : "center",
                        allowEditing : false,
                        cellTemplate(c,e){
                            c.css('text-align','left');
                            c.text(e.displayValue)
                        }
                    },
                    {
                        dataField    : "dspl_hh",
                        caption      : "표출시간",
                        alignment    : "center",
                        lookup       : {
                            dataSource : _dsplHHDataSource,
                        }
                    },
                    {
                        dataField    : "dspl_strt_hh",
                        caption      : "시작시각",
                        allowEditing : false,
                        alignment    : "center",
                        dataType     : 'datetime',
                        format       : 'yyyy-MM-dd HH:mm',
                    },
                    {
                        dataField    : "dspl_end_hh",
                        caption      : "종료시각",
                        allowEditing : false,
                        alignment    : "center",
                        dataType     : 'datetime',
                        format       : 'yyyy-MM-dd HH:mm',
                    },
                    {
                        dataField    : "use_yn",
                        caption      : "사용",
                        alignment    : "center",
                        lookup       : {
                            dataSource : _useYnDataSource,
                        },
                    },
                    {
                        dataField    : "phase",
                        caption      : "Phase",
                        allowEditing : false,
                        alignment    : "center",
                    },
                    // {
                    //     dataField    : 'basic',
                    //     caption      : '기본',
                    //     alignment    : 'center',
                    //     cssClass     : 'no-padding',
                    // }
        ]
    }).dxDataGrid("instance").on('cellDblClick', (cell) => listDblClikcEvent(cell));

    fetchBaseData();

});
// 초기 데이터 로딩
async function fetchBaseData() {
    getDataAsync( _commonUri + '/' + encodeURIComponent(type) + '/A/' + encodeURIComponent(kind) + '/' + encodeURIComponent(form), fetchVmsListFunc);
    getDataAsync( '/api/vms/form/manage/' + form, fetchFormFunc);
}

//셀렉트 박스 세팅
function selectSettings(classNm, dataSource, width, value, stylingMode){
    const select = {
        box              : null,
        class            : classNm,
        dataSource       : dataSource,
        width            : width,
        value            : value,
        stylingMode      : stylingMode,
    }
    return select;
};

//데이트 박스 세팅
function dateSettings(classNm, type, width, value, displayFormat, stylingMode, interval, invalid){
 const  date  =  
    {
        box              : null,
        class            : classNm,
        type             : type,
        value            : value,
        interval         : interval,
        displayFormat    : displayFormat,
        width            : width,
        stylingMode      : stylingMode,
        invalid          : invalid,
    };

    return date;
};

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

//동일 내용으로 저장 이벤트
function sameContentSaveEvent(){
    const selectedData     = _listTable.getSelectedRowsData();
    let dspl_strt_hh       = null;
    let dspl_end_hh        = null;
    const insertUpdateData = [];
    let dateValArr         = dateValidation(_strtDt, _endDt, _strtTime, _endTime, dspl_strt_hh, dspl_end_hh );
    
    if (selectedData.length <= 0) {
        return alertWarning('선택된 VMS 목록이 없습니다.');
    }
    else if (!dateValArr) return false;
    else {
        selectedData.forEach(function(row){
            let updateData           = {};
            let selectedRow          = { ...row };
            console.log(selectedRow);
            selectedRow.dspl_strt_hh = getSendDate(dateValArr.dspl_strt_hh);
            selectedRow.dspl_end_hh  = getSendDate(dateValArr.dspl_end_hh);
            selectedRow.dspl_hh      = getValue(dsplHH.box);
            selectedRow.use_yn       = getValue(useYn.box);
            for( key in _updateData){
                updateData[key] = selectedRow[key] === undefined? _updateData[key] : selectedRow[key];
            }
            insertUpdateData.push(updateData);
        });
        confirmMessage("VMS 스케줄 일괄 관리<br>선택한 VMS에 대하여 스케줄 정보를 동일 내용으로 저장 하시겠습니까?").done((yes) => {
            if (yes === true) {
                const result = postInsertUpdate('/api/vms/schedule/common/batch', insertUpdateData);
                if(result > 0) {
                    alertConfirm('VMS 스케줄 일괄 관리<br>VMS 스케줄 정보를 저장 하였습니다.');
                    window.opener.scheduleTableListRefresh();
                    window.close();
                    return false;
                }
                //alertError('VMS 스케줄 일괄 관리<br>VMS 스케줄 정보가 저장 되지 않았습니다.');
            }
        });

    }
    
};

//개별 내용으로 저장 이벤트
function seperateContentSaveEvent(){
    const selectedData   = _listTable.getSelectedRowsData();
    let insertUpdateData = [];
    if( selectedData.length <= 0 ) {
        return alertWarning('선택된 VMS 목록이 없습니다.');
    }

    const changes = _listTable.option('editing.changes');
    if(changes.length > 0){
        for( idx in changes ){
            const data = changes[idx].data;
            for(key in data){
                if(data[key] === null){
                    alertWarning('입력하지 않은 항목이 있습니다. [ '+_listMap.get(key)+' ]');
                    return false;
                }
            }
        }
    };

    _listTable.saveEditData();

    selectedData.forEach(function(row){
        let updateData  = {};
        let selectedRow = { ...row };
        for( key in _updateData){
            if((key === 'dspl_strt_hh' || key === 'dspl_end_hh') && selectedRow[key])selectedRow[key] = getSendDate(selectedRow[key]);
            updateData[key] = selectedRow[key] === undefined? _updateData[key] : selectedRow[key];
        }
        insertUpdateData.push(updateData);
    });
    console.log(insertUpdateData);
    confirmMessage("VMS 스케줄 일괄 관리<br>선택한 VMS에 대하여 스케줄 정보를 저장 하시겠습니까?").done((yes) => {
        if (yes === true) {
            const result = postInsertUpdate('/api/vms/schedule/common/batch', insertUpdateData);
            if(result > 0) {
                alertConfirm('VMS 스케줄 일괄 관리<br>VMS 스케줄 정보를 저장 하였습니다.');
                window.opener.scheduleTableListRefresh();
                window.close();
                return false;
            }
            //return alertError('VMS 스케줄 일괄 관리<br>VMS 스케줄 정보가 저장 되지 않았습니다.');
        }
    });

};

//list table 데이터 수신
function fetchVmsListFunc(jsonData){
    const listData = [...jsonData];
    const selectkeyArr = [];
    if(listData.length > 0){
        
        listData.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));
            if (item.select_yn === 'Y') selectkeyArr.push({ vms_ctlr_nmbr : item.vms_ctlr_nmbr, vms_ctlr_id : item.vms_ctlr_id, phase : item.phase});
        });

        _listTable.option('dataSource', listData);
        _listTable.refresh().then(()=>{
            _listTable.selectRows(selectkeyArr, true);
        });
    }

    mapSettings( _listMap, _listTable);
};

//form table 데이터 수신
function fetchFormFunc(jsonData){
    const formData = [];
    formData.push({...jsonData});
    _formTable.option('dataSource', formData);
    _formTable.refresh();
    mapSettings( _formMap, _formTable);
};

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

//list table 더블 클릭 이벤트 
function listDblClikcEvent(cell){
    if(cell.column){
        if(cell.column.name === 'dspl_hh' || cell.column.name === 'use_yn') return;
        modalDateBtnInit(cell);
        $(".modal-background").css("display",'flex');
        _modalSave.box.off('click')
        _modalSave.box.on('click', () => modalSaveEvent(cell));
    }
};

//모달 시간 저장 이벤트
function modalSaveEvent(cell){
    let dspl_strt_hh = null;
    let dspl_end_hh  = null;

    let dateValArr = dateValidation(_modalStrtDt, _modalEndDt, _modalStrtTime, _modalEndTime, dspl_strt_hh, dspl_end_hh);
    if(!dateValArr) return false;
    //모달 창 닫기
    $(".modal-background").css("display","none");
   
    cell.component.cellValue(cell.rowIndex, 'dspl_strt_hh', dateValArr.dspl_strt_hh);
    cell.component.cellValue(cell.rowIndex, 'dspl_end_hh', dateValArr.dspl_end_hh);
}

//모달 데이트 박스 값 초기화
function modalDateBtnInit(cell){
    setValue(_modalStrtDt.box, cell.data.dspl_strt_hh); 
    setValue(_modalEndDt.box, cell.data.dspl_end_hh);
    setValue(_modalStrtTime.box, cell.data.dspl_strt_hh.getTime()); 
    setValue(_modalEndTime.box,  cell.data.dspl_end_hh.getTime()); 
}

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('시작 시각이 종료 시각보다 큽니다.');
        return false; 
     }
     return {dspl_strt_hh, dspl_end_hh};
}

function mapSettings(map, table){
    table.option('columns').map((column) => {
        map.set(column.dataField, column.caption);
    })
}