"use-strict"
const _code     = 'FMSIG';
const _partMap  = new Map();
const updateColumns = {
    part_nmbr : 0,
    subj_nmbr : 0,
    part_id   : 0,
    part_nm   : null,
    part_detl : null,
    valid_mn  : null,
    valid_cnt : null,
    del_yn    : "N",
}
let fcltType;
let addBtn;
let editBtn;
let delBtn;
let saveBtn;
let cancelBtn;
let partNmbr;
let subjNm;
let partNm;
let partId;
let partDetl;
let validMn;
let validCnt;
let inputArr;
let gridTable;
let partList;
let _selectedFcltType;
let _selectedSubjNmbr;
const _apiUri = '/api/facility/bom/subj';

$(()=>{
    const closeBtn  = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', null, null, false, true);
    closeBtn.onClick(()=>window.close());
    fcltType     = new dxSelect($('.select'), 'outlined', 150, 30, 'cmmn_cd_kor_nm', 'cmmn_cd', false, 'fclt_type');
    fcltType.onItemClick(comboClick);
    addBtn    = new dxBtn($('.add-btn'), '추가', 'plus', 'outlined', null, null, true, 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);
    partNmbr  = new dxTxt($('.part_nmbr'), 'part_nmbr', 10, '부품 번호', 150, 30, null, true);
    subjNm    = new dxTxt($('.subj_nmbr'), 'subj_nmbr', 10, '품목 관리번호', 150, 30, null, true);
    partNm    = new dxTxt($('.part_nm'), 'part_nm', 100, '부품명', 250, 30, null, true);
    partId    = new dxTxt($('.part_id'), 'part_id', 5, '부품 ID', 250, 30, null, true);
    partDetl  = new dxTxt($('.part_detl'), 'part_detl', 100, '부품 세부사양', 250, 30, null, true);
    validMn   = new dxNumber($('.valid_mn'), 'outlined', 80, 30, 1, 99999, true, null, 'valid_mn', '#,##0', true);
    validCnt  = new dxNumber($('.valid_cnt'), 'outlined', 80, 30, 1, 99999, true, null, 'valid_cnt', '#,##0', true);
    inputArr  = [
        partNmbr,
        subjNm,
        partNm,
        partId,
        validMn,
        validCnt,
        partDetl,
    ]

    addBtn.onClick(addBtnClick);
    cancelBtn.onClick(cancelBtnClick);
    editBtn.onClick(editBtnClick);
    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 : ['fclt_type', 'subj_id'],
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:  [
            {
                caption   : '구성품 번호',
                dataField : "subj_id",
                alignment : 'center',
                width     : 150,
                sortIndex : 0,
                sortOrder : "asc",
            },
            {
                caption   : '시설물 유형',
                dataField : "fclt_type",
                visible   : false,
                alignment : 'center',
            },
            {
                dataField : "subj_nm",
                caption   : "구성품목명",
                alignment : "center",
                cellTemplate(c,e) {
                    alignTemplate(c, e, "left");
                }
            },
            {
                dataField    : "valid_mn",
                caption      : "내구연한",
                alignment    : "center",
            },
        ],
        onRowClick(e){
            gridTableClick(e);
        },
    }).dxDataGrid("instance");

    partList = $('.part-list').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 : 'part_nmbr',
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:  [
            {
                caption   : '부품 번호',
                dataField : "part_nmbr",
                alignment : 'center',
                width     : 150,
                sortIndex : 0,
                sortOrder : "asc",
            },
            {
                caption   : '부품 ID',
                dataField : "part_id",
                alignment : 'center',
            },
            {
                dataField : "part_nm",
                caption   : "부품명",
                alignment : "center",
                cellTemplate(c,e) {
                    alignTemplate(c, e, "left");
                }
            },
            {
                dataField : "part_detl",
                caption   : "부품 세부사양",
                alignment : "center",
                cellTemplate(c,e) {
                    alignTemplate(c, e, "left");
                }
            },
            {
                dataField    : "valid_mn",
                caption      : "내구연한",
                alignment    : "center",
            },
            {
                dataField    : "valid_cnt",
                caption      : "재고수량",
                alignment    : "center",
            },
        ],
        onRowClick(e){
            partListClick(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){
    if (!_selectedFcltType || _selectedFcltType !== type) {
        _selectedFcltType = type;
        const param = encodeURIComponent(type);
        getDataAsync(_apiUri + '/fclt/' + param, fetchListData);
    }
}

function fetchListData(jsonData){
    gridTable.option('dataSource', jsonData);
    gridTable.clearSelection();
    gridTable.option('focusedRowIndex', -1);
    if ( partList.getSelectedRowsData().length > 0 ){
        partList.option('dataSource', null);
    }
}

function gridTableClick(e){
    const subjNmbrVal = e.data.subj_nmbr;
    if (!_selectedSubjNmbr || _selectedSubjNmbr !== subjNmbrVal) {
        _selectedSubjNmbr = subjNmbrVal
        const param = encodeURIComponent(subjNmbrVal);
        getDataAsync('/api/facility/part/bom/subj/' + param, fetchPartListData);
        partList.option('focusedRowIndex', -1);
        partList.clearSelection();
        addBtn.setDisabled(false);
        editBtn.setDisabled(true);
        delBtn.setDisabled(true);
        inputArr.map((item)=>{
            item.setValue(null);
        })
        subjNm.setValue(subjNmbrVal);
    }
}
function fetchPartListData(jsonData){
    partList.option('dataSource', jsonData);
}
function comboClick(e){
    initInputData(true);
    partList.option('dataSource', null);
    bomDataWidthFcltType(e.itemData.cmmn_cd);
}
function getNewNmbr(){
    let newNmbr = [];
    getData('/api/facility/part/bom/new-id/part/' + encodeURIComponent(_selectedSubjNmbr), newNmbr);
    return newNmbr[0].new_id;
}
function addBtnClick() {
    btnStts(false);
    partNmbr.setValue(getNewNmbr());
    validMn.setValue(1);
    partDetl.setValue(null);
    partId.setValue(null);
    partNm.setValue(null);
    validCnt.setValue(1);
    inputEditMode();
    saveBtn.offClick();
    saveBtn.onClick(()=>saveBtnClick('add'));
}
function delBtnClick(){
    const delPartNmbr = partList.getSelectedRowsData()[0].part_nmbr;
    confirmMessage("부품 번호 : " 
                    + delPartNmbr 
                    + '<br>선택하신 부품 정보를 삭제하시겠습니까?')
                    .done((yes)=>{
                        if (yes === true) {
                            const result = deleteData('/api/facility/part/bom', delPartNmbr);
                            if (result > 0) {
                                delResultMsg("부품 번호 : " + delPartNmbr + '<br>부품');
                                partList.clearSelection();
                                partList.option('focusedRowIndex', -1);
                                getDataAsync('/api/facility/part/bom/subj/' + encodeURIComponent(_selectedSubjNmbr), fetchPartListData);
                                addBtn.setDisabled(false);
                                editBtn.setDisabled(true);
                                delBtn.setDisabled(true);
                                inputArr.map((item)=>{
                                    item.setValue(null);
                                })
                                subjNm.setValue(_selectedSubjNmbr);
                            }
                        }
                    });
}

function inputEditMode(){
    inputArr.map((item)=>{
        if (item.column !== 'subj_nmbr' && item.column !== 'part_nmbr') {
            item.setReadOnly(false);
        }
    })
}

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

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

function btnStts(stts){
    editBtn.setVisible(stts);
    addBtn.setVisible(stts);
    delBtn.setVisible(stts);
    saveBtn.setVisible(!stts);
    cancelBtn.setVisible(!stts);
    gridTable.option('disabled', !stts);
    partList.option('disabled', !stts)
    fcltType.setDisabled(!stts);
    //imgBtn.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 partListClick(e, callback){
    editBtn.setDisabled(false);
    delBtn.setDisabled(false);
    callback(e.data, true);
}


function saveBtnClick(type){
    let updateData;

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

    const nmbr = partNmbr.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);
        }
    }
    
    inputArr.map((item)=>{
        updateData[item.column] = item.getValue();
    });
    
    const result = postInsertUpdate('/api/facility/part/bom/' + encodeURIComponent(nmbr), updateData);
    const subjNmVal = gridTable.getSelectedRowsData()[0].subj_nm;
    if (result > 0) {
        insResultMsg("부품 번호 : " + nmbr +"<br>" + subjNmVal + " 부품");
        getDataAsync('/api/facility/part/bom/subj/' + encodeURIComponent(_selectedSubjNmbr), updateAfterDataInit, nmbr);
    }
}

function updateAfterDataInit(jsonData, key){
    partList.option('dataSource', jsonData);
    partList.refresh().done(()=>{
        partList.selectRows(key).done(()=>{
            partList.option('focusedRowKey', key);
            editBtn.setDisabled(false);
            delBtn.setDisabled(false);
            cancelBtnClick();
        })
    })
}