"use-strict"
const _code = 'FMSTP';
//닫기 버튼
let closeBtn;

//조회 테이블
let listTable;
let fcltList;

//상단 조회기간
let strtDt;
let endDt;
let searchBtn;

//좌측 하단 장애 등록 영역
let failNo;
let findMan;
let strDt;
let failRegCd;
let failNm;
let failLevlCd;
let subjNmbr;
let wthrCd;
let failDesc;
let befActDesc;
let failEtcRmk;
let fcltAddBtn;
let fcltEditBtn;
let fcltSaveBtn;
let fcltDelBtn;
let fcltCancelBtn;

const failUpdateColumns = {
    bef_act_desc : null,
    end_dt       : null,
    etc_rmk      : null,
    fail_desc    : null,
    fail_levl_cd : null,
    fail_nm      : null,
    fail_no      : null,
    fail_ocrr_cd : null,
    fail_reg_cd  : null,
    fclt_nmbr    : null,
    find_man     : null,
    reg_dt       : null,
    step_cd      : 'ACT0',
    str_dt       : null,
    subj_nmbr    : null,
    use_yn       : "Y",
    wthr_cd      : null,
}

let failInputArr;
let selectArr;
let fcltAddVisibleArr;
let fcltAddHideArr;
let failOcrrCd;
let selectedType;
let fcltNmbr;
let _newNumber;

