//데이터, 테이블, 상단 버튼
let clsfCdData           = [];
let clsfCdServeData      = [];
let cdData               = [];
let cdServeData          = [];
let clsfCdTable          = null;
let clsfCdServeTable     = null;
let searchBtn            = null;

//좌측 관련
let leftAddBtn           = null;
let leftEditBtn          = null;
let leftDelBtn           = null;
let leftCdIdText         = null;
let leftCdKorNmText      = null;
let leftCdEngNmText      = null;
let leftRmrkText         = null;
let leftCdUseYnSelect    = null;
let leftSaveBtn          = null;
let leftCancleBtn        = null;
let _selectedCd          = null;


//우측 관련
let cdTypeText           = null;
let cdKorNmText          = null;
let rightAddBtn          = null;
let rightEditBtn         = null;
let rightDelBtn          = null;
let rightSaveBtn         = null;
let rightCancleBtn       = null;
let rightCdIdText        = null;
let rightCdKorNmText     = null;
let rightCdEngNmText     = null;
let rightRmrkText        = null;
let rightAttr1Text       = null;
let rightAttr2Text       = null;
let rightAttr2Select     = null;

//모달 관련
let modalSelectBtn       = null;
let modalCancleBtn       = null;
let modalText            = null;
let modalCancleIcon      = null;
const clsfCdUri          = '/api/database/code/clsf-cd';

let _leftInputArr = []
let _rightInputArr = []

// //코드 중복 방지를 위한 코드 배열 값 세팅
// cdData = fetchCdArr(clsfCdData, 'cmmn_clsf_cd');

