let userInfrData = [];
let delData = [];
let dayTypeArr = [];
let userGropData = [];
let userOperSystData = [];
let _listTable = 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 userInfrUri = "/api/database/user-infr";
const checkByteArr = [
    [ 'pwd', '비밀번호', 64, true],
    [ 'name', '성명', 30, true],
    [ 'comp', '회사', 50, false],
    [ 'tel', '전화번호', 128, false],
    [ 'addr', '주소', 200, false],
    [ 'mobile', '이동전화', 128, false],
    [ 'email', '이메일', 128, false],
]

getData("/api/database/user-infr/user-grop", userGropData);
getData("/api/database/user-infr/oper-syst", userOperSystData);

console.log(userGropData);
$(() => {
    $("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");

    //운영자 관리 테이블
    _listTable = $(".user-infr-table").width('100%').height('100%').dxDataGrid({
        dataSource: null,
        allowColumnReordering: true,
        showColumnLines: true,
        allowColumnResizing: true,
        showBorders: true,
        rowAlternationEnabled: true,
        columnAutoWidth: true,
        focusedRowEnabled: true,
        noDataText: '표출할 정보가 없습니다.',
        keyExpr: 'user_id',
        selection: {
            mode: 'none',
        },
        // filterRow: {
        //     visible: true,
        //     applyFilter: "auto",
        //     showOperationChooser: false,
        // },
        // headerFilter: {
        //     visible: true,
        // },
        grouping: {
            autoExpandAll: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        export: {
            enabled: true,
            texts: {
                exportAll: "엑셀 파일",
            },
        },
        onExporting(e) {
            gridExcellExporting(e, _pageName);
        },
        columns: [
            {
                dataField: "user_id",
                caption: "ID",
                alignment: "center",
                allowEditing: false,
                sortIndex: 0,
                sortOrder: "asc",
                cellTemplate(c, e) {
                    let result = nullChecker(e.displayValue);
                    return $('<div style="text-align: left;">' + result + '</div>')
                }
            },
            {
                dataField: "pwd",
                caption: "비밀번호",
                alignment: "center",
                editorOptions: {
                    mode: "password",
                    dataType : 'string',
                    maxLength : 64,
                },
                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 : 30,
                },
                cellTemplate(c, e) {
                    let result = nullChecker(e.displayValue);
                    return $('<div style="text-align: left;">' + result + '</div>')
                }
            },
            {
                dataField: "grop_id",
                caption: "운영자그룹",
                alignment: "center",
                lookup: {
                    dataSource: userGropData[0],
                    valueExpr: "grop_id",
                    displayExpr: "grop_desc",
                },
                cellTemplate(c, e) {
                    let result = nullChecker(e.displayValue);
                    return $('<div style="text-align: left;">' + result + '</div>')
                }
            },
            {
                dataField: "oper_syst_id",
                caption: "운영시스템ID",
                alignment: "center",
                lookup: {
                    dataSource: userOperSystData[0],
                    valueExpr: "oper_syst_id",
                    displayExpr: "oper_syst_name"
                },
                cellTemplate(c, e) {
                    let result = nullChecker(e.displayValue);
                    return $('<div style="text-align: left;">' + result + '</div>')
                }
            },
            {
                dataField: "comp",
                caption: "회사",
                alignment: "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 50,
                },
            },
            {
                dataField: "tel",
                caption: "전화번호",
                alignment: "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 128,
                },
            },
            {
                dataField: "addr",
                caption: "주소",
                alignment: "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 200,
                },
            },
            {
                dataField: "mobile",
                caption: "이동전화",
                alignment: "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 128,
                },
            },
            {
                dataField: "email",
                caption: "이메일",
                alignment: "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 128,
                },
            },

            {
                dataField: "del_yn",
                caption: "삭제 여부",
                alignment: "center",
                visible :false,
                lookup: {
                    dataSource: ['Y', 'N'],
                }
            },
        ],
        onSelectionChanged(e) {
            delData = e.selectedRowsData;
        }
    }).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() {
            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() {
            _listTable.option("selection", {
                mode: 'multiple',
            });

            _listTable.option('editing', {
                mode: 'none',
                allowUpdating: false,
            });

            dsblOnBtn(addBtn);
            dsblOnBtn(delBtn);
        }
    }).dxButton("instance");

    //하단 적용 버튼
    applyBtn = $(".apply-btn").dxButton({
        stylingMode: 'outlined',
        text: '적용',
        disabled: true,
        icon: 'save',
        onClick() {
            saveEvent();
        }
    }).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: '20',
        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(userInfrUri, (jsonData)=>{
        userInfrData = jsonData;
        _listTable.option('dataSource', userInfrData);
    });

}

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

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

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

