"use-strict"
//시설물 유형 코드
const _code = "FMSCRS";
const _pageName = '시설물 정보';
//우측 구성품 정보 관련
let addBtn;
let editBtn;
let delBtn;
let saveBtn;
let cancelBtn;
let fcltId;
let fcltLctn;
let istlCmpy;
let makeCmpy;
let mngrCmpy;
let mdlNm;
let istlDt;
//let makeDt;
let fcltType;
let mngr;
let _inputArr;

//미등록 시설물 모달 관련
let unregCancelBtn;
let unregSaveBtn;
let unlegClose;
let unregList;

//상단 버튼 및 리스트
let closeBtn;
let _regListTable;

/**
 *  abdn_dt	        string 폐기 일시, Nullable = Y, VARCHAR2(14)
    amt	            integer 금액, Nullable = Y, NUMBER(15)
    del_yn	        string 삭제 여부, Nullable = Y, CHAR(1)
    fclt_id	        strinn 시설물 ID, Nullable = N, VARCHAR2(30)
    fclt_lctn	    string 시설물 위치, Nullable = Y, VARCHAR2(100)
    fclt_nmbr	    integer 시설물 관리 번호, Nullable = N, NUMBER(10)
    fclt_type	    string 시설물 유형, Nullable = N, VARCHAR2(7)
    istl_cmpy_id	string 설치업체 ID, Nullable = Y, VARCHAR2(30)
    istl_dt	        string 설치일, Nullable = Y, VARCHAR2(8)
    istl_lctn_addr	string 설치 위치 주소, Nullable = Y, VARCHAR2(200)
    main_user_id	string 관리책임자-정 사원번호(ID), Nullable = Y, VARCHAR2(20)
    mdl_nm	        string 모델 명, Nullable = Y, VARCHAR2(50)
    mnfc_cmpy_id	string 제조업체 ID, Nullable = Y, VARCHAR2(30)
    rfid_id	        string RFID ID, Nullable = Y, VARCHAR2(30)
    sub_user_id	    string 관리책임자-부 사원번호(ID), Nullable = Y, VARCHAR2(20)
    use_year	    integer 사용 년수, Nullable = Y, NUMBER(3)
    valid_ymd	    string 유효기간, Nullable = Y, VARCHAR2(8)
    work_step	    string 사업단계, Nullable = Y, VARCHAR2(7)
    */
const updateColumns = {
    abdn_dt : null,
    amt     : 0,
    del_yn  : 'N',
    fclt_id : null,
    fclt_lctn : null,
    fclt_nmbr : 0,
    fclt_type : null,
    istl_cmpy_id : null,
    istl_dt : null,
    istl_lctn_addr : null,
    main_user_id : null,
    maint_cmpy_id : null,
    mdl_nm: null,
    mnfc_cmpy_id : null,
    rfid_id: null,
    use_year: 0,
    valid_ymd : null,
    work_step : null,
}

const testData = {
    abdn_dt : null,
    amt     : 0,
    del_yn  : 'N',
    fclt_id : 1,
    fclt_lctn : "평택 도로",
    fclt_nmbr : 1,
    fclt_type : 'CCTV',
    istl_cmpy_id : '1002',
    istl_dt : new Date(),
    istl_lctn_addr : '평택 도로',
    main_user_id : null,
    mdl_nm: 'Sony Camera',
    mnfc_cmpy_id : '1002',
    maint_cmpy_id : '1002',
    rfid_id: null,
    use_year: 0,
    valid_ymd : 10,
    work_step : 0,
}

const modalDiv = $(`
<div class="modal-background">
    <div class="modal-container b0 dx-theme-border-color dx-theme-background-color">
        <div class="b0 dx-theme-border-color">
            <div class="modal-title-box dx-nav-item">
                <div class="modal-title">CCTV 미등록 시설물 정보</div>
                <div>
                    <div class="modal-cancel"></div>
                </div>
            </div>
            <div class="fclt-info b2 dx-theme-border-color">
                <div class="fclt-info-box b0 dx-theme-border-color">
                    <div class="serve-title dx-nav-item b2 dx-theme-border-color">시설물 목록</div>
                    <div>
                        <div class="unregistered-list"></div>
                    </div>
                </div>
                <div class="select-unreg-box">
                    <div>
                        <div class="cancel-unreg-btn"></div>
                    </div>
                    <div class="ml-5">
                        <div class="select-unreg-btn"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>`
);

