
let gropMenuAutrData  = [];
let updateData        = [];
let gropMenuAutrTable = null;
let applyBtn          = null;
let searchBtn         = null;
const gropMenuAthrUri = "/api/database/grop-menu-athr";
const _pageName        = '운영자 그룹 메뉴 관리';

$(()=>{
    //상단 조회 버튼
    searchBtn = $(".search-button").dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        height:'30px',
        width: '80px',
        onClick(){
            fetchListData();
        }
    }).dxButton("instance")
    
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance")
    
    //연계기관정보 관리 테이블
    gropMenuAutrTable = $(".grop-menu-athr-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
           mode : 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible : true,
        },
        grouping: {
            autoExpandAll : true,
        },
        scrolling: {
            mode : 'virtual',
        },
        groupPanel:{
            visible         : true,
            emptyPanelText  : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        export:{
            enabled : true,
            texts   : {
                exportAll :"엑셀 파일",
            },
        },
        sorting: {
            showSortIndexes: false,
        },
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        columns:[
            {   
                dataField    : "grop_nm",
                caption      : "운영자 그룹",
                alignment    : "center",
                allowEditing : false,
                sortIndex    : 1,
                sortOrder    : "asc",
                groupIndex   : 1,
                validationRules: [{ type: 'required' }],
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                },
            },
            {
                dataField   : "oper_syst_nm",
                caption     : "메뉴 그룹",
                alignment   : "center",
                allowEditing : false,
                groupIndex   : 2,
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {
                dataField    : "oper_syst_menu_nm",
                caption      : "메뉴명",
                alignment    : "center",
                allowEditing : false,
                allowEditing : false,
                sortIndex    : 2,
                sortOrder    : 'asc',
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {   
                dataField   : "athr_yn",
                caption     : "메뉴권한",
                alignment   : "center",
                lookup      : {
                    dataSource:[
                        {
                            athr_yn:"Y", 
                            athr_yn_desc:'[Y] 권한있음',
                        }
                        ,
                        {
                            athr_yn:"N",
                            athr_yn_desc:'[N] 권한없음',
                        },
                    ],
                    valueExpr:"athr_yn",
                    displayExpr:"athr_yn_desc"
                },
                cellTemplate(c,e){
                    if(e.displayValue === '[N] 권한없음'){
                        c.css('background-color', '#ff0000');
                    }
                    c.text(e.displayValue);
                }
            },
        ],
        onRowUpdated(e){
            updateData.push(e.data);
        },
    }).dxDataGrid("instance");
    
    //하단 편집 버튼
    editBtn = $(".edit-btn").dxButton({
        stylingMode:'outlined',
        text:'편집',
        icon:'edit',
        onClick(){
            eventOn();
        }
    }).dxButton("instance")
    
    //하단 취소 버튼
    editCancleBtn = $(".edit-cancle-btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        visible:false,
        icon:'close',
        onClick(){
            setTimeout(()=>{
                if (updateData.length > 0) {
                    confirmMessage('변경 하신 데이터가 있습니다. 취소 하시겠습니까?').done((yes) => {
                        if (yes === true) {
                            eventOff();
                        }
                    });
                }
                else {
                    eventOff();
                }
            }, 300);
        }
    }).dxButton("instance")
    
    
    
    //하단 적용 버튼
    applyBtn = $(".apply-btn").dxButton({
        stylingMode:'outlined',
        text:'적용',
        disabled:true,
        icon:'save',
        onClick(){
            gropMenuAutrTable.saveEditData().done(function(){
                let updateDataFommat = [];
                let result = 0;
                if(updateData.length > 0){
                    updateData.map((item) =>{
                        updateDataFommat.push(
                            {
                                athr_yn          : item.athr_yn,
                                grop_id          : item.grop_id,
                                opersyst_menu_id : item.opersyst_menu_id,
                            }
                        )
                    })
                    result = postInsertUpdate(gropMenuAthrUri,updateDataFommat);
                }
                if(result > 0){
                    refresh(gropMenuAutrTable,gropMenuAutrData,gropMenuAthrUri);
                    eventOff();
                    alertConfirm("입력한 정보를 저장하였습니다.");
                    return;
                }
                //return alertError("입력한 정보가 저정되지 않았습니다.");
            });
        }
    }).dxButton("instance")
    
    fetchListData();
})

function fetchListData(){
    getDataAsync(gropMenuAthrUri, (jsonData)=>{
        gropMenuAutrData = jsonData;
        gropMenuAutrTable.option('dataSource', gropMenuAutrData);
    });
}


function eventOff(){
    showBtn(editBtn);
    hideBtn(editCancleBtn);
    dsblOnBtn(applyBtn);
    dsblOffBtn(searchBtn);
    gropMenuAutrTable.option("editing",{
        mode:"cell",
        allowUpdating:false,
    });
    
    fetchListData();
    updateData = [];
}
function eventOn(){
    showBtn(editCancleBtn);
    hideBtn(editBtn);
    dsblOnBtn(searchBtn);
    dsblOffBtn(applyBtn);
    gropMenuAutrTable.option("editing",{
        mode:'cell',
        allowUpdating: true
    })
}