import { apiGet } from "/js/utils/restApi.js";

"use-strict"

const _code = 'FMSIG';

const updateColumns = {
    fclt_id   : null,
    out_cnt   : null,
    out_desc  : null,
    out_dt    : null,
    part_nmbr : null,
    user_id   : null,
    valid_cnt : 0,
}

let addBtn;
let editBtn;
let delBtn;
let saveBtn;
let cancelBtn;
let partNmbr;
let outDesc;
let outDt;
let outCnt;
let userId;
let fcltId;
let _cntMap;
let inputArr;
let partList;
let listTable;
let _selectedPartNmbr;
let _selectedFcltType;

$(()=>{

     /**
        fclt_id   : null,
        out_cnt   : null,
        out_desc  : null,
        out_dt    : null,
        part_nmbr : null,
        user_id   : null,
        valid_cnt : null,
     */
    const closeBtn  = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', null, null, false, true);
    closeBtn.onClick(()=>window.close());
    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', 100, '부품명', 160, 30, null, true);
    fcltId    = new dxSelect($('.fclt_id'), 'outlined', 250, 30, 'desc', 'fclt_id', true, 'fclt_id');
    outDesc   = new dxTxtArea($('.out_desc'), 'out_desc', 200, '출고 내용', 250, 60, null, true);
    outDt     = new dxDate($('.out_dt'), 'yyyy-MM-dd', '출고 일자', 120, 30, 'date', null, 'out_dt', null);
    outCnt    = new dxNumber($('.out_cnt'), 'outlined', 200, 30, 1, 99999, true, null, 'out_cnt', '#,##0', true);
    userId    = new dxTxt($('.user_id'), 'user_id', 10, '입고 담당자 ID', 200, 30, null, true, null);
    //validCnt  = new dxNumber($('.valid_cnt'), 'outlined', 200, 30, 1, 99999, true, null, 'valid_cnt', '#,##0', true);
    outDt.setReadOnly(true);
    inputArr = [
        partNmbr,
        outDt,
        outDesc,
        outCnt,
        userId,
        fcltId,
    ]
    addBtn.onClick(addBtnClick);
    cancelBtn.onClick(cancelBtnClick);
    editBtn.onClick(editBtnClick);
    delBtn.onClick(delBtnClick);

    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', 'out_dt', 'fclt_id'],
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:  [
            {
                caption   : '부품 번호',
                dataField : "part_nmbr",
                alignment : 'center',
                width     : 150,
                sortIndex : 0,
                sortOrder : "asc",
            },
            {
                caption   : '시설물 ID',
                dataField : "fclt_id",
                alignment : 'center',
                lookup : {
                    dataSource : [],
                    valueExpr : 'fclt_id',
                    displayExpr : 'desc',
                }
            },
            {
                caption   : '출고 일자',
                dataField : "out_dt",
                alignment : 'center',
                dataType  : 'date',
                format    : 'yyyy-MM-dd',
            },
            {
                dataField    : "out_cnt",
                caption      : "출고 개수",
                alignment    : "center",
            },
            {
                dataField    : "user_id",
                caption      : "출고 담당자 ID",
                alignment    : "center",
            },
            {
                dataField    : "valid_cnt",
                caption      : "재고 수량",
                alignment    : "center",
            },

        ],
        onRowClick(e){
            partListClick(e, setInputValue)
        },
    }).dxDataGrid("instance");
    
    listTable = $('.grid').width('100%').height('100%').dxTreeView({
        dataSource : null,
        focusStateEnabled: true,
        keyExpr    : "id",
        onItemClick(e){
           listTableClick(e);
        }
    }).dxTreeView("instance");
    fetchFcltLookupData();
    fetchTreeListData();
})
function fetchFcltLookupData(){
    getDataAsync('/api/facility/manager/info',
    (jsonData)=>{
        if (jsonData.length > 0) {
            jsonData.map((item)=>{
                item.desc = '[' + item.fclt_id + '] ' + item.fclt_lctn;
            })
        }
        partList.option('columns[1].lookup.dataSource', jsonData);
    })
}
function delBtnClick(){
    const selectedData = partList.getSelectedRowsData()[0];
    const partNmbrVal = selectedData.part_nmbr;
    const fcltIdVal   = selectedData.fclt_id;
    const outDtVal = getSendDate(selectedData.out_dt).substring(0,8);
    const dateStr = getParseDate(outDtVal);
    const frontMsg = '부품번호 : '+ partNmbrVal + '<br>시설물 ID : ' + fcltIdVal + '<br>출고일자 : '+ dateStr +'<br>부품 출고';
    confirmMessage( frontMsg + ' 정보를 삭제하시겠습니까?').done((yes)=>{
                    if (yes === true) {
                        const result = deleteData('/api/facility/part/out', partNmbrVal + '/' + fcltIdVal + '/' + outDtVal);
                        if (result > 0) {
                            delResultMsg(frontMsg);
                            partList.clearSelection();
                            partList.option('focusedRowIndex', -1);
                            initInputData(true);
                            fetchPartListData(partNmbrVal);
                            fetchTreeListData();
                        }
                    }
                })
}
function listTableClick(e){
    if (e.itemData && e.itemData.part_nmbr) {
        const data        = e.itemData;
        const partNmbrVal = data.part_nmbr;
        const maxCnt      = data.valid_cnt;
        const fcltType    = data.fclt_type;
        console.log(`partNmbrVal:${partNmbrVal}, maxCnt : ${maxCnt}, fcltType : ${fcltType}`);
        if (!maxCnt) {
            addBtn.setDisabled(true);
        }
        else {
            addBtn.setDisabled(false);
        }
        editBtn.setDisabled(true);
        delBtn.setDisabled(true);
        partList.clearSelection();
        partList.option('focusedRowIndex', -1);
        outCnt.setMax(maxCnt);
        initInputData(true);
        partNmbr.setValue(partNmbrVal);
        if (!_selectedPartNmbr || _selectedPartNmbr !== partNmbrVal){
            fetchPartListData(partNmbrVal);
            _selectedPartNmbr = partNmbrVal;
        }
        if (!_selectedFcltType || _selectedFcltType !== fcltType){
            fetchFcltData(fcltType);
            _selectedFcltType = fcltType;
        }
    }
}
function fetchFcltData(fcltType){
    getDataAsync('/api/facility/manager/info?fcltType=' 
                + encodeURIComponent(fcltType),
                (jsonData)=>{
                    if (jsonData.length > 0) {
                        jsonData.map((item)=>{
                            item.desc = '[' + item.fclt_id + '] ' + item.fclt_lctn;
                        })
                    }
                    fcltId.setDataSource(jsonData);
                })
}
function fetchPartListData(partNum){
    getDataAsync('/api/facility/part/out/part/' 
                + encodeURIComponent(partNum)
                , (jsonData)=>{
                    dataFormat(jsonData);
                    partList.option('dataSource', jsonData);
    })
}

