let symblTable       = null;
let commonUri        = "/api/vms/manager/symb-sbt1";
let symblData        = [];
let saveBtn          = null;
let cancleBtn        = null;
let addBtn           = null;
let delBtn           = null;
let editBtn          = null;
let imageNmText      = null;
let imageContentText = null;
let imageLinkText    = null;
let cellNum          = null;
let cellAplyBtn      = null;
let cellDelBtn       = null;
let underAplyBtn     = null;
let underDelBtn      = null;
let listData         = [];


//하단 버튼들
const btnArr    = [
    editBtn = {
        class        : "edit-btn", 
        box          : null, 
        option       : 80, 
        visible      : true, 
        disabled     : true, 
        selectdsb    : false, 
        click        : {
            visible  : true, 
            disabled : false, 
        }, 
        on           : {
            visible  : false, 
            disabled : false, 
        },
        addvsb       : false, 
        icon         : "edit", 
        text         : "편집", 
        method       : function(){
            editEvent();
        }
    }, 
    addBtn = {
        class        : "add-btn", 
        box          : null, 
        option       : 80, 
        visible      : true, 
        disabled     : false, 
        selectdsb    : false, 
        click        : {
            visible  : true, 
            disabled : false, 
        }, 
        on           : {
            visible  : true, 
            disabled : true, 
        },
        addvsb       : false, 
        icon         : "plus", 
        text         : "추가", 
        method       : function(){
            addEvent();
        }
    }, 
    delBtn = {
        class        : "del-btn", 
        box          : null, 
        option       : 80, 
        visible      : true, 
        disabled     : true, 
        selectdsb    : false, 
        click        : {
            visible  : true, 
            disabled : false, 
        }, 
        on           : {
            visible  : true, 
            disabled : true, 
        },
        addvsb       : false, 
        icon         : "minus", 
        text         : "삭제", 
        method       : function(){
            deleteEvent();
        }
    }, 
    cancleBtn = {
        class        : "cancle-btn", 
        box          : null, 
        option       : 80, 
        visible      : false, 
        disabled     : false, 
        selectdsb    : false, 
        click        : {
            visible  : false, 
            disabled : false, 
        }, 
        on           : {
            visible  : true, 
            disabled : false, 
        },
        addvsb       : true, 
        icon         : "close", 
        text         : "취소", 
        method       : function(){
            eventOff();
        }
    }, 
    saveBtn = {
        class        : "save-btn", 
        box          : null, 
        option       : 80, 
        disabled     : true, 
        selectdsb    : true, 
        click        : {
            visible  : true, 
            disabled : true, 
        }, 
        on           : {
            visible  : true, 
            disabled : false, 
        },
        adddsb       : false, 
        visible      : true, 
        icon         : "save", 
        text         : "저장",
    }, 
]

const cellSectArr = [
    cellNum = {
        box             : null,
        class           : 'cell-num',
        type            : 'number',
        width           : 80,
    },
    cellAplyBtn = {
        box             : null,
        class           : 'cell-aply-btn',
        type            : 'button',
        text            : '셀적용',
    },
    cellDelBtn = {
        box             : null,
        class           : 'cell-del-btn',
        type            : 'button',
        text            : '셀삭제',
        method          : function(){
            cellDelEvent();
        }
    },
    underAplyBtn = {
        box             : null,
        class           : 'under-aply-btn',
        type            : 'button',
        text            : '적용',
        icon            : 'arrowleft',
        method          : function(){
            insertEvent();
        }
    },
    underDelBtn = {
        box             : null,
        class           : 'under-del-btn',
        type            : 'button',
        text            : '삭제',
        icon            : 'arrowright',
        method          : function(){
            delEvent();
        }
    },

]

//우측 버튼들
const textArr    = [
    imageNmText = {
        class       : "image-nm", 
        box         : null, 
        option      : 120, 
        disabled    : true, 
        method      : function(){
        }
    }, 
    imageContentText = {
        class       : "image-content", 
        box         : null, 
        option      : 250,
        maxLength   : 200,
        disabled    : true, 
        method      : function(){
        }
    },
    imageLinkText = {
        class       : "image-link-text", 
        box         : null, 
        option      : 200, 
        disabled    : true, 
        method      : function(){
        }
    },
]

getData(commonUri, symblData);
getData(commonUri + '/figure-ifsc', listData);