let _modalTitle;
const _apiUri       = '/api/facility/manager/info';

$(()=>{
    //모달 관련
    $('body').append(modalDiv);
    modalDiv.css('display','none');
    _modalTitle = $('.modal-title');
    unregList = $('.unregistered-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 :'multiple',
            showCheckBoxesMode  : "onClick"
        },
        keyExpr : 'fclt_id',
        paging: {
            enabled: false,
            pageSize: 1000,
        },
        scrolling: {
            mode: 'standard',
        },
        columns:  [
            {
                caption   : '시설물 유형',
                dataField : "fclt_type",
                width     : 120,
                alignment : 'center',
            },
            {
                caption   : '시설물 ID',
                dataField : "fclt_id",
                alignment : 'center',
                width     : 140,
                sortIndex : 0,
                sortOrder : "asc",
            },
            {
                dataField : "fclt_lctn",
                caption   : "시설물 위치",
                alignment : "center",
                cellTemplate(c,e) {
                    alignTemplate(c, e, "left");
                }
            },
        ],
    }).dxDataGrid('instance');
    unregCancelBtn = new dxBtn($('.cancel-unreg-btn'), '취소', 'close', 'outlined', null, null, false, true);
    unregSaveBtn   = new dxBtn($('.select-unreg-btn'), '저장', 'save', 'outlined', null, null, false, true);
    unlegClose     = new dxBtn($('.modal-cancel'), null, 'close', 'text', null, null, false, true);
    unlegClose.onClick(hideUnlegList);
    unregCancelBtn.onClick(hideUnlegList);
    unregSaveBtn.onClick(uregSaveBtnClick);


    //좌측 상단 시설물 종류
    fcltType = new dxSelect($('.fclt_type'), 'outlined', 150, 30, 'cmmn_cd_kor_nm', 'cmmn_cd', false, 'fclt_type', '시설물 종류');
    fcltType.onItemClick((e)=>fetchListAllData(e,itemData.cmmn_cd, e.itemData.cmmn_cd_kor_nm));
    
    //우측 상단 닫기 버튼
    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);
    fcltId    = new dxTxt($('.fclt_id'), 'fclt_id', 30, '시설물 ID', 150, 30, null, true);
    fcltLctn  = new dxTxt($('.fclt_lctn'), 'fclt_lctn', 100, '설치위치', 250, 30, null, true);
    istlCmpy  = new dxSelect($('.istl_cmpy'), 'outlined', 150, 30, 'cmpy_nm', 'cmpy_id', true, 'istl_cmpy_id', '설치업체');
    makeCmpy  = new dxSelect($('.make_cmpy'), 'outlined', 150, 30, 'cmpy_nm', 'cmpy_id', true, 'mnfc_cmpy_id', '제조업체');
    mngrCmpy  = new dxSelect($('.mngr_cmpy'), 'outlined', 150, 30, 'cmpy_nm', 'cmpy_id', true, 'maint_cmpy_id', '유지보수업체');
    mdlNm     = new dxTxt($('.mdl_nm'), 'mdl_nm', 50, '모델명', 250, 30, null, true);
    istlDt    = new dxDate($('.istl_dt'), 'yyyy-MM-dd', '설치일자', 120, 30, 'date', null, 'istl_dt');
    //makeDt    = new dxDate($('.make_dt'), 'yyyy-MM-dd', '제조일자', 120, 30, 'date', null, 'make_dt');
    _inputArr  = [
        fcltId,
        istlDt,
        fcltLctn,
        istlCmpy,
        makeCmpy,
        mngrCmpy,
        mdlNm,
        //makeDt,
    ]
    addBtn.onClick(addBtnClick);
    cancelBtn.onClick(cancelBtnClick);
    editBtn.onClick(editBtnClick);
    saveBtn.onClick(saveBtnClick);
    delBtn.onClick(delBtnClick);
    istlDt.setReadOnly(true);
    //makeDt.setReadOnly(true);

    //시설물 리스트 테이블
    _regListTable = $('.grid').width('100%').height('100%').dxDataGrid({
        dataSource : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        idDataText              : '표출할 정보가 없습니다.',
        headerFilter: {
            visible: true,
        },
        selection  : {
            mode :'single'
        },
        keyExpr : 'fclt_id',
        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   : '시설물 ID',
                dataField : "fclt_id",
                alignment : 'center',
                width     : 140,
                sortIndex : 0,
                sortOrder : "asc",
            },
            {
                dataField : "fclt_lctn",
                caption   : "설치위치",
                alignment : "center",
                cellTemplate(c,e) {
                    alignTemplate(c, e, "left");
                }
            },
            {
                dataField    : "istl_cmpy_id",
                caption      : "설치업체",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'cmpy_nm',
                    valueExpr   : 'cmpy_id',
                }
            },
            {
                dataField    : "istl_dt",
                caption      : "설치일자",
                alignment    : "center",
                dataType     : "date",
                format       : "yyyy-MM-dd",
            },
            {
                dataField    : "maint_cmpy_id",
                caption      : "유지보수업체",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'cmpy_nm',
                    valueExpr   : 'cmpy_id',
                }
            },
            {
                dataField    : "main_user_id",
                caption      : "관리책임자(정)",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'user_id',
                    valueExpr   : 'main_user_id',
                }
            },
            {
                dataField    : "sub_user_id",
                caption      : "관리책임자(부)",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'user_id',
                    valueExpr   : 'sub_user_id',
                }
            },
            {
                dataField    : "mnfc_cmpy_id",
                caption      : "제조업체",
                alignment    : "center",
                lookup       : {
                    dataSource  : null,
                    displayExpr : 'cmpy_nm',
                    valueExpr   : 'cmpy_id',
                }
            },
            // {
            //     dataField    : "make_dt",
            //     caption      : "제조일자",
            //     visible      : false,
            //     alignment    : "center",
            //     dataType     : "date",
            //     format       : "yyyy-MM-dd",
            // },
            {
                dataField    : "mdl_nm",
                caption      : "모델명",
                alignment    : "center",
            },
        ],
        onRowClick(e){
            regListTableClick(e, setInputValue)
        },
    }).dxDataGrid("instance");
    
    fetchBaseData();
})