async function fetchTreeListData(){
    let fcltType = apiGet('/api/database/code/cmmn-cd/' + _code);
    let subjList = apiGet('/api/facility/bom/subj');
    let partList = apiGet('/api/facility/part/bom');
    Promise.all([fcltType, subjList, partList])
        .then((results) => Promise.all(results.map((r) => r.json())))
        .then((values) => {
            recvTreeListData(values[0], values[1], values[2]);
        })
        .catch((err) => {
            console.log(`${err}: can not success....`)
        })
        .finally(() => {
            console.log(`promise close`);
        });
}

function recvTreeListData(fcltType, subjList, partList){
    let cnt = 1;
    let treeListData = [];
    _cntMap = new Map();
    dataSorting(fcltType, 'cmmn_cd');
    dataSorting(subjList, 'subj_nmbr');
    dataSorting(partList, 'part_nmbr');
    fcltType.map((item)=>{
        treeListData.push({
            id : cnt++,
            code : item.cmmn_cd,
            text : item.cmmn_cd_kor_nm,
            expanded : true,
            items : [],
        });
        _cntMap.set(item.cmmn_cd, new Map());
    });

    if (subjList.length > 0 && partList.length > 0) {
        treeListData.map((item)=>{
            let subjCnt = 1;
            subjList.map((obj)=>{
                let partCnt = 1;
                if (item.code === obj.fclt_type) {
                    const id = item.id + '_' + subjCnt;
                    item.items.push({
                        id :  item.id + '_' + subjCnt++,
                        text : obj.subj_nm + " - " + obj.subj_detl,
                        expanded: false,
                        items : [],
                    });
                    partList.map((part)=>{
                        if (part.subj_nmbr === obj.subj_nmbr) {
                            _cntMap.get(obj.fclt_type).set(part.part_nmbr, part.valid_cnt);
                            item.items[item.items.length - 1].items.push({
                                id : id + '_' + partCnt++,
                                fclt_type : obj.fclt_type,
                                part_nmbr : part.part_nmbr,
                                valid_cnt : part.valid_cnt,
                                text : '[' +part.part_nmbr + '] ' + part.part_nm + ' - ' + part.part_detl +' (재고 수량 : '+part.valid_cnt +')',
                                expanded: false,
                            })
                        }
                    })
                }
            })
        });
    }
    console.log(partList);
    listTable.option('dataSource', treeListData);
}

