let companyData      = [];
let updatedData      = [];
let insertData       = [];
let idData           = [];
let delData          = [];
let companyTable    = 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 commonUri      = "/api/facility/company";
const _pageName      = '시설물 업체관리';

const _checkByteArr  = [
    ['cmpy_id', '업체 ID', 30],
    ['cmpy_nm', '업체 명', 30],
    ['cmpy_rgst_nmbr', '사업자등록번호', 30],
    ['addr','주소', 200],
    ['chgr_hp_nmbr','담당자 연락처', 128],
    ['tel', '전화번호', 128],
    ['fcsm_nmbr','팩스번호', 128],
    ['rprv_nm', '대표자명', 30],
    ['chgr_nm','담당자 명', 30],
    ['chgr_email', '담당자 이메일', 128],
]

const updateData = {
    addr           : null,
    cmpy_rgst_nmbr : null,
    chgr_email     : null,
    chgr_hp_nmbr   : null,
    chgr_nm        : null,
    cmpy_id        : null,
    cmpy_nm        : null,
    del_yn         : null,
    fcsm_nmbr      : null,
    rprv_nm        : null,
    tel            : null,
}
const btnArr = [
    cancleBtn = {
        box         : null,
        class       : 'cancle-button',
        icon        : 'close',
        height      : '30',
        width       : '80',
        text        : '닫기',
        stylingMode : 'outlined',
        method      : function(){
            window.close();
        }
    },
    searchBtn = {
        box         : null,
        class       : 'search-button',
        icon        : 'refresh',
        height      : '30',
        width       : '80',
        on          : {disabled : true},
        text        : '조회',
        stylingMode : 'outlined',
        method      : function(){
            fetchBaseData();
        }
    },
    editBtn = {
        box         : null,
        class       : 'edit-btn',
        icon        : 'edit',
        text        : '편집',
        on          : {visible : false, disabled : false},
        off         : {visible : true, disabled : false},
        stylingMode : 'outlined',
        method      : function(){
            eventOn();
        }
    },
    editCancleBtn = {
        box         : null,
        class       : 'edit-cancle-btn',
        icon        : 'close',
        on          : {visible : true, disabled : false},
        off         : {visible : false, disabled : false},
        visible     : false,
        text        : '취소',
        stylingMode : 'outlined',
        method      : function(){
            if(companyTable.hasEditData()){
                confirmMessage('변경 하신 데이터가 있습니다. 취소 하시겠습니까?').done((yes)=>{
                    if (yes) {
                        eventCancle();
                        companyTable.clearSelection();
                        setValue(modalText, null);
                    }
                })
            }
            else {
                eventCancle();
            }
        }
    },
    addBtn  = {
        box         : null,
        class       : 'add-btn',
        icon        : 'plus',
        on          : {visible : true, disabled : false},
        off         : {visible : true, disabled : true},
        disabled    : true,
        text        : '추가',
        stylingMode : 'outlined',
        method      : function(){
            $(".modal-background").css("display","flex");
           
            insertIdInit();

            companyTable.option("editing", {
                selectTextOnEditStart   : false,
            });

            setValue(modalText, null);
            modalText.focus();
        }
    },
    delBtn  = {
        box         : null,
        class       : 'del-btn',
        icon        : 'minus',
        on          : {visible : true, disabled : false},
        off         : {visible : true, disabled : true},
        disabled    : true,
        text        : '삭제',
        stylingMode : 'outlined',
        method       : function(){
            updatedData = [];

            companyTable.option("selection",{
                mode               : 'multiple',
                showCheckBoxesMode : "onClick"
            })

            companyTable.option('editing',{
                mode               : 'none'
            })

            dsblOnBtn(addBtn.box);
            dsblOnBtn(delBtn.box);
            applyBtn.box.off('click');
            applyBtn.box.on('click', () => delEvent());
        }
    },
    applyBtn = {
        box         : null,
        class       : 'apply-btn',
        icon        : 'save',
        on          : {visible : true, disabled : false},
        off         : {visible : true, disabled : true},
        disabled    : true,
        text        : '적용',
        stylingMode : 'outlined',
    },
    modalSelectBtn  = {
        box         : null,
        class       : 'modal-save-Btn',
        icon        : 'check',
        text        : '선택',
        stylingMode : 'outlined',
        method      : function(){
            insertNewId(modalText.option("value"));
        }
    },
    modalCancleBtn = {
        box         : null,
        class       : 'modal-cancle-Btn',
        icon        : 'close',
        text        : '취소',
        stylingMode : 'outlined',
        method      : function(){
            $(".modal-background").css("display",'none');
        }
    },
    modalXBtn = {
        box         : null,
        class       : 'modal-cancle',
        icon        : 'close',
        stylingMode : 'text',
        method      : function(){
            $(".modal-background").css("display",'none');
        }
    },
];