$(()=>{
    //모달 추가
    $("body").append(modalDiv);
    $(".modal-title").prepend($("<div>대표코드</div>"));
    $(".modal-background").css("display",'none');
    $(".modal-content").append($("<div class='modal-content-title'>").html("새로운 대표코드를 입력하세요<br>입력후에는 수정이 불가능합니다."),$("<div class='modal-text'>"))
    
    //상단 조회 버튼
    searchBtn = $(".search-button").dxButton({
        stylingMode:'outlined',
        text:'조회',
        icon:'refresh',
        height:'30px',
        width: '80px',
        onClick(){
            searchBtnClick();
        }
    }).dxButton("instance");
    
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance");
    
    //대분류 코드 관리 테이블
    clsfCdTable = $(".clsf-cd-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'cmmn_clsf_cd',
        focusedRowEnabled       : true,
        selection: {
           mode : 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible : true,
        },
        grouping: {
            autoExpandAll : true,
        },
        scrolling: {
            mode : 'virtual',
        },
        groupPanel:{
            visible         : true,
            emptyPanelText  : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        
        columns:[
            {   
                dataField    : "cmmn_clsf_cd",
                caption      : "분류 코드",
                alignment    : "center",
                allowEditing : false,
                sortIndex    : 0, 
                sortOrder    : "asc",
                validationRules: [{ type: 'required' }],
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {
                dataField   : "cmmn_clsf_kor_nm",
                caption     : "한글명",
                alignment   : "center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {   
                dataField   : "cmmn_clsf_engl_nm",
                caption     : "영문명",
                alignment   : "center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {   
                dataField   : "use_yn",
                caption     : "사용여부",
                alignment   : "center",
                lookup:{
                    dataSource:['Y','N']
                }
            },
            {   
                dataField   : "rmrk",
                caption     : "비고",
                alignment   : "center",
            },
        ],
        onRowClick(e){
            clsfCdTableRowClick(e);
        },
    }).dxDataGrid("instance");
    
    clsfCdServeTable = $(".clsf-cd-serve-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'cmmn_cd',
        focusedRowEnabled       : true,
        selection: {
           mode : 'single',
        },
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        headerFilter: {
            visible : true,
        },
        grouping: {
            autoExpandAll : true,
        },
        scrolling: {
            mode : 'virtual',
        },
        groupPanel:{
            visible         : true,
            emptyPanelText  : "그룹 지을 항목을 여기에 끌어다 놓으세요"
        },
        columns:[
            {   
                dataField    : "cmmn_cd",
                caption      : "공통 코드",
                alignment    : "center",
                allowEditing : false,
                sortIndex    : 0, 
                sortOrder    : "asc",
                validationRules: [{ type: 'required' }],
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {
                dataField   : "cmmn_cd_kor_nm",
                caption     : "한글명",
                alignment   : "center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {   
                dataField   : "cmmn_cd_engl_nm",
                caption     : "영문명",
                alignment   : "center",
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {
                dataField   : "atrb1",
                caption     : "속성1",
                alignment   : "center",
            },
            {
                dataField   : "atrb2",
                caption     : "속성2",
                alignment   : "center",
            },
            {   
                dataField   : "use_yn",
                caption     : "사용여부",
                alignment   : "center",
                lookup:{
                    dataSource:['Y','N']
                }
            }, 
            {   
                dataField   : "rmrk",
                caption     : "비고",
                alignment   : "center",
            },
        ],
        onRowClick(e){
            rightTextPull();
        },
    }).dxDataGrid("instance");

    //우측 상단 텍스트 박스
    cdTypeText = $(".cd-type-text").dxTextBox({
        width       : 100,
        height      : 27,
        readOnly    : true,
        stylingMode : 'outlined'

    }).dxTextBox("instance");

    //우측 상단 텍스트 박스
    cdKorNmText = $(".cd-kor-nm-text").dxTextBox({
        width       : 250,
        height      : 27,
        readOnly    : true,
        stylingMode : 'outlined'

    }).dxTextBox("instance");
    
    //좌측 추가 버튼
    leftAddBtn = $(".left-add-btn").dxButton({
        stylingMode:'outlined',
        text:'추가',
        icon:'plus',
        onClick(){
            if (clsfCdTable.option('disabled') === true) {
                return 
            }
            modalText.option('maxLength', 5);
            $(".modal-content-title").html("새로운 대표코드를 입력하세요<br>입력후에는 수정이 불가능합니다.")
            $(".modal-background").css("display","flex");
            modalText       .option("value",null);
            modalText       .focus();
            modalSelectBtn  .off("click");
            leftSaveBtn     .off("click");
            modalText       .off("enterKey")
            modalCancleBtn  .off("click");
            modalCancleIcon .off("click");
            modalSelectBtn  .on("click",() => leftAddEvent());
            leftSaveBtn     .on("click",() => leftCdInsert());
            modalText       .on("enterKey",() => leftAddEvent());
            modalCancleBtn  .on("click",() => leftModalCancle()); 
            modalCancleIcon .on("click",() => leftModalCancle());
        }    
    }).dxButton("instance");
    
    //좌측 삭제 버튼
    leftDelBtn = $(".left-del-btn").dxButton({
        stylingMode:'outlined',
        text:'삭제',
        icon:'minus',
        onClick(){
            if (clsfCdTable.option('disabled') === true) {
                return 
            }

            if (clsfCdTable.getSelectedRowsData().length <= 0 ) {
                return alertWarning('대표 코드를 선택해주세요');
            }
            
            confirmMessage("대표 코드를 삭제하시겠습니까?").done((yes) => {
                if (yes === true) {
                    let result = deleteData(clsfCdUri,clsfCdTable.getSelectedRowsData()[0].cmmn_clsf_cd);
                    if(result > 0){
                        fetchListData();
                        clsfCdServeTable.option("dataSource", []);
                        clsfCdTable.clearSelection();
                        clsfCdTable.option('focusedRowIndex', -1);
                        leftTextInit();
                        rightTextInit();
                        setValue(cdTypeText, null);
                        setValue(cdKorNmText, null);
                        _selectedCd = null;
                        alertConfirm("대표 코드가 삭제되었습니다.");
                    }
                    //return alertError("대표 코드가 삭제되지 않았습니다.")
                }
            });
        }
    }).dxButton("instance");
    
    //좌측 수정 버튼
    leftEditBtn = $(".left-edit-btn").dxButton({
        stylingMode:'outlined',
        text:'수정',
        icon:'edit',
        onClick(){
            if (clsfCdTable.option('disabled') === true) {
                return 
            }

            if (clsfCdTable.getSelectedRowsData().length <= 0) {
                return alertWarning("대표 코드를 선택해주세요");
            }
            leftUpdateOn();
            leftSaveBtn.off("click")
            leftSaveBtn.on("click",() => leftCdUpdate())
        }
    }).dxButton("instance");
    
    //좌측 저장 버튼
    leftSaveBtn = $(".left-save-btn").dxButton({
        stylingMode:'outlined',
        text:'저장',
        icon:'save',
        visible: false,
    }).dxButton("instance");

    //좌측 취소 버튼
    leftCancleBtn = $(".left-cancle-btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        icon:'close',
        visible: false,
        onClick(){
            leftUpdateOff();
            if ( clsfCdTable.getSelectedRowsData().length > 0 ){
                leftTextPull();
            } 
            else {
                leftTextInit();
            }
            cdData = fetchCdArr([clsfCdData], 'cmmn_clsf_cd');
        }
    }).dxButton("instance");

    //우측 추가 버튼
    rightAddBtn = $(".right-add-btn").dxButton({
        stylingMode:'outlined',
        text:'추가',
        icon:'plus',
        onClick(){
            if (clsfCdServeTable.option('disabled') === true) {
                return false;
            }

            if (clsfCdTable.getSelectedRowsData().length <= 0) {
                return alertWarning("대표 코드를 선택해주세요");
            }
            modalText.option('maxLength', 7);
            $(".modal-content-title").html("새로운 세부 코드를 입력하세요<br>입력후에는 수정이 불가능합니다.")
            $(".modal-background").css("display","flex");
            modalText.option("value",null);
            modalSelectBtn.off("click");
            rightSaveBtn.off("click");
            modalText.off("enterKey");
            modalCancleBtn.off("click"); 
            modalCancleIcon.off("click");
            modalSelectBtn.on("click",() => rightAddEvent());
            rightSaveBtn.on("click",() => rightCdInsert());
            modalText.on("enterKey",() => rightAddEvent());
            modalCancleBtn.on("click",() => rightModalCancle());
            modalCancleIcon.on("click",() => rightModalCancle());
            modalText.focus();
        }    
    }).dxButton("instance");
    
    //우측 삭제 버튼
    rightDelBtn = $(".right-del-btn").dxButton({
        stylingMode:'outlined',
        text:'삭제',
        icon:'minus',
        onClick(){
            if (clsfCdServeTable.option('disabled') === true) {
                return false;
            }

            if(clsfCdServeTable.getSelectedRowsData().length <= 0) {
                return alertWarning("세부 코드를 선택해주세요");
            }
            confirmMessage("세부 코드를 삭제하시겠습니까?").done((yes) => {
                if (yes === true) {
                    let result = 0;
                    result = deleteData("/api/database/code/cmmn-cd/"+cdTypeText.option("value"),clsfCdServeTable.getSelectedRowsData()[0].cmmn_cd);
                    if(result > 0){
                        clsfCdServeData = refresh(clsfCdServeTable, clsfCdServeData, "/api/database/code/cmmn-cd/"+cdTypeText.option("value"));
                        cdServeData = fetchCdArr(clsfCdServeData, 'cmmn_cd');
                        clsfCdServeTable.clearSelection();
                        clsfCdServeTable.option('focusedRowIndex', -1);
                        rightTextInit();
                        alertConfirm("세부 코드가 삭제되었습니다.")
                    }
                    //return alertError("세부 코드가 삭제되지 않았습니다.");
                }
            });
        }
    }).dxButton("instance");
    
    //우측 수정 버튼
    rightEditBtn = $(".right-edit-btn").dxButton({
        stylingMode:'outlined',
        text:'수정',
        icon:'edit',
        onClick() {
            if (clsfCdServeTable.option('disabled') === true) {
                return false;
            }

            if(clsfCdServeTable.getSelectedRowsData().length <= 0) {
                return alertWarning("세부 코드를 선택해주세요");
            }
            rightUpdateOn();
            rightSaveBtn.off("click");
            rightSaveBtn.on("click",()=>rightCdUpdate());
        }
    }).dxButton("instance");
     
    //우측 저장 버튼
     rightSaveBtn = $(".right-save-btn").dxButton({
        stylingMode:'outlined',
        text:'저장',
        icon:'save',
        visible: false,
    }).dxButton("instance");
    
    //우측 취소 버튼
    rightCancleBtn = $(".right-cancle-btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        icon:'close',
        visible: false,
        onClick(){
            rightUpdateOff();
            if ( clsfCdServeTable.getSelectedRowsData().length > 0 ) {
                rightTextPull();
            }
            else {
                rightTextInit();
            }
            cdServeData = fetchCdArr(clsfCdServeData, 'cmmn_cd');
        }   
    }).dxButton("instance");
    
    //좌측 아이디 텍스트
    leftCdIdText       = $(".left-cd-id-text").dxTextBox({
        readOnly    : true,
        stylingMode : 'outlined',
        width       : 120,
    }).dxTextBox("instance");
    
    //좌측 한글명 텍스트
    leftCdKorNmText    = $(".left-cd-kor-nm-text").dxTextBox({
        readOnly    : true,
        maxLength   : 100,
        width       : "70%",
        stylingMode : 'outlined'
    }).dxTextBox("instance");
    
    //좌측 영어명 텍스트 
    leftCdEngNmText    = $(".left-cd-eng-nm-text").dxTextBox({
        readOnly    : true,
        maxLength   : 100,
        width       : "70%",
        stylingMode : 'outlined'
    }).dxTextBox("instance");
    
    //좌측 비고 텍스트
    leftRmrkText     = $(".left-rmrk-text").dxTextBox({
        readOnly    : true,
        maxLength   : 600,
        width       : "70%",
        stylingMode : 'outlined'
    }).dxTextBox("instance");
    
    //좌측 사용 여부 셀렉트
    leftCdUseYnSelect  = $(".left-user-yn-select").dxSelectBox({
        items       : ["Y","N"],
        readOnly    : true,
        width       : 80,
        stylingMode : 'outlined'
    }).dxSelectBox("instance");
    
    //우측 ID 텍스트
    rightCdIdText      = $(".right-cd-id-text").dxTextBox({
        readOnly    : true,
        stylingMode : 'outlined',
        width       : 120,
    }).dxTextBox("instance");
    
    //우측 한글명 텍스트 
    rightCdKorNmText   = $(".right-cd-kor-nm-text").dxTextBox({
        readOnly    : true,
        width       : "70%",
        maxLength   : 100,
        stylingMode : 'outlined'
    }).dxTextBox("instance");
    
    //우측 영어명 텍스트
    rightCdEngNmText   = $(".right-cd-eng-nm-text").dxTextBox({
        readOnly    : true,
        width       : "70%",
        maxLength   : 100,
        stylingMode : 'outlined'
    }).dxTextBox("instance");
    
    //우측 비고 텍스트
    rightRmrkText    = $(".right-rmrk-text").dxTextBox({
        readOnly : true,
        width     : "70%",
        maxLength : 600,
        stylingMode : 'outlined'
    }).dxTextBox("instance");
    
    //우측 속성1 텍스트
    rightAttr1Text     = $(".right-attr1-text").dxTextBox({
        readOnly : true,
        width     : "52%",
        maxLength : 60,
        stylingMode : 'outlined'
    }).dxTextBox("instance");
    
    //우측 속성2 텍스트
    rightAttr2Text     = $(".right-attr2-text").dxTextBox({
        readOnly : true,
        width     : "100%",
        maxLength : 60,
        stylingMode : 'outlined'
    }).dxTextBox("instance");
    
    //우측 사용여부 셀렉트
    rightAttr2Select   = $(".right-attr2-select").dxSelectBox({
        readOnly : true,
        items:["Y","N"],
        width : 80,
        stylingMode : 'outlined'
    }).dxSelectBox("instance");
   
    //모달 선택 버튼
    modalSelectBtn = $(".modal-save-Btn").dxButton({
        stylingMode:'outlined',
        text:'선택',
        icon:'check',
    }).dxButton("instance");
    
    //모달 텍스트
    modalText = $(".modal-text").dxTextBox({
        width: 355,
        stylingMode : 'outlined',
    }).dxTextBox("instance");

    //모달 취소 버튼
    modalCancleBtn = $(".modal-cancle-Btn").dxButton({
        stylingMode:'outlined',
        text:'취소',
        icon:'close',
    }).dxButton("instance");
    
    //휴일 선택 모달 x 버튼
    modalCancleIcon = $(".modal-cancle").dxButton({
        stylingMode:'text',
        icon:'close',
        onClick(){
            $(".modal-background").css("display",'none');
        }
    }).dxButton("instance");

    fetchListData();
    _leftInputArr = [
        [leftCdIdText, 'cmmn_clsf_cd'],
        [leftCdKorNmText, 'cmmn_clsf_kor_nm'],
        [leftCdEngNmText, 'cmmn_clsf_engl_nm'],
        [leftRmrkText, 'rmrk'],
        [leftCdUseYnSelect, 'use_yn'],
    ];
    _rightInputArr = [
        [rightAttr1Text, 'atrb1'],
        [rightAttr2Text, 'atrb2'],
        [rightCdIdText, 'cmmn_cd'],
        [rightCdEngNmText, 'cmmn_cd_engl_nm'],
        [rightCdKorNmText, 'cmmn_cd_kor_nm'],
        [cdTypeText, 'cmmn_clsf_cd'],
        [rightRmrkText, 'rmrk'],
        [rightAttr2Select, 'use_yn'],
    ]
})