$(()=>{
    
    //소통정보 테이블
    symblTable = $(".symbl-table").width('100%').height('100%').dxDataGrid({
        dataSource              : symblData[0],
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'symb_lib_nmbr',
        sorting  : {
            showSortIndexes : false,
            mode            : 'none',
        },
        selection: {
            mode: 'single', 
        }, 
        scrolling: {
            mode: 'standard', 
        },
        paging :{
            enabled: true,
            pageSize : 1000,
        },
        columns:[
            {
                dataField    : "symb_lib_nmbr", 
                caption      : "번호", 
                alignment    : "center", 
                sortIndex    : 0, 
                sortOrder    : "asc",
                width        : 90,
            }, 
            {
                dataField    : "imag_data", 
                caption      : "이미지", 
                alignment    : "center",
                cellTemplate(c,e){
                    c.css('padding','3px')
                    const imgSrc = 'data:image/png;base64,'+ e.displayValue
                    return c.append($('<img src="'+imgSrc+'">'));
                }
            }, 
        ], 
        onRowClick(e){
            srcInit( e.data );
            setValue(imageNmText.box, e.data.symb_lib_nmbr);
            setValue(imageContentText.box, e.data.symb_expl);
            dsblOffBtn(imgDown);
            const image = document.querySelector('.symbl-image');
            let ctx = canvasInit(image);
            ctx.fillStyle = 'red';

            btnArr.map((item)=>{
                item.box.option('visible', item.click.visible);
                item.box.option('disabled', item.click.disabled);
            });

            let cellData = [];
            getData(commonUri + '/' + e.data.symb_lib_nmbr, cellData);
            
            cellData[0].cells = cellSorting(cellData[0].cells)
            
            if (cellData.length > 0){
                cellData[0].cells.map((item) =>{
                    const color = colorList[item.cell_id - 1];
                    ctx.fillStyle = 'rgba(' + color + ')'
                    ctx.fillFlood(item.posx, item.posy);
                });
                cellTable.option('dataSource', cellData[0].cells);
            }

        }
    }).dxDataGrid("instance");

    cellTable = $(".cell-table").width('100%').height('100%').dxDataGrid({
        dataSource              : [], 
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        disabled                : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'cell_id',
        sorting  : {
            showSortIndexes : false,
            mode            : 'none',
        },
        editing                 : {
            confirmDelete : false, 
        }, 
        selection: {
            mode                : 'single', 
            showCheckBoxesMode  : 'onClick',
        }, 
        scrolling: {
            mode: 'standard', 
        },
        paging :{
            enabled: true,
            pageSize : 1000,
        },
        columns:[
            {
                dataField    : "cell_id", 
                caption      : "Cell", 
                alignment    : "center",
                width        : 50,
                cssClass     : 'no-padding',
            }, 
            {
                dataField    : "cell_region",
                caption      : "영역", 
                alignment    : "center", 
                cssClass     : 'no-padding',
                width        : 50,
                cellTemplate(c,e){
                    const color = colorList[e.data.cell_id - 1];
                    c.css({height: '1px'});
                    c.attr('id', 'fill-in');
                    return c.append($('<div>').css({width:'100%', height: '100%', backgroundColor: 'rgba(' + color + ')'}))
                }
            }, 
            {
                dataField    : "vms_ifsc_id", 
                caption      : "구간 ID", 
                alignment    : "center",
                width        : 70,
                cssClass     : 'no-padding',
            }, 
            {
                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      : "종점명", 
                alignment    : "center",
                cssClass     : 'no-padding',
                cellTemplate(c,e){
                    c.css('text-align', 'left');
                    c.text(e.displayValue);
                }
            }, 
        ],
        onRowClick(e){
            setValue(cellNum.box, e.data.cell_id);
            const image = document.querySelector('.symbl-image');
            let ctx = canvasInit(image);

            e.component.option('dataSource').map((item) => {
                const color = colorList[item.cell_id - 1];
                ctx.fillStyle = 'rgba(' + color + ')'
                ctx.fillFlood(item.posx, item.posy);
            });

            ctx.fillStyle = 'rgb(3 25 143)';
            ctx.fillFlood(e.data.posx, e.data.posy);

        }
      
    }).dxDataGrid("instance");
    
    listTable = $(".vms-table").width('100%').height('100%').dxDataGrid({
        dataSource              : listData[0], 
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        disabled                : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'vms_ifsc_id',
        sorting  : {
            showSortIndexes : false,
            mode            : 'none',
        },
        selection: {
            mode                : 'single', 
            showCheckBoxesMode  : 'onClick',
        }, 
        scrolling: {
            mode: 'standard', 
        },
        paging :{
            enabled: true,
            pageSize : 1000,
        },
        columns:[
            {
                dataField    : "vms_id", 
                caption      : "VMS ID", 
                alignment    : "center",
                groupIndex   : 0,
            }, 
            {
                dataField    : "vms_ifsc_id", 
                caption      : "구간 ID", 
                alignment    : "center",
                width        : 65,
                cssClass     : 'no-padding',
            }, 
            {
                dataField    : "vms_ifsc_nm", 
                caption      : "구간명", 
                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',
                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);
                }
            }, 
            
        ], 
      
    }).dxDataGrid("instance");
  
    //하단 버튼 세팅
    btnArr.map((item)=>{
        item.box = $("." + item.class).dxButton({
            icon              : item.icon, 
            width             : item.option, 
            text              : item.text, 
            visible           : item.visible, 
            disabled          : item.disabled,
            focusStateEnabled : false, 
            stylingMode       : 'outlined', 
            onClick(){
                if(item.method){
                    item.method();
                }
            }
        }).dxButton("instance")
    });

    //텍스트 상자 세팅
    textArr.map((item)=>{
        item.box = $("." + item.class).dxTextBox({
            width             : item.option, 
            disabled          : item.disabled, 
            stylingMode       : 'outlined',
            heigth            : 30,
            onClick(){
                if(item.method){
                    item.method();
                }
            }
        }).dxTextBox("instance")
    });

    //이미지 다운로드 버튼
    imgDown = $('.image-download').dxButton({
        icon        : 'download',
        text        : '이미지 파일 저장',
        stylingMode : 'outlined',
        disabled    : true,
        onClick(){
            document.querySelector('.image-download-link').click();
        }
    }).dxButton('instance');

    //이미지 업로드 버튼
    imgLink = $(".image-link").height('31px').dxButton({
        text          : '이미지 업로드',
        icon          : 'upload',
        stylingMode   : 'outlined',
        disabled      : true,
        onClick(){
            $('#image-file').val('');
            $('#image-file').click();
        }

    }).dxButton('instance');

    //이미지 파일 업로드 이벤트
    $('#image-file').on('change', function(){
        if($(this)[0].files[0] === undefined) return false;
        
        if(  $(this)[0].files[0].size > 150000){
            alertWarning('파일 사이즈는 150KBytes를 넘을 수 없습니다. 파일 용량을 줄여주세요')
            $(this).val('');
            return false;
        };
        
        let reader = new FileReader();
        
        reader.onload = function(e) {
            var arrayBuffer = e.target.result;
            
            arrayBufferToBase64(arrayBuffer).then( (byte8) =>{
                const image = document.querySelector('.symbl-image');
                image.setAttribute('src', null);
                image.setAttribute('src', "data:image/png;base64," + byte8);
                setTimeout(()=>canvasInit(image), 100);
            })
        }
        reader.readAsArrayBuffer($(this)[0].files[0]);
        setValue(imageLinkText.box, $(this)[0].files[0].name);
        cellTable.option('dataSource', []);
    });

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

    cellSettings();
});