/**
 * 초기 수신 데이터(회사 코드, 시설물 유형 코드, 시설물 리스트)
 */
function fetchBaseData(){
    getDataAsync('/api/facility/company', recvComboData);
    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);
        fetchListAllData(value, jsonData[0][fcltType.displayExpr]);
    }
}

function recvListData(jsonData, table){
    table.option('dataSource', jsonData);
    table.clearSelection();
    table.option('focusedRowIndex', -1);
}

function recvComboData(jsonData) {
    istlCmpy.setDataSource(jsonData);
    makeCmpy.setDataSource(jsonData);
    mngrCmpy.setDataSource(jsonData);
    _regListTable.option('columns[2].lookup.dataSource', jsonData);
    _regListTable.option('columns[4].lookup.dataSource', jsonData);
    _regListTable.option('columns[7].lookup.dataSource', jsonData);
}


/**
 * 등록, 미등록 리스트 데이터 초기화
 * @param {*} data 시설물 유형 코드
 * @param {*} display 시설물 유형 설명
 */
 function fetchListAllData(data, display){
    inputArrDataInit(true);
    const fcltType = encodeURIComponent(data);
    getDataAsync(_apiUri+ '/?fcltType=' + fcltType, recvListData, _regListTable);
    getDataAsync(_apiUri+ '/unreg/?fcltType=' + fcltType, recvListData, unregList);
    _modalTitle.text( display + ' 미등록 시설물');
}

/**
 * 모달 관련(리스트 감추기, 미등록 리스트 저장)
 */
function hideUnlegList(){
    modalDiv.css('display', 'none');
    unregList.clearSelection();
    unregList.option('focusedRowIndex', -1);
}