function fetchListData(){
    getDataAsync(clsfCdUri, (jsonData)=> {
        clsfCdData = jsonData;
        clsfCdTable.option('dataSource', clsfCdData);
        
        if (clsfCdData.length > 0) {
            cdData = [];
            clsfCdData.map((item) =>{
                if (item.cmmn_clsf_cd) cdData.push(item.cmmn_clsf_cd);
            });
        }
    });
}

function clsfCdTableRowClick(info){
    const rowData = info.data;
    if ( _selectedCd === null || _selectedCd !== rowData.cmmn_clsf_cd) {
        _selectedCd = rowData.cmmn_clsf_cd;
        clsfCdServeData = refresh(clsfCdServeTable, clsfCdServeData, '/api/database/code/cmmn-cd/' + rowData.cmmn_clsf_cd);
        setValue(cdTypeText, rowData.cmmn_clsf_cd);
        setValue(cdKorNmText, rowData.cmmn_clsf_kor_nm);
        clsfCdServeTable.clearSelection();
        clsfCdServeTable.option('focusedRowIndex', -1);
        leftTextPull();
        rightTextInit();
        cdServeData = fetchCdArr(clsfCdServeData,'cmmn_cd');
    }
}

function fetchCdArr(data, column) {
    let cdArr= [];
    if (data[0].length > 0) {
        data[0].map((item) =>{
            cdArr.push(item[column]);
        });
    }
    return cdArr;
}

