"use-strict"
const _code = 'FMCNTR';
const _pageName = '시설물 정보 구성';
const updateColumns = {
    del_yn    : "N",
    fclt_type : null,
    subj_detl : null,
    subj_id   : null,
    subj_nm   : null,
    subj_nmbr : null,
    valid_mn  : null,
}

let fcltType;
let closeBtn;
let addBtn;
let editBtn;
let delBtn;
let saveBtn;
let cancelBtn;
let subjId;
let subjNm;
let validMn;
let subjDetl;
let inputArr;
let gridTable;
let subjNmbr;

const _apiUri = '/api/facility/bom/subj';

$(()=>{

    /**
     *  fclt_type : null,
        subj_id   : null,
        subj_nm   : null,
        valid_mn  : null,
        del_yn    : "N",
     */
    fcltType = new dxSelect($('.fclt_type'), 'outlined', 150, 30, 'cmmn_cd_kor_nm', 'cmmn_cd', false, 'fclt_type', '시설물 종류');
    fcltType.onItemClick(fcltTypeCdClick);
    closeBtn  = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', null, null, false, true);
    closeBtn.onClick(()=>window.close());
    addBtn    = new dxBtn($('.add-btn'), '추가', 'plus', 'outlined', null, null, false, true);
    editBtn   = new dxBtn($('.edit-btn'), '수정', 'edit', 'outlined', null, null, true, true);
    delBtn    = new dxBtn($('.del-btn'), '삭제', 'minus', 'outlined', null, null, true, true);
    saveBtn   = new dxBtn($('.save-btn'), '저장', 'save', 'outlined', null, null, false, false);
    cancelBtn = new dxBtn($('.cancel-btn'), '취소', 'close', 'outlined', null, null, false, false);
    subjId    = new dxNumber($('.subj_id'), 'outlined', 150, 30, 1, 99999, false, null, 'subj_id', '#', true);
    subjNmbr  = new dxNumber($('.subj_nmbr'), 'outlined', 150, 30, 1, 9999999999, false, null, 'subj_nmbr', '#', true);
    subjNm    = new dxTxt($('.subj_nm'), 'subj_nm', 100, '품목명', 250, 30, null, true);
    subjDetl  = new dxTxt($('.subj_detl'), 'subj_detl', 100, '품목 세부사양', 250, 30, null, true);
    validMn   = new dxNumber($('.valid_mn'), 'outlined', 80, 30, 1, 99999, true, null, 'valid_mn', '#,##0', true);
    inputArr = [
        subjNmbr,
        subjId,
        subjNm,
        subjDetl,
        validMn,
    ]

    addBtn.onClick(addBtnClick);
    cancelBtn.onClick(cancelBtnClick);
    editBtn.onClick(editBtnClick);
    saveBtn.onClick(saveBtnClick);
    delBtn.onClick(delBtnClick);
    
    gridTable = $('.grid').width('100%').height('100%').dxDataGrid({
        dataSource : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        idDataText              : '표출할 정보가 없습니다.',
        headerFilter: {
            visible: true,
        },
        selection  : {
            mode :'single'
        },
        keyExpr : 'subj_nmbr',
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        export:{
            enabled: true,
            texts: {
                exportAll:"엑셀 파일",
            },
        },
        onExporting(e){
            const data = fcltType.getDataSource();
            const value = fcltType.getValue();
            const idx = data.findIndex(item => item.cmmn_cd === value);
            gridExcellExporting(e, data[idx].cmmn_cd_kor_nm + ' ' + _pageName);
        },
        columns:  [
            {
                caption   : '품목 번호',
                dataField : "subj_nmbr",
                alignment : 'center',
                width     : 150,
                sortIndex : 0,
                sortOrder : "asc",
            },
            {
                caption   : '품목 ID',
                dataField : "subj_id",
                alignment : 'center',
                width     : 150,
            },
            {
                dataField : "subj_nm",
                caption   : "품목명",
                alignment : "center",
                cellTemplate(c,e) {
                    alignTemplate(c, e, "left");
                }
            },
            {
                dataField : "subj_detl",
                caption   : "품목 세부 사양",
                alignment : "center",
                cellTemplate(c,e) {
                    alignTemplate(c, e, "left");
                }
            },
            {
                dataField    : "valid_mn",
                caption      : "내구연한",
                alignment    : "center",
            },
        ],
        onRowClick(e){
            gridTableClick(e, setInputValue)
        },
    }).dxDataGrid("instance");
    fetchBaseData();
})


function fetchBaseData(){
    getDataAsync('/api/database/code/cmmn-cd/'+ _code, recvTypeData)
}

function recvTypeData(jsonData){
    fcltType.setDataSource(jsonData);
    if (jsonData.length > 0) {
        const value = jsonData[0][fcltType.valueExpr];
        fcltType.setValue(value);
        const param = encodeURIComponent(value);
        bomDataWidthFcltType(param);
    }
}
function bomDataWidthFcltType(type){
    getDataAsync(_apiUri + '/fclt/' + type, fetchListData);
}
function fetchListData(jsonData){
    gridTable.option('dataSource', jsonData);
    gridTable.clearSelection();
    gridTable.option('focusedRowIndex', -1);
}