//하단 편집 이벤트
function editEvent(){
    eventOn();
    $(".content-box").addClass('flex');
    saveBtn.box.off('click');
    saveBtn.box.on('click', ()=>saveEvent('edit'));
}

//하단 추가 이벤트
function addEvent(){
    let canvas = document.querySelector('.canvas');
    const image = document.querySelector('.symbl-image');
    canvas.getContext('2d').clearRect(0, 0, image.width, image.height);

    $('.symbl-image').attr('src', null);
    $('.image-download-link').attr('href', '');
    $('.image-download-link').attr('download', '');
    cellTable.option('dataSource', []);

    eventOn();
    
    let newId = [];

    textArr.map((item)=>{
        setValue(item.box, ''); 
    });

    getData(commonUri + '/new-id', newId);
    
    setValue(imageNmText.box, newId[0].new_id);
   
    saveBtn.box.off('click');
    saveBtn.box.on('click', ()=>saveEvent('add'));
}

//이벤트 시작
function eventOn(){

    btnArr.map((item)=>{
        item.box.option('visible', item.on.visible);
        item.box.option('disabled', item.on.disabled);
    });

    cellSectArr.map((item)=>{
        dsblOffBtn(item.box);
    });

    dsblOffBtn(imageContentText.box);
    dsblOnBtn(symblTable);
    dsblOnBtn(imgDown);
    dsblOffBtn(imgLink);
    dsblOffBtn(cellTable);
    dsblOffBtn(listTable);
    
    let canvas = document.querySelector('.canvas');

    $('.canvas').on('click', function(e){
        
         if(nullChecker($('.symbl-image').attr('src')) !== ""){
             const image = document.querySelector('.symbl-image');
             let ctx = canvasInit(image);

             if(cellTable.option('dataSource').length > 0){
                cellTable.option('dataSource').map((item)=>{
                    const color = colorList[item.cell_id - 1];
                    ctx.fillStyle = 'rgba(' + color + ')'
                    ctx.fillFlood(item.posx, item.posy);
                });
             };
             
             ctx.fillStyle = 'white';
             ctx.fillFlood(e.offsetX, e.offsetY);

             cellAplyBtn.box.off('click');
             cellAplyBtn.box.on('click', () => cellAplyEvent(ctx , e.offsetX, e.offsetY));;

         }
        
    })

}