$(()=>{

    //추가 시 신규 업체 ID 입력을 위한 모달
    $("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'>"));
    
    //시설물 업체관리 테이블
    companyTable = $(".com-table").width('100%').height('100%').dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'cmpy_id',
        focusedRowEnabled       : true,
        selection: {
           mode : 'none',
        },
        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 :"엑셀 파일",
            },
        },
        onExporting(e){
            gridExcellExporting(e, _pageName);
        },
        columns:[
            {   
                dataField    : "cmpy_id",
                caption      : "ID",
                alignment    : "center",
                allowEditing : false,
                sortIndex    : 0, 
                width        : 100,
                dataType     : 'string',
                sortOrder    : "asc",
            },
            {
                dataField   : "cmpy_nm",
                caption     : "업체명",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 30,
                },
            },
            {
                dataField   : "cmpy_rgst_nmbr",
                caption     : "사업자등록번호",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 30,
                },
            },
            {   
                dataField   : "addr",
                caption     : "주소",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 200,
                },
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {   
                dataField   : "tel",
                caption     : "전화번호",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 128,
                },
            },
            {   
                dataField   : "fcsm_nmbr",
                caption     : "팩스번호",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 128,
                },
            },
            {   
                dataField   : "rprv_nm",
                caption     : "대표자명",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 30,
                },
            },
            {   
                dataField   : "chgr_nm",
                caption     : "담당자명",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 30,
                },
            },
            {   
                dataField   : "chgr_hp_nmbr",
                caption     : "담당자 연락처",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 128,
                },
            },
            {   
                dataField   : "chgr_email",
                caption     : "담당자 이메일",
                alignment   : "center",
                editorOptions: {
                    dataType : 'string',
                    maxLength : 128,
                },
            },
            {   
                dataField   : "del_yn",
                visible     : false,
                caption     : "삭제여부",
                lookup      : {
                    dataSource:['Y','N'],
                },
                alignment   : "center",
            },
        ],
        onRowInserted(e){
            updatedData.push(e.data)
        },
        onRowUpdated(e){
            updatedData.push(e.data)
        },
        onSelectionChanged(e){
            if(e.component.option('selection.mode') === 'multiple'){
                delData = e.selectedRowsData;
            }
        },
    }).dxDataGrid("instance");
  
    //신규업체 ID 입력 텍스트 상자
    modalText = $(".modal-text").dxTextBox({
        width:"250px",
        maxLength:'30',
        stylingMode: 'outlined',
        onEnterKey(e){
            insertNewId(e.component._changedValue);
        }
    }).dxTextBox("instance");

    //화면에 버튼 세팅
    btnArr.map((item)=>{
        item.box = $("." + item.class).dxButton({
            stylingMode : item.stylingMode,
            width       : item.width,
            disabled    : item.disabled,
            height      : item.height,
            icon        : item.icon,
            text        : item.text,
            visible     : item.visible,
            onClick(){
                if(item.method){
                    item.method();
                }
            }
        }).dxButton('instance');
    });

    fetchBaseData();
})

function fetchBaseData(){
    getDataAsync(commonUri, fetchListData);
}

function fetchListData(jsonData){
    companyData = jsonData
    if (companyData.length > 0){
        companyData.map((item) =>{
            idData.push(item.cmpy_id);
        });
    }
    companyTable.option('dataSource', companyData);
}

//동일 아이디 확인을 위한 아이디 데이터 배열 세팅 함수
function insertIdInit(){
    idData= [];
    companyData.map((item)=>{
        idData.push(item.cmpy_id);
    })
}

