/** 
 * 상단 조회, 닫기 버튼
*/
let searchBtn;
let closeBtn;

/**
 * 좌측 시설물 테이블
 */
let _listTable;

/**
 * 우측 하단 수정, 취소, 적용 버튼
 */
let editBtn;
let cancelBtn;
let applyBtn;

/**
 * 우측 상단 input box
 */
let mainUserId;
let subUserId;
let fcltNmbr;
let fcltId;
let fcltType;
let inputArr;

/**
 * 페이지 uri 및 페이지 명
 */
const _pageName = '시설물별 인력 정의';
const userInfrUri = "/api/database/user-infr";
const _apiUri     = "/api/facility/manager/info";
$(() => {
    //시설물 테이블
    _listTable = $(".fclt-table").width('100%').height('100%').dxDataGrid({
        dataSource: null,
        allowColumnReordering: true,
        showColumnLines: true,
        allowColumnResizing: true,
        showBorders: true,
        rowAlternationEnabled: true,
        columnAutoWidth: true,
        focusedRowEnabled: true,
        noDataText: '표출할 정보가 없습니다.',
        keyExpr: 'fclt_nmbr',
        selection: {
            mode: 'single',
        },
        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: "fclt_type",
                caption: "시설물 유형",
                alignment: "center",
                groupIndex : 1,

            },
            {
                dataField: "fclt_nmbr",
                caption: "번호",
                alignment: "center",
                allowEditing: false,
                sortIndex: 0,
                sortOrder: "asc",
            },
            {
                dataField: "fclt_id",
                caption: "시설물 ID",
                alignment: "center",
            },
            {
                dataField: "fclt_lctn",
                caption: "설치 위치",
                alignment: "center",
                cellTemplate(c, e) {
                    return alignTemplate(c, e, 'left');
                }
            },
            {
                dataField    : "istl_cmpy_id",
                caption      : "설치업체",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'cmpy_nm',
                    valueExpr   : 'cmpy_id',
                }
            },
            {
                dataField    : "istl_dt",
                caption      : "설치일자",
                alignment    : "center",
                dataType     : "date",
                format       : "yyyy-MM-dd",
            },
            {
                dataField    : "maint_cmpy_id",
                caption      : "유지보수업체",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'cmpy_nm',
                    valueExpr   : 'cmpy_id',
                }
            },
            {
                dataField    : "main_user_id",
                caption      : "관리책임자(정)",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'user_id',
                    valueExpr   : 'main_user_id',
                }
            },
            {
                dataField    : "sub_user_id",
                caption      : "관리책임자(부)",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'user_id',
                    valueExpr   : 'sub_user_id',
                }
            },
            {
                dataField    : "mnfc_cmpy_id",
                caption      : "제조업체",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'cmpy_nm',
                    valueExpr   : 'cmpy_id',
                }
            },
            // {
            //     dataField    : "make_dt",
            //     caption      : "제조일자",
            //     visible      : false,
            //     alignment    : "center",
            //     dataType     : "date",
            //     format       : "yyyy-MM-dd",
            // },
            {
                dataField    : "mdl_nm",
                caption      : "모델명",
                alignment    : "center",
            },
        ],
        onRowClick(e){
            listTableClick(e);
        }
    }).dxDataGrid("instance");


    searchBtn  = new dxBtn($('.search-btn'), '조회', 'refresh', 'outlined', 80, 30, false, true);
    closeBtn   = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', 80, 30, false, true);
    closeBtn.onClick(()=>window.close());
    searchBtn.onClick(fetchListData);

    editBtn    = new dxBtn($('.edit-btn'), '수정', 'edit', 'outlined', null, null, true, true);
    cancelBtn  = new dxBtn($('.cancel-btn'), '취소', 'close', 'outlined', null, null, false, false);
    applyBtn   = new dxBtn($('.apply-btn'), '적용', 'save', 'outlined', null, null, true, true);
    editBtn.onClick(editBtnClick);
    cancelBtn.onClick(cancelBtnClick);
    applyBtn.onClick(applyBtnClick);

    fcltNmbr   = new dxNumber($('.fclt_nmbr'), 'outlined', 100, 30, 1, 9999999, null, null, 'fclt_nmbr', null, true);
    fcltId     = new dxTxt($('.fclt_id'), 'fclt_id', 40, '시설물 ID', 120, 30, null, true);
    fcltType   = new dxTxt($('.fclt_type'), 'fclt_type', 40, '시설물 유형', 120, 30, null, true);
    mainUserId = new dxSelect($('.main_user_id'), 'outlined', 200, 30, 'desc', 'main_user_id', true, 'main_user_id', '관리책임자 ID(정)');
    subUserId  = new dxSelect($('.sub_user_id'), 'outlined', 200, 30, 'desc', 'sub_user_id', true, 'sub_user_id', '관리책임자 ID(부)');
    fcltLctn   = new dxTxt($('.fclt_lctn'), 'fclt_lctn', 200, '시설물 위치', 260, 30, null, true);
    inputArr   = [fcltNmbr, fcltId, fcltType, fcltLctn, mainUserId, subUserId];

    fetchBaseData();
});