$(()=>{
    //상단
    closeBtn        = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', null, null, false, true);
    closeBtn.onClick(()=>window.close());
    strtDt          = new dxDate($('.strt-dt'), 'yyyy-MM-dd', '조회 기간 시작일자', 120, 30, 'date', null, 'strt_dt', null);
    strtDt.setValue(getBefAftDay(-7));
    endDt           = new dxDate($('.end-dt'), 'yyyy-MM-dd', '조회 기간 종료일자', 120, 30, 'date', null, 'end_dt', null);
    endDt.setValue(new Date());
    searchBtn       = new dxBtn($('.search-btn'), '조회', 'refresh', 'outlined', null, 32, false, true);
    searchBtn.onClick(searchBtnClick);
    //장애 등록
    fcltNmbr        = new dxTxt($('.fclt_nmbr'), 'fclt_nmbr', 10, '시설물 번호', 240, 30, null, true, null);
    failNo          = new dxTxt($('.fail_no'), 'fail_no', 10, '장애 번호', 240, 30, null, true, null);
    findMan         = new dxTxt($('.find_man'), 'find_man', 30, '장애발견자', 240, 30, null, true, null);
    strDt           = new dxDate($('.str_dt'), 'yyyy-MM-dd HH:mm:ss', '장애발생일자', 240, 30, 'datetime', null, 'str_dt', null);
    strDt.setReadOnly(true);
    failOcrrCd      = new dxSelect($('.fail_ocrr_cd'), 'outlined', 240, 30, 'desc', 'fail_ocrr_cd', true, 'fail_ocrr_cd', '장애발생구분');
    failRegCd       = new dxSelect($('.fail_reg_cd'), 'outlined', 240, 30, 'desc', 'fail_reg_cd', true, 'fail_reg_cd', '장애등록구분');
    failNm          = new dxTxt($('.fail_nm'), 'fail_nm', 100, '장애명', 240, 30, null, true, null);
    failLevlCd      = new dxSelect($('.fail_levl_cd'), 'outlined', 240, 30, 'desc', 'fail_levl_cd', true, 'fail_levl_cd', '장애(증상)명');
    subjNmbr        = new dxSelect($('.subj_nmbr'), 'outlined', 240, 30, 'desc', 'subj_nmbr', true, 'subj_nmbr', '장애 구성품');
    wthrCd          = new dxSelect($('.wthr_cd'), 'outlined', 240, 30, 'desc', 'wthr_cd', true, 'wthr_cd', '날씨');
    failDesc        = new dxTxtArea($('.fail_desc'), 'fail_desc', 256, '장애 내용', 260, 90, null, true, null);
    befActDesc      = new dxTxtArea($('.bef_act_desc'), 'bef_act_desc', 256, '선조치 내용', 260, 90, null, true, null);
    failEtcRmk      = new dxTxtArea($('.etc_rmk'), 'etc_rmk', 256, '비고', 260, 90, null, true, null);
    fcltAddBtn      = new dxBtn($('.fclt-add-btn'), '추가', 'plus', 'outlined', null, null, true, true);
    fcltEditBtn     = new dxBtn($('.fclt-edit-btn'), '수정', 'edit', 'outlined', null, null, true, true);
    fcltSaveBtn     = new dxBtn($('.fclt-save-btn'), '저장', 'save', 'outlined', null, null, false, false);
    fcltDelBtn      = new dxBtn($('.fclt-del-btn'), '삭제', 'minus', 'outlined', null, null, true, true);
    fcltCancelBtn   = new dxBtn($('.fclt-cancel-btn'), '취소', 'close', 'outlined', null, null, false, false);
    selectArr         = [failRegCd, failLevlCd, wthrCd, failOcrrCd, subjNmbr];
    fcltAddVisibleArr = [ fcltSaveBtn, fcltCancelBtn ];
    fcltAddHideArr    = [ fcltAddBtn, fcltEditBtn, fcltDelBtn ];
    
    failInputArr = [
        fcltNmbr,
        failNo,
        findMan,
        strDt,
        failRegCd,
        failNm,
        failOcrrCd,
        failLevlCd,
        subjNmbr,
        wthrCd,
        failDesc,
        befActDesc,
        failEtcRmk,
    ];

    listTable = $('.list-table')
        .width('100%')
        .height('100%')
        .dxDataGrid({
            dataSource              : null,
            allowColumnReordering   : true,
            showColumnLines         : true,
            allowColumnResizing     : true,
            showBorders             : true,
            rowAlternationEnabled   : true,
            columnAutoWidth         : true,
            noDataText              : '표출할 정보가 없습니다.',
            keyExpr                 : 'fail_no',
            focusedRowEnabled       : true,
            selection: {
            mode : 'none',
            },
            filterRow: {
                visible: false,
                applyFilter: "auto",
                showOperationChooser:false,
            },
            headerFilter: {
                visible : false,
            },
            grouping: {
                autoExpandAll : true,
            },
            scrolling: {
                mode : 'virtual',
            },
            selection: {
                mode : 'single',
            },
            columns:[
                {   
                    dataField    : "fail_no",
                    caption      : "장애 번호",
                    alignment    : "center",
                    allowEditing : false,
                    sortIndex    : 0, 
                    width        : 150,
                    dataType     : 'string',
                    sortOrder    : "asc",
                },
                {   
                    dataField   : "fclt_nmbr",
                    caption     : "시설물 관리 번호",
                    alignment   : "center",
                },
                {   
                    dataField   : "subj_nmbr",
                    caption     : "품목명",
                    alignment   : "center",
                    lookup : {
                        dataSource  : [],
                        displayExpr : 'subj_nm',
                        valueExpr   : 'subj_nmbr',
                    }
                },
                {   
                    dataField   : "step_cd",
                    caption     : "진행상태",
                    alignment   : "center",
                    lookup : {
                        dataSource  : [],
                        displayExpr : 'name',
                        valueExpr   : 'step_cd',
                    }
                },
                {
                    dataField   : "fail_reg_cd",
                    caption     : "장애등록 구분",
                    alignment   : "center",
                    lookup : {
                        dataSource  : [],
                        displayExpr : 'name',
                        valueExpr   : 'fail_reg_cd',
                    }
                },
                {
                    dataField   : "fail_ocrr_cd",
                    caption     : "장애 발생 구분",
                    alignment   : "center",
                    lookup : {
                        dataSource  : [],
                        displayExpr : 'fail_ocrr_cd_nm',
                        valueExpr   : 'fail_ocrr_cd',
                    }
                },
                {
                    dataField   : "fail_levl_cd",
                    caption     : "장애등급",
                    alignment   : "center",
                    lookup : {
                        dataSource  : [],
                        displayExpr : 'name',
                        valueExpr   : 'fail_levl_cd',
                    }
                },
                {   
                    dataField   : "str_dt",
                    caption     : "장애발생일시",
                    alignment   : "center",
                    dataType    : 'datetime',
                    format      : 'yyyy-MM-dd HH:mm:ss',
                },
                {   
                    dataField   : "end_dt",
                    caption     : "장애종료일시",
                    alignment   : "center",
                    dataType    : 'datetime',
                    format      : 'yyyy-MM-dd HH:mm:ss',
                },
                {
                    dataField   : "fail_nm",
                    caption     : "장애명",
                    alignment   : "center",
                    cellTemplate(c, e){
                        alignTemplate(c, e, 'left');
                    }
                },
                {
                    dataField   : "fail_desc",
                    caption     : "장애내용",
                    alignment   : "center",
                    cellTemplate(c, e){
                        alignTemplate(c, e, 'left');
                    }
                },
                {
                    dataField   : "find_man",
                    caption     : "발견자명",
                    alignment   : "center",
                },
                {
                    dataField   : "bef_act_desc",
                    caption     : "선조치 내용",
                    alignment   : "center",
                    cellTemplate(c, e){
                        alignTemplate(c, e, 'left');
                    }
                },
                {   
                    dataField   : "wthr_cd",
                    caption     : "날씨",
                    alignment   : "center",
                    lookup : {
                        dataSource  : [],
                        displayExpr : 'name',
                        valueExpr   : 'wthr_cd',
                    }
                },
                {   
                    dataField   : "etc_rmk",
                    caption     : "기타비고",
                    alignment   : "center",
                },
            ],
        onRowClick(e){
            listTableClick(e);
        }
    }).dxDataGrid("instance");
    
    fcltList = $('.fclt-list')
        .width('100%')
        .height('100%')
        .dxDataGrid({
            dataSource              : null,
            allowColumnReordering   : true,
            showColumnLines         : true,
            allowColumnResizing     : true,
            showBorders             : true,
            rowAlternationEnabled   : true,
            columnAutoWidth         : true,
            noDataText              : '표출할 정보가 없습니다.',
            keyExpr                 : 'fclt_nmbr',
            focusedRowEnabled       : true,
            selection: {
            mode : 'none',
            },
            filterRow: {
                visible: false,
                applyFilter: "auto",
                showOperationChooser:false,
            },
            headerFilter: {
                visible : false,
            },
            grouping: {
                autoExpandAll : true,
            },
            scrolling: {
                mode : 'virtual',
            },
            selection: {
                mode : 'single',
            },
            groupPanel:{
                visible         : false,
                emptyPanelText  : "그룹 지을 항목을 여기에 끌어다 놓으세요"
            },
            columns:[
                {   
                    dataField    : "fclt_type",
                    caption      : "시설물 유형",
                    alignment    : "center",
                    groupIndex    : 0,
                    lookup:{
                        dataSource  : [],
                        displayExpr : 'cmmn_cd_kor_nm',
                        valueExpr   : 'cmmn_cd'
                    }
                },
                {   
                    dataField   : "fclt_nmbr",
                    caption     : "시설물 번호",
                    alignment   : "center",
                    sortIndex   : 1,
                    sortOrder   : 'asc',
                },
                {
                    dataField   : "fclt_id",
                    caption     : "시설물 ID",
                    alignment   : "center",
                },
                {
                    dataField   : "fclt_lctn",
                    caption     : "설치 위치",
                    alignment   : "center",
                    cellTemplate(c, e) {
                        alignTemplate(c, e, 'left');
                    }
                },
                {
                    dataField   : "istl_lctn_addr",
                    caption     : "설치 주소",
                    alignment   : "center",
                    cellTemplate(c, e) {
                        alignTemplate(c, e, 'left');
                    }
                },
                {   
                    dataField   : "mdl_nm",
                    caption     : "모델명",
                    alignment   : "center",
                    cellTemplate(c, e) {
                        alignTemplate(c, e, 'left');
                    }
                },
            ],
            onRowClick(e){
                fcltListClick(e);
            }
    }).dxDataGrid('instance');

    fcltAddBtn.onClick(fcltAddBtnClick);
    fcltEditBtn.onClick(fcltEditBtnClick)
    fcltCancelBtn.onClick(fcltCancelBtnClick);
    fcltDelBtn.onClick(fcltDelBtnClick);

    fetchCodeData();
    fetchTreeList();
    _newNumber = getNewNumb();
    searchBtnClick();
})