//이벤트 활성화
function eventOn(){
    //버튼 활성화/비활성화
    btnArr.map((item)=>{
        if(item.on){
            item.box.option('visible', item.on.visible);
            item.box.option('disabled', item.on.disabled);
        };
    })

    //테이블 수정 모드 변경
    companyTable.option("editing",{
        mode                    : 'batch',
        allowUpdating           : true,
        selectTextOnEditStart   : true,
    });
    
    //수정 시 툴바 사용 못하게 감추기
    companyTable.option('toolbar',{
        visible : false,
    });

    companyTable.refresh();

    //적용시 수정 이벤트 활성화
    applyBtn.box.off('click');
    applyBtn.box.on('click', () => editEvent());
}

//이벤트 비활성화
function eventCancle(){
    //버튼 활성화/비활성화
    btnArr.map((item)=>{
        if(item.off){
            item.box.option('visible', item.off.visible);
            item.box.option('disabled', item.off.disabled);
        };
    })

    //테이블 수정 모드 종료
    companyTable.option("editing",{
        allowUpdating : false,
    });
    //테이블 선택 모드 싱글
    companyTable.option("selection",{
        mode : 'single'
    });
    //툴바 활성화(Excell down)
    companyTable.option('toolbar',{
        visible : true,
    });
    
    dsblOffBtn(searchBtn.box);
    companyTable.refresh();
}

//아이디 유효성 검사
function insertNewId(id){
    switch (true) {
        case !id:
            alertWarning("ID를 입력해 주세요", null, modalText);
            break;
        case idData.includes(id):
            alertWarning("이미 사용중인 ID 입니다.", null, modalText);
            break;
        case getByteLength(id) > 30 :
            alertWarning("ID를 30바이트 이내로 입력해주세요.", null, modalText);
            break;
        default:
            companyTable.addRow();

            companyTable.option('editing.changes',[{
                key  : companyTable.option('editing.editRowKey'),  
                data : {
                    cmpy_id : id,
                    del_yn  : 'N',
                },
                type : "insert",
            }]);
            
            $(".modal-background").css("display","none");
            
            idData.push(id);
            modalText.option('value', '');
            dsblOnBtn(delBtn.box);
            dsblOnBtn(addBtn.box);
            break;
    }
}

//수정 이벤트
function editEvent(){
    let updateData = [];
    if( !companyTable.hasEditData() ) return alertWarning('변경된 데이터가 없습니다.')
    companyTable.option('editing.changes').map((item)=>{
        companyTable.byKey(item.key).done(function(obj) {
            const data = {...obj};
            updateData.push(data);
        });
    });
    for(let obj of updateData){
        const frontContent = "업체 ID : " + obj.cmpy_id + "<br>"
        for (let checkByte of _checkByteArr) {
            const value = obj[checkByte[0]];
            const empty = nullChecker(value) === '';
            if (!empty && getByteLength(value) > checkByte[2]) {
                return alertWarning( frontContent + checkByte[2]+ " 바이트 이내로 입력해주세요. [ " + checkByte[1] + " ]");
            }
        }
    }

    const result = postInsertUpdate(commonUri, updateData);
    if(result > 0 ){
        insResultMsg(_pageName);
        eventCancle();
        fetchBaseData();
        updatedData = [];
        return false;
    }
}

//삭제 이벤트
function delEvent(){
    let ids = [];
    const selectedData = companyTable.getSelectedRowsData();
    if (selectedData.length <= 0 ) {
        return alertWarning(_pageName + '가 선택 되지 않았습니다.');
    }
    
    selectedData.map((item)=>{
        ids.push(item.cmpy_id);
    });
    
    if (deleteDataIds(commonUri, ids) > 0){
        delResultMsg(_pageName);
        eventCancle();
        fetchBaseData();
        delData = [];
    }
}

function getCellVal( idx, column ){
    let cellValue = companyTable.cellValue(idx, column);
    if (nullChecker(cellValue) === "") {
        cellValue = null;
    }
    else {
        cellValue = nullChecker(cellValue);
    }
    return cellValue;
}