function fcltTypeCdClick(e){
    gridTable.clearSelection();
    gridTable.option('focusedRowIndex', -1);
    bomDataWidthFcltType(e.itemData.cmmn_cd);
    initInputData(true);
}

function getNewNumb(){
    let data = [];
    getData(_apiUri + '/new-id', data);
    getData(_apiUri + '/new-id/subj/' + encodeURIComponent(fcltType.getValue()), data)
    return data;
}
function addBtnClick() {
    btnStts(false);
    let newNums = getNewNumb();
    subjNmbr.setValue(newNums[0].new_id);
    subjId.setValue(newNums[1].new_id);
    subjNm.setValue(null);
    subjDetl.setValue(null);
    validMn.setValue(1);
    inputEditMode();
    saveBtn.offClick();
    saveBtn.onClick(() => saveBtnClick('add'));
}

function inputEditMode(){
    let justReadOnlyArr = ['subj_id', 'subj_nmbr'];
    inputArr.map((item)=>{
        if (!justReadOnlyArr.includes(item.column)) {
            item.setReadOnly(false);
        }
    })
}

function editBtnClick(){
    btnStts(false);
    inputEditMode();
    saveBtn.offClick();
    saveBtn.onClick(() => saveBtnClick('edit'));
}

function cancelBtnClick(){
    let selectedData = gridTable.getSelectedRowsData();
    btnStts(true);
    if (selectedData.length > 0){
        setInputValue(selectedData[0], true);
    }
    else {
        initInputData(true);
    }
}

function saveBtnClick(type){
    let updateData;

    if (type === 'add') {
        updateData = {...updateColumns};
    }
    else {
        updateData = {...gridTable.getSelectedRowsData()[0]};
    }

    const nmbr = subjNmbr.getValue();
    for (let input of inputArr) {
        const max = input.max;
        if (input.isNull()) {
            return alertWarning("품목 번호 : " + nmbr +"<br>필수 사항을 입력해주세요. [ " + input.label + " ]", null, input);
        }
        else if (max < input.getByte()) {
            return alertWarning("품목 번호 : " + nmbr +"<br>" + max + " 바이트 이내로 입력해주세요. [ " + input.label + " ]", null, input);
        }
    }
    const updateInputArr = [subjNmbr, subjId, subjNm, validMn, subjDetl, fcltType];
    updateInputArr.map((item)=>{
        updateData[item.column] = item.getValue();
    });

    const result = postInsertUpdate(_apiUri + '/' + encodeURIComponent(nmbr), updateData);
    if (result > 0) {
        insResultMsg("품목 번호 : " + nmbr +"<br>" + getTypeName() + " 시설물 구성품");
        getDataAsync(_apiUri + '/fclt/' + fcltType.getValue(), updateAfterDataInit, nmbr);
    }
}

function delBtnClick(){
    let selectedData = gridTable.getSelectedRowsData()[0];
    const nmbr = selectedData.subj_nmbr;
    confirmMessage("품목 번호 : " + nmbr + "<br>구성품 정보를 삭제하시겠습니까?").done((yes)=>{
        if (yes === true) {
            const result = deleteData(_apiUri, nmbr);
            if (result > 0) {
                delResultMsg("품목 번호 : " + nmbr + "<br>" + getTypeName() + " 시설물 구성품");
                bomDataWidthFcltType(fcltType.getValue());
                btnStts(true);
                initInputData();
                editBtn.setDisabled(true);
                delBtn.setDisabled(true);
            }
        }
    })
}

function updateAfterDataInit(jsonData, key){
    gridTable.option('dataSource', jsonData);
    gridTable.refresh().done(()=>{
        gridTable.selectRows(key);
        gridTable.option('focusedRowKey', key);
        btnStts(true);
        editBtn.setDisabled(false);
        delBtn.setDisabled(false);
        inputArr.map((item)=>{
            item.setReadOnly(true);
        })
    })
}

function btnStts(stts){
    editBtn.setVisible(stts);
    addBtn.setVisible(stts);
    delBtn.setVisible(stts);
    saveBtn.setVisible(!stts);
    cancelBtn.setVisible(!stts);
    gridTable.option('disabled', !stts);
    fcltType.setDisabled(!stts);
}

function initInputData(stts){
    inputArr.map((item)=>{
        if (item.value){
            item.setValue(item.value);
        }
        else {
            item.setValue(null);
        }
        item.setReadOnly(stts);
    })
    
}

function setInputValue(data, stts){
    inputArr.map((item)=>{
        item.setValue(data[item.column]);
        item.setReadOnly(stts);
    });
  
}

function gridTableClick(e, callback){
    editBtn.setDisabled(false);
    delBtn.setDisabled(false);
    callback(e.data, true);
}

function getTypeName(){
    let display;
    const value = fcltType.getValue();
    fcltType.getDataSource().map((item)=>{
        if (item.cmmn_cd === value){
            display = item.cmmn_cd_kor_nm;
        }
    });
    return display;
}