/**
 * 저장 버튼 클릭 파라미터 설정
 * @param type 추가 버튼, 수정 버튼 별 타입 별개 부여
 */
function saveBtnClickType(type){
    fcltSaveBtn.offClick();
    fcltSaveBtn.onClick(()=>fcltSaveBtnClick(type));
}
/**
 * 수정버튼 클릭
 */
function fcltEditBtnClick(){
    elementState(true);
    editOnOff(fcltAddVisibleArr, fcltAddHideArr);
    failInputArr.map((item)=>{
        if (item.column !== 'fclt_nmbr' && item.column !== 'fail_no') {
            item.setReadOnly(false);
        }
    });
    saveBtnClickType('edit');
}
/**
 * 추가버튼 클릭
 */
function fcltAddBtnClick(){
    elementState(true);
    editOnOff(fcltAddVisibleArr, fcltAddHideArr, ()=> inputInit(false));
    addInputInit();
    saveBtnClickType('add');
}

function addInputInit(){
    selectArr.map((item)=>{
        const data = item.getDataSource();
        if (data && data.length > 0) {
            item.setValue(data[0][item.valueExpr]);
        }
    });

    failNo.setValue(_newNumber);
    strDt.setValue(new Date());
    findMan.setValue(window.opener.$userId);
}
/**
 * 취소버튼클릭
 */