function fetchBaseData(){
    fetchListData();
    fetchComboData();
}

function fetchComboData(){
    getDataAsync(userInfrUri, recvComboData);
}

function recvComboData(jsonData){
    if (jsonData.length > 0) {
        jsonData.map((item)=>{
            item.desc = '[' + item.user_id + '] ' + item.name;
        });
    }
    mainUserId.setDataSource(jsonData);
    subUserId.setDataSource(jsonData);
}

function listTableClick(e) {
    if (e.data){
        inputArr.map((item)=>{
            item.setValue(e.data[item.column]);
        });
        editBtn.setDisabled(false);
    }
}

function editBtnClick(){
    toggleStts(false);
}

function cancelBtnClick(){
    toggleStts(true);
}

function applyBtnClick(){
    const validationArr = [mainUserId, subUserId];
    const fcltNmbrVal   = fcltNmbr.getValue();
    const frontMsg      = "시설물 번호 : " + fcltNmbrVal +"<br>"
    const selectedData  = _listTable.getSelectedRowsData()[0];
    const updateData    = {...selectedData};
    for (let item of validationArr) {
        const value = item.getValue();
        if (nullChecker(value) === "") {
            return alertWarning(frontMsg + '필수 항목을 입력해주세요. ['+ item.label+']');
        }
        else {
            updateData[item.column] = value;
        }
    }
    
    const result = postInsertUpdate('/api/facility/manager/info/' + encodeURIComponent(fcltNmbrVal), updateData);
    if (result > 0) {
        insResultMsg(frontMsg + '시설물별 인력 정의');
        fetchListData(()=>{
            _listTable.refresh().done(()=>{
                _listTable.selectRows(fcltNmbrVal).done(() =>{
                    _listTable.option('focusedRowKey', fcltNmbrVal);
                    toggleStts(true);
                }) 
            })
        })
    }
}

function toggleStts(stts){
    mainUserId.setReadOnly(stts);
    subUserId.setReadOnly(stts);
    _listTable.option('disabled', !stts);
    searchBtn.setDisabled(!stts);
    editBtn.setVisible(stts);
    cancelBtn.setVisible(!stts);
    applyBtn.setDisabled(stts);
}

function parseDateColumn(data, column){
    if (data[column]) data[column] = new Date(getParseDate(data[column])); 
}

function fetchListData(callback){
    _listTable.clearSelection();
    _listTable.option('focusedRowIndex', -1);
    inputArr.map((item)=>{
        item.setValue(null);
    })
    getDataAsync(_apiUri, (jsonData)=>{
        if (jsonData.length > 0) {
            jsonData.map((item)=>{
                parseDateColumn(item, 'abdn_dt');
                parseDateColumn(item, 'istl_dt');
                parseDateColumn(item, 'valid_ymd');
            })
        }
        _listTable.option('dataSource', jsonData);
        if (callback) {
            callback();
        }
    });

}