function searchBtnClick(){
    fetchListData();
    clsfCdTable.clearSelection();
    clsfCdTable.option('focusedRowIndex', -1);
    clsfCdServeTable.option('dataSource', []);
    leftTextInit();
    rightTextInit();
    setValue(cdTypeText, null);
    setValue(cdKorNmText, null);
    _selectedCd = null;
}


//===============좌측 이벤트========================
//좌측 수정 기본 세팅
function leftUpdateOn(){
    showBtn(leftSaveBtn);
    showBtn(leftCancleBtn);
    hideBtn(leftAddBtn);
    hideBtn(leftDelBtn);
    hideBtn(leftEditBtn);
    leftCdKorNmText.option('readOnly', false);
    leftCdEngNmText.option('readOnly', false);
    leftRmrkText.option('readOnly', false);
    leftCdUseYnSelect.option('readOnly', false);
    dsblOnBtn(clsfCdTable);
    dsblOnBtn(clsfCdServeTable);
    modalText.option('maxLength', 5);
}

//좌측 추가
function leftCdInsert(){
    const validationArr = [[leftCdKorNmText, '코드 한글명'], [leftCdEngNmText, '코드 영문명'], [leftRmrkText, '비고']];
    if (byteValidation(validationArr)) {
        return false;
    }

    let insertData = {
        cmmn_clsf_cd        : null,
        cmmn_clsf_kor_nm    : null,
        cmmn_clsf_engl_nm   : null,
        msg_type_cd         : null,
        rmrk                : null,
        use_syst_cd         : null,
        use_yn              : null,
    }
    for (let input of _leftInputArr) {
        let value = getValue(input[0]);
        value = nullChecker(value) === "" ? null : value;
        insertData[input[1]] = value;
    }


    let result = postInsertUpdate(clsfCdUri,insertData);
    if ( result > 0) {
        leftUpdateOff();
        clsfCdData = [];
        getData(clsfCdUri,clsfCdData)
        clsfCdTable.option("dataSource",clsfCdData[0]);
        clsfCdTable.refresh().done(()=>{
            clsfCdTable.selectRows(insertData.cmmn_clsf_cd).done(()=>{
                clsfCdTable.option('focusedRowKey', insertData.cmmn_clsf_cd);
                setValue(cdTypeText, insertData.cmmn_clsf_cd);
                setValue(cdKorNmText, insertData.cmmn_clsf_kor_nm);
                clsfCdServeTable.option('dataSource', []);
                rightTextInit();
                alertConfirm("대표 코드가 등록되었습니다.");
            })
        })
    }
    //return alertError("대표 코드가 등록되지 않았습니다.");
}

