let _webUserInfrData     = [];
let updateData       = [];
let insertData       = [];
let delData          = [];
let dayTypeArr       = [];
let userGropData     = [];
let userOperSystData = [];
let userInfrTable    = null;
let modalText        = null;
let modalCancleBtn   = null;
let modalSelectBtn   = null;
let addBtn           = null;
let delBtn           = null;
let applyBtn         = null;
let modalDate        = null;
let searchBtn        = null;
const _pageName      = '홈페이지 운영자 관리';
const _apiUri        = "/api/database/web-member";
const checkByteArr   = [
    ['pwd', '비밀번호', 100, true],
    ['name', '사용자명', 15, true],
    ['contact_num', '연락처', 20, false],
    ['ip_address', '관리자 계정접속 가능 IP', 200, false],
]

$(()=>{
    $("body").append(modalDiv);
    $(".modal-title").prepend($('<div>홈페이지 운영자 ID</div>'));
    $(".modal-background").css("display",'none'); 
    $(".modal-content").append($("<div class='modal-content-title'>").html("신규 운영자 ID를 입력하세요"),$("<div class='modal-text'>"))
    
    //상단 조회 버튼
    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")
    
    //웹 사용자 관리 테이블
    userInfrTable = $(".user-infr-table").width('100%').height('100%').dxDataGrid({
        dataSource              : _webUserInfrData[0],
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'email',
        selection: {
           mode : 'none',
        },
        // filterRow: {
        //     visible: true,
        //     applyFilter: "auto",
        //     showOperationChooser:false,
        // },
        // headerFilter: {
        //     visible : false,
        // },
        grouping: {
            autoExpandAll : true,
        },
        scrolling: {
            mode : 'virtual',
        },
        groupPanel:{
            visible         : true,
            emptyPanelText  : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        export:{
            enabled : true,
            texts   : {
                exportAll :"엑셀 파일",
            },
        },
        sorting:{
            mode: 'none',
        },
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        columns:[
            {   
                dataField    : "email",
                caption      : "ID",
                alignment    : "center",
                allowEditing : false,
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {
                dataField   : "pwd",
                caption     : "비밀번호",
                alignment   : "center",
                width       : 200,
                editorOptions: {
                    mode: "password",
                    dataType : 'string',
                    maxLength : 60,
                },
                customizeText: function(e){
                    let pwd = "";
                    if (e.value) {
                        for(let ii = 0; ii < e.value.length; ii++){
                            pwd += '*';
                        }
                    }
                    return pwd;
                }
            },
            {
                dataField   : "name",
                caption     : "사용자명",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 15,
                },
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {   
                dataField   : "contact_num",
                caption     : "연락처",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 20,
                },
            },
            {   
                dataField   : "ip_address",
                caption     : "홈페이지 운영자 계정접속 가능 IP",
                alignment   : "center",
                width       : 300,
                editorOptions: {
                    dataType : 'string',
                    maxLength : 200,
                },
            },
            {   
                dataField   : "login_fail_count",
                caption     : "로그인 실패 횟수",
                alignment   : "center",
                dataType    : 'number',
                visible     : false,
                width       : 130,
            },
            {   
                dataField    : "is_account_lock",
                caption      : "계정 잠김 여부",
                alignment    : "center",
                allowEditing : false,
                width        : 130,
                lookup       : {
                    dataSource : [
                        {
                            is_account_lock : 'Y',
                            is_account_lock_desc : 'ON', 
                        },
                        {
                            is_account_lock : 'N',
                            is_account_lock_desc : 'OFF',
                        }
                    ],
                    displayExpr : 'is_account_lock_desc',
                    valueExpr   : 'is_account_lock',
                }
            },
          
        ],
        onCellClick(e){
            listCellClickLockOff(e);
        },
        onRowClick(e){
        },
        onRowUpdated(e){
            updateData.push(e.data);
        },
        onRowInserted(e){
            insertData.push(e.data);
        },
        onSelectionChanged(e){
            delData = e.selectedRowsData;
        }
    }).dxDataGrid("instance");
    
    //하단 편집 버튼
    editBtn = $(".edit-btn").dxButton({
        stylingMode:'outlined',
        text:'편집',
        icon:'edit',
        onClick(){
            eventOn();
            applyBtn.off('click');
            applyBtn.on('click', () => saveEvent('edit'));
        }
    }).dxButton("instance")
    
    //하단 취소 버튼
    editCancleBtn = $(".edit-cancle-btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        visible:false,
        icon:'close',
        onClick(){
            eventOff();
        }
    }).dxButton("instance")
    
    //추가 버튼
    addBtn = $(".add-btn").dxButton({
        stylingMode:'outlined',
        text:'추가',
        disabled:true,
        icon:'plus',
        onClick(){
            $(".modal-background").css("display","flex");
            setValue(modalText, '');
            modalText.focus();
        }
    }).dxButton("instance")
    
    //삭제 버튼
    delBtn = $(".del-btn").dxButton({
        stylingMode:'outlined',
        text:'삭제',
        disabled:true,
        icon:'minus',
        onClick(){
            userInfrTable.option("selection",{
                mode:'multiple',
            });
            
            userInfrTable.option('editing', {
                mode:'none',
                allowUpdating : false,
            });

            dsblOnBtn(addBtn);
            dsblOnBtn(delBtn);
        }
    }).dxButton("instance")
    
    //하단 적용 버튼
    applyBtn = $(".apply-btn").dxButton({
        stylingMode:'outlined',
        text:'적용',
        disabled:true,
        icon:'save',
    }).dxButton("instance")
    
    //신규 ID 모달 선택 버튼
    modalSelectBtn = $(".modal-save-Btn").dxButton({
        stylingMode:'outlined',
        text:'선택',
        icon:'check',
        onClick(){
            addUserId(getValue(modalText));
        },
    }).dxButton("instance")
    
    modalText = $(".modal-text").dxTextBox({
        width:"250px",
        stylingMode: 'outlined',
        maxLength:'30',
        onEnterKey(e){
           addUserId(e.component._changedValue)
        }
    }).dxTextBox("instance");

    //신규 ID 모달 취소 버튼
    $(".modal-cancle-Btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        icon:'close',
        onClick(){
            modalCancel();
        },
    }).dxButton("instance");
    
    //신규 ID 선택 모달 x 버튼
    modalCancleBtn=$(".modal-cancle").dxButton({
        stylingMode:'text',
        icon:'close',
        onClick(){
            modalCancel();
        }
    }).dxButton("instance");

    fetchListData();
});

