import { requestGet, apiGet } from "/js/utils/restApi.js";
"use-strict"
const _code = 'FMITS';
let addBtn;
let editBtn;
let delBtn;
let saveBtn;
let cancelBtn;
let partNmbr;
let inDt;
let inUnit;
let perAmt;
let inCnt;
let cmpyId;
let userId;
let validCnt;
let inputArr;
let fcltType;
let subjNmbr;
let partList;
let listTable;
let _selectedPartNmbr;

const updateColumns = {
    cmpy_id: null,
    in_cnt: 0,
    in_dt: null,
    in_unit: null,
    part_nmbr: 0,
    per_amt: 0,
    user_id: null,
    valid_cnt: 0
  }

$(()=>{

    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);
    inDt      = new dxDate($('.in_dt'), 'yyyy-MM-dd', '입고 일자', 120, 30, 'date', null, 'in_dt', null);
    inUnit    = new dxTxt($('.in_unit'), 'in_unit', 10, '단위', 200, 30, null, true, null);
    perAmt    = new dxNumber($('.per_amt'), 'outlined', 200, 30, 0, 9999999999, true, null, 'per_amt', '#,##0', true);
    inCnt     = new dxNumber($('.in_cnt'), 'outlined', 200, 30, 1, 99999, true, null, 'in_cnt', '#,##0', true);
    cmpyId    = new dxSelect($('.cmpy_id'), 'outlined', 200, 30, 'desc', 'cmpy_id', true, 'cmpy_id');
    fcltType  = new dxSelect($('.fclt_type'), 'outlined', 140, 30, 'desc', 'fclt_type', false, 'fclt_type');
    subjNmbr  = new dxSelect($('.subj_nmbr'), 'outlined', 300, 30, 'desc', 'subj_nmbr', false, 'subj_nmbr');
    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);
    inDt.setReadOnly(true);
    inputArr = [
        partNmbr,
        inDt,
        inUnit,
        perAmt,
        inCnt,
        cmpyId,
        userId,
        //validCnt,
    ]

    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', 'in_dt'],
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:  [
            {
                caption   : '부품 번호',
                dataField : "part_nmbr",
                alignment : 'center',
                width     : 150,
                sortIndex : 0,
                sortOrder : "asc",
            },
            {
                caption   : '입고 일자',
                dataField : "in_dt",
                alignment : 'center',
                dataType  : 'date',
                format    : 'yyyy-MM-dd'
            },
            {
                dataField : "in_unit",
                caption   : "단위",
                alignment : "center",
            },
            {
                dataField : "per_amt",
                caption   : "단위 수량당 단가",
                alignment : "center",
                format    : "#,##0",
            },
            {
                dataField    : "in_cnt",
                caption      : "입고 개수",
                alignment    : "center",
            },
            {
                dataField    : "cmpy_id",
                caption      : "매입 업체",
                alignment    : "center",
                lookup:{
                    dataSource  : [],
                    displayExpr : 'cmpy_nm',
                    valueExpr   : 'cmpy_id',
                }
            },
            {
                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");

    fetchTreeListData();
});

function delBtnClick(){
    const selectedData = partList.getSelectedRowsData()[0];
    const partNmbrVal = selectedData.part_nmbr;
    const inDtVal = getSendDate(selectedData.in_dt).substring(0,8);
    const dateStr = getParseDate(inDtVal);
    const frontMsg = '입고일자 : '+ dateStr + '<br>부품번호 : '+ partNmbrVal + '<br>부품 입고';
    confirmMessage( frontMsg + ' 정보를 삭제하시겠습니까?').done((yes)=>{
                    if (yes === true) {
                        const result = deleteData('/api/facility/part/in', partNmbrVal + '/' + inDtVal);
                        if (result > 0) {
                            delResultMsg(frontMsg);
                            partList.clearSelection();
                            partList.option('focusedRowIndex', -1);
                            initInputData(true);
                            fetchPartListData(partNmbrVal);
                        }
                    }
                })
}
function listTableClick(e){
    if (e.itemData && e.itemData.part_nmbr) {
        const partNmbrVal = e.itemData.part_nmbr;
        addBtn.setDisabled(false);
        editBtn.setDisabled(true);
        delBtn.setDisabled(true);
        partList.clearSelection();
        partList.option('focusedRowIndex', -1);
        initInputData(true);
        partNmbr.setValue(partNmbrVal);
        if (!_selectedPartNmbr || _selectedPartNmbr !== partNmbrVal){
            fetchPartListData(partNmbrVal);
            _selectedPartNmbr = partNmbrVal;
        }
    }
}

function fetchPartListData(partNum){
    getDataAsync('/api/facility/part/in/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');
    let cmpyList = apiGet('/api/facility/company');
    Promise.all([fcltType, subjList, partList, cmpyList])
        .then((results) => Promise.all(results.map((r) => r.json())))
        .then((values) => {
            recvTreeListData(values[0], values[1], values[2]);
            recvCmpyData(values[3])
        })
        .catch((err) => {
            console.log(`${err}: can not success....`)
        })
        .finally(() => {
            console.log(`fetchTreeListData finish`)
        });
}
function recvCmpyData(jsonData){
    if (jsonData.length) {
        dataSorting(jsonData, 'cmpy_id');
        jsonData.map((item)=>{
            item.desc = '[' + item.cmpy_id + '] '+ item.cmpy_nm;
        });
    }
    cmpyId.setDataSource(jsonData);
    partList.option('columns[5].lookup.dataSource', jsonData);
}

function recvTreeListData(fcltType, subjList, partList){
    let cnt = 1;
    let treeListData = [];
    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 : [],
        })
    });

    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) {
                            console.log(part);
                            item.items[item.items.length - 1].items.push({
                                id : id + '_' + partCnt++,
                                part_nmbr : part.part_nmbr,
                                text : '[' +part.part_nmbr + '] ' + part.part_nm + ' - ' + part.part_detl,
                                expanded: false,
                            })
                        }
                    })
                }
            })
        });
    }
    listTable.option('dataSource', treeListData);
}

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

function inputAddInitData(){
    inDt.setValue(new Date());
    inCnt.setValue(1);
    userId.setValue(window.opener.$userId);
    inUnit.setValue(null);
    perAmt.setValue(0);
    const cmpyData = cmpyId.getDataSource();
    if (cmpyData) {
        cmpyId.setValue(cmpyData[0][cmpyId.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 !== 'in_dt') {
            updateData[item.column] = item.getValue();
        }
        else {
            updateData[item.column] = item.getSendDateValue().substring(0, 8);
        }
    });
    console.log(updateData);
    const result = postInsertUpdate('/api/facility/part/in', updateData);
    if (result > 0) {
        insResultMsg("부품 번호 : " + nmbr +"<br>부품 입고");
        getDataAsync('/api/facility/part/in/part/' + encodeURIComponent(nmbr), updateAfterDataInit, { part_nmbr:nmbr, in_dt : inDt.nowVal()});
    }
}

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);
            })
        })
    })
}
function dataFormat(data) {
    if (data.length > 0) {
        data.map((item)=>{
            if (item.in_dt) item.in_dt = new Date(getParseDate(item.in_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);
    callback(e.data, true);
}