//좌측 수정 기본 세팅 취소
function leftUpdateOff(){
    showBtn(leftAddBtn);
    showBtn(leftDelBtn);
    showBtn(leftEditBtn);
    hideBtn(leftSaveBtn);
    hideBtn(leftCancleBtn);
    leftCdKorNmText.option('readOnly', true);
    leftCdEngNmText.option('readOnly', true);
    leftRmrkText.option('readOnly', true);
    leftCdUseYnSelect.option('readOnly', true);
    dsblOffBtn(clsfCdTable);
    dsblOffBtn(clsfCdServeTable);
}

//좌측 수정
function leftCdUpdate(){
    const rowData = clsfCdTable.getSelectedRowsData()[0];
    const validationArr = [[leftCdKorNmText, '코드 한글명'], [leftCdEngNmText, '코드 영문명'], [leftRmrkText, '비고']];
    if (byteValidation(validationArr)) {
        return false;
    }

    let updateData = {
        cmmn_clsf_cd        : null,
        cmmn_clsf_kor_nm    : null,
        cmmn_clsf_engl_nm   : null,
        msg_type_cd         : rowData.msg_type_cd,
        rmrk                : null,
        use_syst_cd         : rowData.use_syst_cd,
        use_yn              : null,
    }

    for (let input of _leftInputArr) {
        let value = getValue(input[0]);
        value = nullChecker(value) === "" ? null : value;
        updateData[input[1]] = value;
    }
    
    let result = postInsertUpdate(clsfCdUri, updateData);
    if ( result > 0) {
        leftUpdateOff();
        clsfCdData = refresh(clsfCdTable, clsfCdData, clsfCdUri);
        alertConfirm("대표 코드가 수정되었습니다.");
    }
    //return alertError("대표 코드가 수정되지 않았습니다.");
}
function byteValidation(validationArr){
    for (let validation of validationArr) {
        const value = getValue(validation[0]);
        const max   = validation[0].option('maxLength');
        if ( value && getByteLength(value) > max) {
            alertWarning(max + ' 바이트 이내로 입력해주세요. [ ' + validation[1] + ' ]', null, validation[0])
            return true;
        }
    }
    return false;
}
//좌측 추가 시 버튼 이벤트 세팅
function leftAddEvent(){
    leftCdKorNmText.option("value", null);
    leftCdEngNmText.option("value", null);
    leftRmrkText.option("value", null);
    let textVal = modalText.option("value");
    if ( nullChecker(textVal) === "" || cdData.includes(textVal)){
        return alertWarning("값이 입력되지 않았거나 중복된 코드입니다. 다시 입력해주세요", null, modalText);
    }
    else if (getByteLength(textVal) > 5) {
        return alertWarning("대표 코드 ID는 5바이트 이내로 입력해주세요.", null, modalText);
    }
    leftUpdateOn();
    $(".modal-background").css("display", "none");
    leftCdUseYnSelect.option("value", "Y");
    leftCdIdText.option("value", textVal);
    cdData.push(textVal);
    dsblOnBtn(clsfCdServeTable);
}