function fetchListData(){
    getDataAsync(_apiUri, (jsonData)=>{
        _webUserInfrData = jsonData;
        userInfrTable.option('dataSource', _webUserInfrData);
    });
}
function getUseEmailId(){
    let idData = [];
    if (_webUserInfrData.length > 0){
        _webUserInfrData.map((item) =>{
            idData.push(item.email);
        });
    };
    return idData;
}

function listCellClickLockOff(info){
    if (info.column && info.column.caption === '계정 잠김 여부' && info.value === 'Y'){
        confirmMessage('계정 잠김 상태를 해제 하시겠습니까?').done((yes)=>{
            if (yes === true) {
                const result = putUpdate(_apiUri + '/' + info.data.email);
                if (result > 0) {
                    fetchListData();
                    return alertConfirm('ID : ' + info.data.email  + '<br>계정 잠김 상태가 해제 되었습니다.')
                }
            }
        })
    }
}

function modalCancel(){
    $(".modal-background").css("display",'none');
}

function eventOn(){
    showBtn(editCancleBtn);
    hideBtn(editBtn);
    dsblOffBtn(applyBtn);
    dsblOffBtn(addBtn);
    dsblOffBtn(delBtn);
    dsblOnBtn(searchBtn);

    userInfrTable.option("editing",{
        mode                    : 'batch',
        allowUpdating           : true,
        selectTextOnEditStart   : true,
    });
    userInfrTable.option('toolbar.visible', false);
};

function eventOff(){
    if (userInfrTable.hasEditData() || delData.length > 0){
        confirmMessage("변경 하신 운영자 정보가 있습니다. 취소 하시겠습니까?").done((yes) => {
            if (yes === true) {
                resetState();
            }
        });
    }
    else {
        resetState();
    }
}