//이벤트 취소
function eventOff(){
    const selectedData = symblTable.getSelectedRowsData();
    cellTable.option('focusedRowIndex', -1);
    listTable.option('focusedRowIndex', -1);
    cellTable.clearSelection();
    listTable.clearSelection();
    setValue(cellNum.box, null);
    cellTable.option('dataSource', []);

    $(".content-box").removeClass('flex');
    
    textArr.map((item)=>{
        setValue(item.box, ''); 
    });

    btnArr.map((item)=>{
        item.box.option('visible', item.visible);
        item.box.option('disabled', item.disabled);
    });

    cellSectArr.map((item)=>{
        dsblOnBtn(item.box);
    })

    $('.symbl-image').attr('src', null );
    $('.image-download-link').attr('href', null);
    $('.image-download-link').attr('download', null);
    $('.canvas').off('click');

    const image = document.querySelector('.symbl-image');
    let ctx = canvasInit(image);

    dsblOnBtn(imgLink);
    dsblOffBtn(symblTable);
    dsblOnBtn(imageContentText.box);
    dsblOnBtn(cellTable);
    dsblOnBtn(listTable);
    dsblOnBtn(imgDown);

    if(selectedData.length > 0){
        srcInit( selectedData[0] );
        
        ctx = canvasInit($('.symbl-image')[0]);

        let data = [];
        getData( commonUri + '/' + selectedData[0].symb_lib_nmbr, data);
        data[0].cells = cellSorting(data[0].cells);
        if(data.length > 0){
            cellNum.box.option('max', data[0].cells.length);
            data[0].cells.map((item) =>{
                const color = colorList[item.cell_id - 1];
                ctx.fillStyle = 'rgba(' + color + ')'
                ctx.fillFlood(item.posx, item.posy);
            });
            cellTable.option('dataSource', data[0].cells);
        }
        
        setValue(imageNmText.box, selectedData[0].symb_lib_nmbr);
        setValue(imageContentText.box, selectedData[0].symb_expl);
        dsblOffBtn(imgDown);

        btnArr.map((item)=>{
            item.box.option('visible', item.click.visible);
            item.box.option('disabled', item.click.disabled);
        });

        return false;
    };
    
   
}

//삭제 이벤트 우측
function deleteEvent(){
    const selectedData = symblTable.getSelectedRowsData()[0];
    const id = selectedData.symb_lib_nmbr;
    let usageData = [];
    getData(commonUri + '/usage/' + id, usageData);
    
    if(usageData[0] && usageData[0].count > 0){
        return alertWarning('삭제할 이미지 정보가 VMS 폼에서 사용되고 있습니다.<br>먼저 해당 폼에서 삭제해주시기 바랍니다.');
    }
    
    const result = deleteData(commonUri, id);
    if(result > 0){
        delResultMsg('VMS 소통정보 배경 이미지');
        symblData = refresh( symblTable , symblData, commonUri );
        symblTable.refresh();
        symblTable.option('focusedRowIndex', -1);
        symblTable.clearSelection();
        eventOff();
        return false;
    }
    //return alertError('VMS 소통정보 배경 이미지 정보가 삭제 되지 않았습니다.')
}