//좌측 취소 시 모달 이벤트 세팅
function leftModalCancle(){
    $(".modal-background").css("display",'none'); 
    if ( clsfCdTable.getSelectedRowsData().length > 0 ) {
        return leftTextPull();
    }
    leftTextInit();
}

//좌측 하단 텍스트 null 세팅
function leftTextInit(){
    const leftTextArr = [
        leftCdIdText,
        leftCdKorNmText,
        leftCdEngNmText,
        leftRmrkText,
        leftCdUseYnSelect
    ];

    leftTextArr.map((item)=>{
        setValue(item, null);
    });
}

//좌측 하단 텍스트 값 세팅
function leftTextPull(){
    let rowData = clsfCdTable.getSelectedRowsData();
    leftCdIdText.option("value", rowData[0].cmmn_clsf_cd);
    leftCdKorNmText.option("value", rowData[0].cmmn_clsf_kor_nm);
    leftCdEngNmText.option("value", rowData[0].cmmn_clsf_engl_nm);
    leftRmrkText.option("value", rowData[0].rmrk);
    leftCdUseYnSelect.option("value", rowData[0].use_yn);
}

//===============우측 이벤트========================

//우측 수정 기본 세팅
function rightUpdateOn(){
    showBtn(rightSaveBtn);
    showBtn(rightCancleBtn);
    hideBtn(rightAddBtn);
    hideBtn(rightDelBtn);
    hideBtn(rightEditBtn);
    rightCdKorNmText.option('readOnly', false);
    rightCdEngNmText.option('readOnly', false);
    rightRmrkText.option('readOnly', false);
    rightAttr2Select.option('readOnly', false);
    rightAttr1Text.option('readOnly', false);
    rightAttr2Text.option('readOnly', false);
    dsblOnBtn(clsfCdTable);
    dsblOnBtn(clsfCdServeTable);
}