function uregSaveBtnClick(){
    const selectedData = unregList.getSelectedRowsData();
    const value = fcltType.getValue();
    let display = null;
    const typeDataArr = fcltType.getDataSource();
    typeDataArr.map((item)=>{
        if (item.cmmn_cd === fcltType.getValue()){
            display = item.cmmn_cd_kor_nm;;
        };
    })
    if (selectedData.length <= 0) return notSelectMsg(display + ' 미등록 시설물');
    const result = postInsertUpdate( _apiUri + '/reg', selectedData);
    if (result > 0) {
        insResultMsg(fcltType.getValue() + ' 미등록 시설물');
        fetchListAllData(value, display);
        hideUnlegList();
    }
}

/**
 * CRUD 구역(추가, 수정, 저장, 삭제, 취소)
 */
function addBtnClick() {
    modalDiv.css('display', 'flex');
    unregList.refresh();
}


function editBtnClick(){
    elementSttsChange(false);
    _inputArr.map((item)=>{
        if (item.column !== 'fclt_id') {
            item.setReadOnly(false);
        }
    })
}

function saveBtnClick(){
    const selectedData = _regListTable.getSelectedRowsData()[0];
    const updateData = {...selectedData};
    for (let input of _inputArr) {
        const column = input.column;
        if (column !== 'istl_dt' && column !== 'make_dt') {
            updateData[column] = input.getValue();
        }
        else {
            updateData[column] = input.getSendDateValue();
        }
    }
    console.log(updateData);
    const result = postInsertUpdate(_apiUri, [updateData]);
    if (result > 0) {
        let display = getTypeName();
        const value = fcltType.getValue();
        insResultMsg('시설물 ID : ' + updateData.fclt_id + '<br>' + display + ' 시설물');
        const param = encodeURIComponent(value);
        getDataAsync(_apiUri + '/?fcltType=' + param, recvResultData, [_regListTable, updateData.fclt_id, updateData]);
    }
}function recvResultData(jsonData, args){
    const table = args[0];
    const key   = args[1];
    table.option('dataSource', jsonData);
    table.refresh().done(()=>{
        table.clearSelection();
        table.selectRows(key).done(()=>{
            table.option('focusedRowKey', key);
            elementSttsChange(true);
            _inputArr.map((item)=>{
                item.setReadOnly(true);
            })
        })
    })
}

function delBtnClick(){
    const selectedData = _regListTable.getSelectedRowsData()[0];
    const id = selectedData.fclt_id;
    let display = getTypeName();
    confirmMessage("시설물 ID : " 
                    + id 
                    + "<br>선택하신 " + display 
                    + " 시설물 정보를 삭제하시겠습니까?").done((yes)=>{
                        if (yes === true) {
                            const result = deleteDataIds(_apiUri, [id]);
                            if (result > 0) {
                                delResultMsg('시설물 ID : ' + id + '<br>' + display + ' 시설물');
                                fetchListAllData(fcltType.getValue(), display);
                            }
                        }   
    })
}

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;
}

function cancelBtnClick(){
    let selectedData = _regListTable.getSelectedRowsData();
    elementSttsChange(true);
    if (selectedData.length > 0){
        setInputValue(selectedData[0], true);
    }
    else {
        inputArrDataInit(true);
    }
}

/**
 * 요소 상태 변경 함수 
 * @param {*} stts true, false
 */
function elementSttsChange(stts){
    editBtn.setVisible(stts);
    addBtn.setVisible(stts);
    delBtn.setVisible(stts);
    saveBtn.setVisible(!stts);
    cancelBtn.setVisible(!stts);
    _regListTable.option('disabled', !stts);
    fcltType.setDisabled(!stts);
}

function inputArrDataInit(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 dateInit(){
    istlDt.setValue(new Date());
    //makeDt.setValue(new Date());
}

function selectBoxInit(){
    const selectBoxArr = [   
            istlCmpy,
            makeCmpy,
            mngrCmpy,
    ]
    selectBoxArr.map((item)=>{
        if (item.getDataSource()) {
            item.setValue(item.getDataSource()[0][item.valueExpr]);
        }
    })
}

/**
 * 시설물 테이블 클릭 함수
 */
function regListTableClick(e, callback){
    editBtn.setDisabled(false);
    delBtn.setDisabled(false);
    callback(e.data, true);
}