//저장 이벤트
function saveEvent(type){
    let updateData = {
        cells: [],
        del_yn : null,
        rgst_dt: null,
        imag_data: null,
        imag_size: null,
        symb_expl: null,
        symb_lib_nmbr: null,
        updt_dt : null,
    };
    switch (true) {
        case nullChecker(getValue(imageNmText.box)) === "" :
            alertWarning('이미지 번호를 입력해주세요', null, imageNmText.box);
            break;
        case nullChecker(getValue(imageContentText.box)) === "" :
            alertWarning('이미지 설명을 입력해주세요', null, imageContentText.box);
            break;
        case getByteLength(getValue(imageContentText.box)) > imageContentText.maxLength :
            alertWarning('이미지 설명을 ' + imageContentText.maxLength + ' 바이트 입력해주세요', null, imageContentText.box);
            break;
        case nullChecker($('.symbl-image').attr('src')) === "" :
            alertWarning('이미지를 업로드 해주세요', null, imgLink);
            break;
        case cellTable.option('dataSource').length <= 0 :
            alertWarning('Cell을 추가해주세요', null, cellTable);
            break;
        default:
            const now = getSendDate(new Date());
            updateData['cells']         = cellTable.option('dataSource');
            updateData['rgst_dt']       = now;
            updateData['symb_expl']     = getValue(imageContentText.box);
            updateData['imag_data']     = $('.symbl-image').attr('src').substring(22, $('.symbl-image').attr('src').length);
            updateData['symb_lib_nmbr'] = getValue(imageNmText.box);
            updateData['del_yn']        = "N";

            for( idx in updateData['cells']){
                if(updateData['cells'][idx]['vms_ifsc_id'] === null) {
                    alertWarning('VMS 정보제공구간 목록을 선택해주세요')
                    return false;
                }
            }

            if (type === 'edit'){
                const selectedData = symblTable.getSelectedRowsData()[0];
                updateData['rgst_dt'] = selectedData['rgst_dt'];
                updateData['imag_size'] = updateData['imag_data'] === selectedData['imag_data']
                                         ? selectedData['imag_size'] : $('#image-file')[0].files[0].size;
                let result = false;
                
                for ( key in selectedData ){
                    if ( updateData[key] && selectedData[key] !== updateData[key] ) {
                        result = true;
                    }
                };

                let data = [];
                getData(commonUri + '/' + updateData['symb_lib_nmbr'], data);
                
                data[0].cells = cellSorting(data[0].cells);

                if ( data.length > 0 && data[0].cells.length === updateData['cells'].length){
                    for (idx in updateData['cells']){
                        for (key in updateData['cells'][idx]){
                            if (updateData['cells'][idx][key] !== data[0].cells[idx][key]){
                                result = true;
                            } 
                        }
                     }
                     
                     if (!result){
                         alertWarning('변경 된 소통정보 배경 이미지 정보가 없습니다.');
                         break
                     }
                }
                
            }
            else {
                updateData['imag_size'] = $('#image-file')[0].files[0].size;
            }
            updateData['updt_dt'] = now;
            const result = postInsertUpdate(commonUri + '/' + getValue(imageNmText.box) , updateData);
            
            if ( result > 0 ){
                insResultMsg('VMS 소통정보 배경 이미지');
                symblData = [];
                getData(commonUri, symblData);
                symblTable.option('dataSource', symblData[0]);
                symblTable.refresh().done(() => {
                    const key = updateData.symb_lib_nmbr;
                    symblTable.clearSelection();
                    symblTable.selectRows(key).done(()=>{
                        symblTable.option('focusedRowKey', key);
                        symblTable.navigateToRow(key);
                        eventOff();
                    });
                });
            }
            break;
    }

    
}

function cellSorting(data){
    data.sort(function(a, b){
        return a.cell_id > b.cell_id ? 1 : -1;
    })
    return data;
}