//우측 수정 기본 세팅 취소
function rightUpdateOff(){
    showBtn(rightAddBtn);
    showBtn(rightDelBtn);
    showBtn(rightEditBtn);
    hideBtn(rightSaveBtn);
    hideBtn(rightCancleBtn);
    rightCdKorNmText.option('readOnly', true);
    rightCdEngNmText.option('readOnly', true);
    rightRmrkText.option('readOnly', true);
    rightAttr2Select.option('readOnly', true);
    rightAttr1Text.option('readOnly', true);
    rightAttr2Text.option('readOnly', true);
    dsblOffBtn(clsfCdTable);
    dsblOffBtn(clsfCdServeTable);
}

//우측 추가
function rightCdInsert(){
    const validationArr = [
        [rightCdKorNmText, '코드 한글명'],
        [rightCdEngNmText, '코드 영문명'],
        [rightRmrkText, '비고'],
        [rightAttr1Text, '속성1'],
        [rightAttr2Text, '속성2'],
    ];
    if (byteValidation(validationArr)) {
        return false;
    }

    const insertData = {
        atrb1           : null,
        atrb2           : null,
        cmmn_cd         : null,
        cmmn_cd_abbr    : null,
        cmmn_cd_engl_nm : null,
        cmmn_cd_kor_nm  : null,
        cmmn_clsf_cd    : null,
        rmrk            : null,
        use_yn          : null,
    }
    for (let input of _rightInputArr) {
        let value = getValue(input[0]);
        value = nullChecker(value) === "" ? null : value;
        insertData[input[1]] = value;
    }
    let result = postInsertUpdate("/api/database/code/cmmn-cd", insertData);
    if ( result > 0 ) {
        rightUpdateOff();
        clsfCdServeData = [];
        getData('/api/database/code/cmmn-cd/' + cdTypeText.option("value"), clsfCdServeData);
        clsfCdServeTable.option('dataSource',clsfCdServeData[0]);
        clsfCdServeTable.refresh().done(()=>{
            clsfCdServeTable.selectRows(insertData.cmmn_cd).done(()=>{
                clsfCdServeTable.option('focusedRowKey', insertData.cmmn_cd);
            })
        })
        alertConfirm("세부 코드가 등록되었습니다.");
    }
    //return alertError("세부 코드가 등록되지 않았습니다.");
}