function fcltCancelBtnClick(){
    elementState(false);
    editOnOff(fcltAddHideArr, fcltAddVisibleArr, () => inputInit(true, listTable.getSelectedRowsData()));
}

/**
 * 삭제버튼 클릭
 */
function fcltDelBtnClick(){
    const selectedData = listTable.getSelectedRowsData()[0];
    const failNoVal = selectedData.fail_no;
    let data = [];
    getData('/api/facility/fail/plan/usage/' + encodeURIComponent(failNoVal), data);
    if (data.length > 0 && data[0].count > 0) {
        return alertWarning('장애번호 : ' + failNoVal  + '<br>장애 조치내역이 있습니다.'
        +'<br>삭제하시려면 장애 조치 내역을 먼저 삭제해주세요.');
    }
    else {
        const msg = "장애번호 : " + failNoVal + '<br>장애 등록';
        confirmMessage(msg  + " 정보를 삭제하시겠습니까?").done((yes)=>{
            if (yes === true) {
                const result = deleteData('/api/facility/fail/plan', failNoVal);
                if (result > 0) {
                    delResultMsg(msg);
                    listTable.clearSelection();
                    listTable.option('focusedRowIndex', -1);
                    inputInit(true);
                    searchBtnClick();
                }
            }
        })
    }
}

function elementState(stts){
    listTable.option('disabled', stts);
    fcltList.option('disabled', stts);
    strtDt.setReadOnly(stts);
    endDt.setReadOnly(stts);
    searchBtn.setDisabled(stts);
}

function listTableClick(e){
    const data = e.data;
    const fcltData = fcltList.option('dataSource');
    const index = fcltData.findIndex(e=>e.fclt_nmbr === data.fclt_nmbr);
    const fclt_type = fcltData[index].fclt_type;
    fcltList.clearSelection();
    fcltList.option('focusedRowIndex', -1);
    if (!selectedType || selectedType !== fclt_type) {
        selectedType = fclt_type;
        fetchSubjCdData(selectedType);
    }
    failInputArr.map((item)=>{
        item.setValue(data[item.column]);
    });
    fcltEditBtn.setDisabled(false);
    fcltDelBtn.setDisabled(false);
    fcltAddBtn.setDisabled(true);
}

/**
 * 
 * @returns 
 */