function addBtnClick() {
    btnStts(false);
    inputAddInitData();
    inputEditMode('add');
}

function inputAddInitData(){
    outDt.setValue(new Date());
    outCnt.setValue(1);
    userId.setValue(window.opener.$userId);
    outDesc.setValue(null);
    const fcltList = fcltId.getDataSource();
    if (fcltList && fcltList.length > 0) {
        fcltId.setValue(fcltList[0][fcltId.valueExpr]);
    }
}

function inputEditMode(type){
    inputArr.map((item)=>{
        if (item.column !== 'subj_id') {
            item.setReadOnly(false);
        }
    });

    if (type) {
        setSaveBtnClickType(type);
    }
}

function editBtnClick(){
    btnStts(false);
    inputEditMode('edit');
}

function setSaveBtnClickType(type){
    saveBtn.offClick();
    saveBtn.onClick(()=>saveBtnClick(type));
}
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)=>{
        if (item.column !== 'out_dt') {
            updateData[item.column] = item.getValue();
        }
        else {
            updateData[item.column] = item.getSendDateValue().substring(0, 8);
        }
    });
    console.log(updateData);
    const result = postInsertUpdate('/api/facility/part/out', updateData);
    if (result > 0) {
        insResultMsg("부품 번호 : " + nmbr +"<br>부품 입고");
        getDataAsync('/api/facility/part/out/part/' + encodeURIComponent(nmbr), updateAfterDataInit
                    , { part_nmbr:nmbr, out_dt : outDt.nowVal(), fclt_id : fcltId.getValue()});
    }
}

function updateAfterDataInit(jsonData, key){
    dataFormat(jsonData);
    partList.option('dataSource', jsonData);
    partList.refresh().done(()=>{
        partList.selectRows([key]).done(()=>{
            partList.option('focusedRowKey', key);
            btnStts(true);
            inputArr.map((item)=>{
                item.setReadOnly(true);
            })
        })
    });
    addBtn.setDisabled(true);
    fetchTreeListData();
}
function dataFormat(data) {
    if (data.length > 0) {
        data.map((item)=>{
            if (item.out_dt) item.out_dt = new Date(getParseDate(item.out_dt));
        });
    }
}

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);
    partList.option('disabled', !stts);
    listTable.option('disabled', !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);
    addBtn.setDisabled(true);
    outCnt.setMax(e.data.out_cnt + _cntMap.get(_selectedFcltType).get(e.data.part_nmbr));
    callback(e.data, true);
}