//우측 수정
function rightCdUpdate(){
    const rowData = clsfCdServeTable.getSelectedRowsData()[0];

    const validationArr = [
        [rightCdKorNmText, '코드 한글명'],
        [rightCdEngNmText, '코드 영문명'],
        [rightRmrkText, '비고'],
        [rightAttr1Text, '속성1'],
        [rightAttr2Text, '속성2'],
    ];
    if (byteValidation(validationArr)) {
        return false;
    }

    const updateData = {
        atrb1           : null,
        atrb2           : null,
        cmmn_cd         : null,
        cmmn_cd_abbr    : rowData.cmmn_cd_abbr,
        cmmn_cd_engl_nm : null,
        cmmn_cd_kor_nm  : null,
        cmmn_clsf_cd    : null,
        rmrk            : null,
        use_yn          : null,
        last_crct_dt    : getSendDate(new Date()),
    }
    for (let input of _rightInputArr) {
        let value = getValue(input[0]);
        value = nullChecker(value) === "" ? null : value;
        updateData[input[1]] = value;
    }
    let result = postInsertUpdate("/api/database/code/cmmn-cd", updateData);
    if (result > 0) {
        rightUpdateOff();
        clsfCdServeData = [];
        getData('/api/database/code/cmmn-cd/' + cdTypeText.option("value"), clsfCdServeData);
        clsfCdServeTable.option('dataSource', clsfCdServeData[0]);
        alertConfirm("세부 코드가 수정되었습니다.");
    };
}

//우측 추가 시 버튼 이벤트 세팅
function rightAddEvent(){
        let value = modalText.option("value");
        modalText.option('maxLength', 7);
        if ( nullChecker(value) === "" || cdServeData.includes(value)){
            alertWarning("값이 입력되지 않았거나 중복된 코드입니다. 다시 입력해주세요", null, modalText);
            return;
        }
        else if (value && getByteLength(value) > 7) {
            return alertWarning("세부코드 ID는 7바이트 이내로 입력해주세요.", null, modalText);
        }
        rightUpdateOn();
        $(".modal-background").css("display","none");
        rightTextInit();
        rightCdIdText.option("value", value);
        rightAttr2Select.option("value", "Y");
        cdServeData.push(value);
}

//우측 취소 시 모달 이벤트 세팅
function rightModalCancle(){
    $(".modal-background").css("display",'none');
    
    if ( clsfCdServeTable.getSelectedRowsData().length > 0 ) {
        rightTextPull();
    }
    else {
        rightTextInit();
    } 
}

//우측 하단 텍스트 null 세팅
function rightTextInit(){
    rightCdIdText.option("value",null);
    rightCdKorNmText.option("value",null);
    rightCdEngNmText.option("value",null);
    rightRmrkText.option("value",null);
    rightAttr1Text.option("value",null);
    rightAttr2Text.option("value",null);
    rightAttr2Select.option("value",null);
}

//우측 하단 텍스트 값 세팅
function rightTextPull(){
    let rowData = clsfCdServeTable.getSelectedRowsData();
    rightCdIdText.option("value",rowData[0].cmmn_cd);
    rightCdKorNmText.option("value",rowData[0].cmmn_cd_kor_nm);
    rightCdEngNmText.option("value",rowData[0].cmmn_cd_engl_nm);
    rightRmrkText.option("value",rowData[0].rmrk);
    rightAttr1Text.option("value",rowData[0].atrb1);
    rightAttr2Text.option("value",rowData[0].atrb2);
    rightAttr2Select.option("value",rowData[0].use_yn);
}