function fcltSaveBtnClick(type){
    let updateData;
    if (type === 'add') {
        updateData = {...failUpdateColumns};
    }
    else {
        updateData = {...listTable.getSelectedRowsData()[0]};
    }
    const fcltNmbrVal = fcltNmbr.getValue();
    for (let input of failInputArr){
        const max = input.max;
        if (!input.isNull() && input.getByte() > max) {
            return alertWarning('시설물 번호 : ' 
                                + fcltNmbrVal 
                                + '<br>' 
                                + max 
                                + ' 바이트 이내로 입력해주세요. [ '+input.label+' ]'
                                , null,
                                input);
        }
    }
    failInputArr.map((item)=>{
        const column = item.column;
        if (column === 'str_dt'){
            updateData[column] = item.getSendDateValue();
        }
        else {
            updateData[column] = item.getValue();
        }
    })
    
    
    updateData.reg_dt = getSendDate(new Date());
    const result = postInsertUpdate('/api/facility/fail/plan/' + fcltNmbrVal, updateData);
    if (result > 0) {
        insResultMsg('시설물 번호 : ' + fcltNmbrVal +'<br>시설물 장애 등록');
        elementState(false);
        getDataAsync('/api/facility/fail/plan/list/all/' 
        + strtDt.getSendDateValue().substring(0, 8) 
        +'/'
        + endDt.getSendDateValue().substring(0, 8)
        , (jsonData)=>{
            console.log(jsonData);
            if (jsonData.length > 0) {
                jsonData.map((item)=>{
                    console.log(item);
                    if (item.str_dt) item.str_dt = new Date(getParseDateTime(item.str_dt));
                    if (item.end_dt) item.end_dt = new Date(getParseDateTime(item.end_dt));
                })
            }
            listTable.option('dataSource', jsonData);
            listTable.refresh().done(()=>{
                listTable.selectRows(updateData.fail_no).done(()=>{
                    listTable.option('focusedRowKey', updateData.fail_no);
                    fcltList.clearSelection();
                    fcltList.option('focusedRowIndex', -1);
                    fcltCancelBtnClick();
                    fcltAddBtn.setDisabled(true);
                    fcltEditBtn.setDisabled(false);
                    fcltDelBtn.setDisabled(false);
                })
            })
        });
        _newNumber = getNewNumb();
    }
}


function fcltListClick(e){
    const data = e.data;
    fcltEditBtn.setDisabled(true);
    fcltDelBtn.setDisabled(true);
    fcltAddBtn.setDisabled(false);
    fcltNmbr.setValue(data.fclt_nmbr);
    failNo.setValue(_newNumber);
    findMan.setValue(null);
    strDt.setValue(null);
    failNm.setValue(null);
    failDesc.setValue(null);
    befActDesc.setValue(null);
    failEtcRmk.setValue(null);
    listTable.clearSelection();
    listTable.option('focusedRowIndex', -1);
    if (!selectedType || selectedType !== data.fclt_type) {
        selectedType = data.fclt_type;
        fetchSubjCdData(selectedType);
    }
}
function fetchTreeList(){
    getDataAsync('/api/facility/manager/info', recvTreeListData);
}
function recvTreeListData(jsonData){
    let data = [];
    getData('/api/database/code/cmmn-cd/' + encodeURIComponent(_code), data);
    fcltList.option('columns[0].lookup.dataSource', data[0]);
    fcltList.option('dataSource', jsonData);
}

function searchBtnClick(){
    const searchDtArr = [strtDt, endDt];
    for (let searchDt of searchDtArr) {
        if (searchDt.isValidation()) {
            return alertWarning('형식에 맞게 입력해주세요. [ ' + searchDt.label + ']', null, searchDt);
        }
    }
    if (strtDt.nowVal() > endDt.nowVal()) {
        return alertWarning(strtDt.label + '가 ' + endDt.label + ' 보다 큽니다.', null, endDt);
    }
    else {
        getDataAsync('/api/facility/fail/plan/list/all/' 
                    + strtDt.getSendDateValue().substring(0, 8) 
                    +'/'
                    + endDt.getSendDateValue().substring(0, 8)
                    , fetchListData, listTable);
    }
}