//바이트 변환 이벤트
function arrayBufferToBase64(buffer) {
    return new Promise( (succ,fail)=>{
        try {
            var binary = '';
            const bytes = new Uint8Array(buffer);
            const len = bytes.byteLength;
            for (let i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            succ( window.btoa(binary) );	    	
        } catch(e){
            console.log('to big....');
            fail(e);
        }	
    });
}

function canvasInit(image){
    let canvas = document.querySelector('.canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    $('.canvas').css('width', image.width);
    $('.canvas').css('height', image.height);
    canvas.getContext('2d').clearRect(0, 0, image.width, image.height);
    let ctx = canvas.getContext('2d');
    ctx.drawImage(image, 0, 0 , image.width, image.height);
    return ctx;
}

function srcInit( data ){
    $('.symbl-image').attr('src', "data:image/png;base64," + data.imag_data );
    $('.image-download-link').attr('href', "data:image/png;base64," + data.imag_data);
    $('.image-download-link').attr('download', data.symb_lib_nmbr +'.bmp');
}

function cellSettings(){
    cellSectArr.map((item)=>{
        switch (item.type) {
            case 'number':
                item.box = $('.' + item.class).dxNumberBox({
                    value           : null,
                    min             : 1,
                    stylingMode     : 'outlined',
                    width           : item.width,
                    disabled        : true,
                    height          : 28,
                    readOnly        : true,
                    showSpinButtons : true,
                }).dxNumberBox('instance');
                break;
        
            default:
                item.box = $('.' + item.class).dxButton({
                    stylingMode     : 'outlined',
                    width           : item.width,
                    height          : 30,
                    disabled        : true,
                    icon            : item.icon,
                    text            : item.text,
                    onClick(){
                        if(item.method){
                            item.method();
                        }
                    }
                }).dxButton('instance');
                break;
        }
    })
}

//가운데 적용 이벤트
function insertEvent(){
    //테이블 선택이 있다면 실행
    const listData = listTable.getSelectedRowsData();
    const key = cellTable.getSelectedRowKeys();
    if(listData.length > 0 && key.length > 0){
        const rowIndex = cellTable.getRowIndexByKey(key[0]);
        cellTable.cellValue(rowIndex, 'vms_ifsc_id', listData[0].vms_ifsc_id);
        cellTable.cellValue(rowIndex, 'dspl_strt_node_nm', listData[0].dspl_strt_node_nm);
        cellTable.cellValue(rowIndex, 'dspl_end_node_nm', listData[0].dspl_end_node_nm);
        cellTable.saveEditData();
        cellTable.refresh();
    }
}

//가운데 삭제 이벤트
function delEvent(){
    //가운데 테이블 선택 값이 있을 경우 실행
    const key = cellTable.getSelectedRowKeys();
    if ( key.length > 0 ){
        const rowIndex = cellTable.getRowIndexByKey(key[0]);
        cellTable.cellValue(rowIndex, 'vms_ifsc_id', null);
        cellTable.cellValue(rowIndex, 'dspl_strt_node_nm', null);
        cellTable.cellValue(rowIndex, 'dspl_end_node_nm', null);
        cellTable.saveEditData();
        cellTable.refresh();
    }
}

//셀 적용 이벤트
function cellAplyEvent(ctx, x, y){
    let dataSource = cellTable.option('dataSource');
                
    const insertData = {
        symb_lib_nmbr     : getValue(imageNmText.box), 
        cell_id           : dataSource.length + 1,
        posx              : x,
        posy              : y,
        vms_ifsc_id       : null,
        dspl_strt_node_nm : null,
        dspl_end_node_nm  : null,
    };

    dataSource.push(insertData);
    cellTable.option('dataSource', dataSource);
    cellTable.refresh;
    
    setValue(cellNum.box, insertData.cell_id);
    

    cellTable.option('dataSource').map((item)=>{

        const color = colorList[item.cell_id - 1];
        ctx.fillStyle = 'rgba(' + color + ')'
        ctx.fillFlood(item.posx, item.posy);

    });

}

//셀 삭제 이벤트
function cellDelEvent(){
    const key = cellTable.getSelectedRowKeys();
    if(key.length <= 0) return false;

    let rowIndex = cellTable.getRowIndexByKey(key[0]);  
    cellTable.deleteRow(rowIndex);
    cellTable.refresh();

    let dataSource = [...cellTable.option("dataSource")];
     
    dataSource = cellSorting(dataSource)
    
    let cnt = 1;
    const image = $('.symbl-image')[0];
    let ctx = canvasInit(image);
    
    dataSource.map((item)=>{
        item.cell_id = item.cell_id === cnt? item.cell_id : cnt;
        cnt ++;
        const color = colorList[item.cell_id - 1];
        ctx.fillStyle = 'rgba(' + color + ')'
        ctx.fillFlood(item.posx, item.posy);
    })
    
    //테이블에 데이터 세팅
    cellTable.option('dataSource', dataSource);
    cellTable.clearSelection();
}