function resetState(){
    showBtn(editBtn);
    hideBtn(editCancleBtn);
    dsblOnBtn(applyBtn);
    dsblOnBtn(delBtn);
    dsblOnBtn(addBtn);
    dsblOffBtn(searchBtn);

    userInfrTable.option("editing",{
        mode :"none",
        allowUpdating:false,
    });
    
    userInfrTable.option('selection', {
        mode : 'single',
    });
    
    fetchListData();
    userInfrTable.option('toolbar.visible', true);
}

function addUserId(value){
    const id = value;
    let idData = getUseEmailId();
    if (!id) {
        alertWarning("ID를 입력해 주세요", null, modalText);
    }
    else if (idData.includes(id)) {
        alertWarning("이미 사용중인 ID 입니다.", null, modalText);
    }
    else if (getByteLength(id) > 50) {
        alertWarning("ID를 50바이트 이내로 입력해주세요.", null, modalText);
    }
    else {
        userInfrTable.addRow();
        userInfrTable.option('editing.changes',[{
            key  : userInfrTable.option('editing.editRowKey'),  
            data :{
                email             : modalText.option("value"),
                password          : "",
                username          : null,
                contactnum        : null,
                userauth          : null,
                question          : null,
                answer            : null,
                regdate           : null,
                login_fail_count  : 0,
                is_account_lock   : 'N',
                ip_address        : null,
                del_yn            : 'N',
            },
            type:"insert",
        }]);
        $(".modal-background").css("display","none");
        dsblOnBtn(delBtn);
        dsblOnBtn(addBtn);
        applyBtn.off('click');
        applyBtn.on('click', ()=>saveEvent());
    }
}

function saveEvent(type) {
    if (!userInfrTable.hasEditData() && delData.length === 0){
        alertWarning("변경하신 데이터가 없습니다.")   
    }
    else {
        let updateDataArr = [];

        if (userInfrTable.hasEditData()) {
            userInfrTable.option('editing.changes').map((item)=>{
                userInfrTable.byKey(item.key).done(function(obj) {
                    const data = {...obj};
                    if (!data.reg_dt) {
                        data.reg_dt = getSendDate(new Date());
                    }
                    updateDataArr.push(data);
                });
            });
            for ( let obj of updateDataArr ) {
                const frontContent = "ID : " + obj.email + "<br>";
                for (let checkByte of checkByteArr) {
                    const value = obj[checkByte[0]];
                    const empty = nullChecker(value) === '';
                    if (empty) {
                        if (checkByte[3]) {
                            return alertWarning(frontContent + "필수 항목을 입력해주세요. [ " + checkByte[1] +" ]");
                        }
                        obj[checkByte[0]] = null;
                    }
                    else {
                        if (getByteLength(value) > checkByte[2]) {
                            return alertWarning( frontContent + checkByte[2]+ " 바이트 이내로 입력해주세요. [ " + checkByte[1] + " ]");
                        }
                    }
                }
            }
            confirmMessage("변경하신 홈페이지 운영자 정보를 적용 하시겠습니까?").done((yes) => {
                if (yes === true) {
                    let result = postInsertUpdate(_apiUri, updateDataArr);
                    if (result > 0) {
                        saveEnd('홈페이지 운영자 정보가 수정 되었습니다.');
                    }
                }
            });
        }
        else if( delData.length > 0){
            confirmMessage("선택하신 홈페이지 운영자 정보를 삭제하시겠습니까?").done((yes) => {
                if (yes === true) {
                    let delIdArr = [];
                    
                    delData.map((item)=>{
                        delIdArr.push(item.email);
                    });
                    console.log(delIdArr);
                    let result = deleteDataIds(_apiUri, delIdArr);
                    
                    if (result > 0) {
                        saveEnd('선택하신 홈페이지 운영자 정보가 삭제 되었습니다.');
                    }
                }
            });

        }
            
            
    }
}

function saveEnd(text){
    showBtn(editBtn);
    hideBtn(editCancleBtn);
    dsblOnBtn(applyBtn);
    dsblOnBtn(delBtn);
    dsblOnBtn(addBtn);
    dsblOffBtn(searchBtn);
    
    userInfrTable.option('toolbar.visible', true);

    userInfrTable.option("editing",{
        mode:"none",
        allowUpdating:false,
    });

    userInfrTable.option("selection", {
        mode: "single",
    });
    
    fetchListData();

    alertConfirm(text);
}