function getNewNumb(){
    let data = [];
    getData('/api/facility/fail/plan/new-id', data);
    return data[0].new_id;
}
function fetchListData(jsonData, table){
    if (jsonData.length > 0) {
        jsonData.map((item)=>{
            if (item.str_dt) {
                item.str_dt = new Date(getParseDateTime(item.str_dt)); 
            }
            if (item.end_dt) {
                item.end_dt = new Date(getParseDateTime(item.end_dt)); 
            }
        })
    }
    table.option('dataSource', jsonData);
}

function fetchCodeData(){
    //장애조치단계
    getDataAsync('/api/facility/fail/plan/code/fail-step', (jsonData)=>{
        recvCodeData('step_cd', jsonData, null, 3);
    });
    //장애등록구분
    getDataAsync('/api/facility/fail/plan/code/fail-reg', (jsonData)=>{
        recvCodeData('fail_reg_cd', jsonData, failRegCd, 4);
    });
    //장애등급 구분
    getDataAsync('/api/facility/fail/plan/code/fail-levl', (jsonData)=>{
        recvCodeData('fail_levl_cd', jsonData, failLevlCd, 6);
    });
    //날씨 코드
    getDataAsync('/api/facility/fail/plan/code/fail-wthr', (jsonData)=>{
        recvCodeData('wthr_cd', jsonData, wthrCd, 13);
    });

    getDataAsync('/api/facility/bom/subj', (jsonData)=>{
        listTable.option('columns[2].lookup.dataSource', jsonData);
    })
    getDataAsync('/api/facility/code/fail-ocrr', (jsonData)=>{
        recvfailOcrrCdData(jsonData);
    })
}

function recvfailOcrrCdData(jsonData){
    if (jsonData.length > 0) {
        jsonData.map((item)=>{
            item.desc =  '['+ item.fail_ocrr_cd +'] '+ item.fail_ocrr_cd_nm;
        })
    }
    failOcrrCd.setDataSource(jsonData);
    listTable.option('columns[5].lookup.dataSource', jsonData);
}

function fetchSubjCdData(fcltType){
    getDataAsync('/api/facility/bom/subj/fclt/' + fcltType, recvSubjNmbrCdData);
}

function recvSubjNmbrCdData(jsonData){
    if (jsonData.length > 0){
        jsonData.map((item)=>{
            item.desc = '[' + item.subj_nmbr + '] ' + item.subj_nm;
        });
    }
    dataSorting(jsonData, 'subj_nmbr');
    subjNmbr.setDataSource(jsonData);
}

function recvCodeData(value, data, selectBox, columnNmbr){
    console.log(data);
    if (nullChecker(columnNmbr) !== ""){
        listTable.option('columns[' + columnNmbr + '].lookup.dataSource', data);
    }

    if (selectBox) {
        selectBox.setDataSource(data);
    }
    
}
function inputInit(stts, data) {
    if (data && data.length > 0){
        const fcltData = fcltList.option('dataSource');
        const index = fcltData.findIndex(e => e.fclt_nmbr === data[0].fclt_nmbr);
        const fclt_type = fcltData[index].fclt_type;
        if (!selectedType || selectedType !== fclt_type) {
            fetchSubjCdData(fclt_type);
        }

        failInputArr.map((item)=>{
            item.setValue(data[0][item.column]);
            if (item.column !== 'fail_no' && item.column !== 'fclt_nmbr'){
                item.setReadOnly(stts);
            }
        });
        
    }
    else {
        failInputArr.map((item)=>{
            if (item.column !== 'fail_no' && item.column !== 'fclt_nmbr'){
                item.setValue(null);
                item.setReadOnly(stts);
            }
        });
    }
}

function editOnOff(visibleArr, hideArr, callback){
    visibleArr.map((item)=>{
        item.setVisible(true);
    });
    hideArr.map((item)=>{
        item.setVisible(false);
    });
    
    if (callback) {
        callback();
    }
}