function eventOff() {
    if (_listTable.hasEditData() || delData.length > 0) {
        confirmMessage("변경 하신 운영자 정보가 있습니다. 취소 하시겠습니까?").done((yes) => {
            if (yes === true) {
                showBtn(editBtn);
                hideBtn(editCancleBtn);
                dsblOnBtn(applyBtn);
                dsblOnBtn(delBtn);
                dsblOnBtn(addBtn);
                dsblOffBtn(searchBtn);

                _listTable.option("editing", {
                    mode: "none",
                    allowUpdating: false,
                });
                _listTable.option('selection', {
                    mode: 'none',
                });
                _listTable.clearSelection();

                fetchListData();

                _listTable.option('toolbar.visible', true);
            }
        });
    } else {

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

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

        _listTable.option('selection', {
            mode: 'single',
        });

        fetchListData();

        _listTable.option('toolbar.visible', true);
    }
}
function getUseIdArr(){
    let idData = [];
    if (userInfrData.length > 0) {
        userInfrData.map((item) => {
            idData.push(item.user_id);
        });
    }
    return idData;
}
function addUserId(value) {
    const id = value;
    let idData = getUseIdArr();
    if (nullChecker(id) === '') {
        alertWarning("ID를 입력해 주세요", null, modalText);
    }
    else if (idData.includes(id)) {
        alertWarning("이미 사용중인 ID 입니다.", null, modalText);
    }
    else if (getByteLength(id) > 20) {
        alertWarning("ID를 20 바이트 이내로 입력해주세요.", null, modalText);
    }
    else {
        _listTable.addRow();
        _listTable.option('editing.changes', [{
                key: _listTable.option('editing.editRowKey'),
                data: {
                    user_id: id,
                    grop_id: 'GROPMANAGER',
                    oper_syst_id: 'ITSOP',
                    del_yn: 'N',
                    addr: null,
                    comp: null,
                    crctymd: null,
                    rgstymd: getSendDate(new Date()),
                    hint_ans: null,
                    hint_ques: null,
                    mobile: null,
                    email: null,
                    name: null,
                    tel: null,
                    pwd: null,
                },
                type: "insert",
            }]
        );

        $(".modal-background").css("display", "none");
        dsblOnBtn(delBtn);
        dsblOnBtn(addBtn);
    }
}

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

        if (_listTable.hasEditData()) {
            _listTable.option('editing.changes').map((item) => {
                _listTable.byKey(item.key).done(function (obj) {
                    const data = {...obj};
                    data.crctymd = getSendDate(new Date());
                    updateDataArr.push(data);
                });
            });

            for (let obj of updateDataArr) {
                const frontContent = "ID : " + obj.user_id + "<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('/api/database/user-infr', updateDataArr);

                    if (result > 0) {
                        saveEnd('변경하신 운영자 정보가 수정 되었습니다.');
                    }
                }
            });
        }

        if (delData.length > 0) {
            confirmMessage("선택하신 운영자 정보를 삭제하시겠습니까?").done((yes) => {
                if (yes === true) {
                    let delIdArr = [];

                    delData.map((item) => {
                        delIdArr.push(item.user_id);
                    });

                    let result = deleteDataIds('/api/database/user-infr', delIdArr);

                    if (result > 0) {
                        saveEnd('선택하신 운영자 정보가 삭제 되었습니다.');
                    }
                }
            });
        }
    }
}

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

    _listTable.option('toolbar.visible', true);

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

    _listTable.option('selection', {
        mode: "single",
    });

    fetchListData();
                
    alertConfirm(text);
}