import { TMapMngr, TFclt } from "/js/vworld/map-mngr.js";
import { LayerIndex } from "/js/vworld/map-const.js";

let _mapManager = null;
let _selectFcltNmbr = null;
const _lyrIdx = LayerIndex.Dsrc;
const _pageName = 'DSRC 제어기 관리';
//우측 섹션 관련
let _managerData     = [];
let _managerTable     = null;
let cctvX            = null;
let cctvY            = null;
let saveBtn          = null;
let cancleBtn        = null;
let editBtn          = null;
let _idArr           = null;
let totClctAbnrBasi  = null;
const _ipExpr        = /^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}$/;
const _updateColumns = {
    clct_abnr_basi   : 0,
    del_yn           : 'N',
    istl_lctn_addr   : null,
    istl_lctn_nm     : null,
    log_cnnc_id      : null,
    log_cnnc_pw      : null,
    mnfc_cmpy_cd     : 0,
    rse_ctlr_id      : null,
    rse_ctlr_ip      : null,
    rse_ctlr_local_no: 0,
    rse_ctlr_nmbr    : 0,
    rse_ctlr_port    : 0,
    rse_mcu_id       : null,
    rse_nm           : null,
    rse_type_cd      : 'DSRC',
    x_crdn           : 0,
    y_crdn           : 0,
}

    
let dsrcMcuId     = null;
let dsrcCtlrId    = null;
let dsrcCtlrNmbr  = null;
let logCnncId     = null;
let logCnncPw     = null;
let clctAbnrBasi  = null;
let mnfcCmpyCd    = null;
let dsrcCtlrPort  = null;

//공통
let commonUri        = '/api/rse/tb_rse_ctlr';
const pageMsg        = 'DSRC'
const inputArr = [
    dsrcCtlrNmbr = {
        box      : null,
        option   : 230,
        readOnly : true,
        column   : "rse_ctlr_nmbr",
        must     : true,
        label    : "ID",
        max      : 10,
    },
    dsrcCtlrId = {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        label    : "DSRC ID",
        column   : "rse_ctlr_id",
        id       : true,
        max      : 30,
    },
    dsrcMcuId = {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        label    : "도로지점 ID",
        column   : "rse_mcu_id",
        max      : 30,
    },
    logCnncId = {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        label    : "로그접속 ID",
        column   : "log_cnnc_id",
        max      : 64,
    },
    logCnncPw = {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        label    : "로그접속 비밀번호",
        column   : "log_cnnc_pw",
        max      : 64,
    },
    {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        label    : "설치 위치",
        column   : "istl_lctn_nm",
        max      : 40,
    },
    {
        box      : null,
        option   : 230,
        readOnly : false,
        column   : "rse_ctlr_ip",
        must     : true,
        ip       : true,
        label    : "IP Address",
        max      : 20,
    },
    dsrcCtlrPort = {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        port     : true,
        label    : "PORT",
        column   : "rse_ctlr_port",
        max      : 5,
    },
    mnfcCmpyCd = {
        box         : null,
        option      : 230,
        readOnly    : false,
        must        : true,
        port        : true,
        type        : 'select',
        label       : "제조업체",
        displayExpr : 'cmmn_cd_kor_nm',
        valueExpr   : 'cmmn_cd',
        column      : "mnfc_cmpy_cd",
        max         : 5,
    },
    clctAbnrBasi = {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        port     : true,
        type     : 'number',
        label    : "수집 이상 기준",
        column   : "clct_abnr_basi",
        min      : 0,
        max      : 9999999,
    },
    cctvX = {
        box      : null,
        option   : 130,   
        readOnly : false,
        must     : true,
        label    : "X좌표",
        value    : '0.0000000',
        method   : function(text){
            crdnChanges(text, 3);
        },
        column   : 'x_crdn',
        max      : 11,
    },
    cctvY = {
        box      : null,
        option   : 130,   
        readOnly : false,
        must     : true,
        label    : "Y좌표",
        value    : '0.0000000',
        method   : function(text){
            crdnChanges(text, 2);    
        },
        column   : "y_crdn",
        max      : 10,
    },
]

const btnArr    = [
    editBtn = {
        class       : "edit-btn",
        box         : null,
        option      : 80,
        visible     : true,
        disabled    : true,
        dbdsb       : false,
        edit        : {
            click   : {
                visible  : false,
                disabled : false,
            },
            cancle : {
                visible  : true,
                disabled : false,
            }
        },
        add         : {
            click   : {
                visible  : false,
                disabled : false,
            },
            selected : {
                visible  : true,
                disabled : false,
            }
            ,
            unSelected : {
                visible  : true,
                disabled : true,
            },
        }
        ,
        addvsb      : false,
        icon        : "edit",
        text        : "편집",
        method      : function(){
            editEvent();
        }
    },
    cancleBtn = {
        class       : "cancle-btn",
        box         : null,
        option      : 80,
        visible     : false,
        disabled    : false,
        dbdsb       : false,
        edit        : {
            click   : {
                visible  : true,
                disabled : false,
            },
            cancle : {
                visible  : false,
                disabled : false,
            }
        },
        add         : {
            click   : {
                visible  : true,
                disabled : false,
            },
            selected : {
                visible  : false,
                disabled : false,
            }
            ,
            unSelected : {
                visible  : false,
                disabled : false,
            },
        },
        addvsb      : true,
        icon        : "close",
        text        : "취소",
    },
    {
        class       : "add-btn",
        box         : null,
        option      : 80,
        disabled    : false,
        visible     : true,
        edit        : {
            click   : {
                visible  : true,
                disabled : true,
            },
            cancle : {
                visible  : true,
                disabled : false,
            }
        },
        add         : {
            click   : {
                visible  : true,
                disabled : true,
            },
            selected : {
                visible  : true,
                disabled : false,
            }
            ,
            unSelected : {
                visible  : true,
                disabled : false,
            },
        },
        dbdsb       : false,
        adddsb      : true,
        icon        : "plus",
        text        : "추가",
        method      : function(){
            addEvent();
        }
    },
    {
        class       : "del-btn",
        box         : null,
        option      : 80,
        disabled    : true,
        visible     : true,
        edit        : {
            click   : {
                visible  : true,
                disabled : true,
            },
            cancle : {
                visible  : true,
                disabled : false,
            }
        },
        add         : {
            click   : {
                visible  : true,
                disabled : true,
            },
            selected : {
                visible  : true,
                disabled : false,
            }
            ,
            unSelected : {
                visible  : true,
                disabled : true,
            },
        },
        dbdsb       : false,
        adddsb      : true,
        icon        : "minus",
        text        : "삭제",
        method      : function(){
            const resCtlrNmbr = _managerTable.getSelectedRowsData()[0].rse_ctlr_nmbr;
            confirmMessage(pageMsg 
                        + " 제어기 관리 번호 : " 
                        + resCtlrNmbr
                        + "<br>선택하신 " 
                        + pageMsg 
                        + " 정보를 삭제하시겠습니까?").done((yes)=>{
                            if (yes === true){
                                const result = deleteData(commonUri, resCtlrNmbr)
                                if (result > 0) {
                                    delResultMsg(pageMsg);
                                    boxInit();
                                    buttonReset('add','unSelected');
                                    deleteFcltObject(resCtlrNmbr);
                                    _managerTable.option('focusedRowKey', null);
                                    _managerData= refresh( _managerTable, _managerData, commonUri);
                                }
                                //return alertError( pageMsg+' 정보가 삭제되지 않았습니다.')
                            }
                        })
        }
    },
    saveBtn = {
        class       : "save-btn",
        box         : null,
        option      : 80,
        disabled    : true,
        dbdsb       : true,
        edit        : {
            click   : {
                visible  : true,
                disabled : false,
            },
            cancle : {
                visible  : true,
                disabled : true,
            }
        },
        add         : {
            click   : {
                visible  : true,
                disabled : false,
            },
            selected : {
                visible  : true,
                disabled : true,
            }
            ,
            unSelected : {
                visible  : true,
                disabled : true,
            },
        },
        adddsb      : false,
        visible     : true,
        icon        : "save",
        text        : "저장",
    },
   
];
let hsTotApplyBtn = null;
$(()=>{
    hsTotApplyBtn = new dxBtn($('.hs-tot-apply-btn'), '일괄적용', 'save', 'outlined', null, 31, false, true);
    hsTotApplyBtn.onClick(hsTotApplyBtnClick);
    totClctAbnrBasi = new dxNumber($('.tot_clct_abnr_basi'), 'outlined', 100, 30, 0, 9999999, true, 1, 'tot_clct_abnr_basi', '#0', false);
    //상단 닫기 버튼
    $(".cancle-button").dxButton({
        text:'닫기',
        icon:'close',
        height:'30px',
        width: '80px',
        stylingMode:'outlined',
        onClick(){
            window.close();
        }
    }).dxButton("instance")
    
    //텍스트 박스 화면 세팅
    inputArr.map((item)=>{

        if (item.type === 'select') {
            item.box = $("." + item.column).dxSelectBox({
                width       : item.option,
                stylingMode : 'outlined',
                readOnly    : true,
                displayExpr : item.displayExpr,
                valueExpr   : item.valueExpr,
                dataSource  : item.dataSource,
                height      : 27,
            }).dxSelectBox("instance");
        }
        else if (item.type === 'number') {
            item.box = $("." + item.column).dxNumberBox({
                width           : item.option,
                stylingMode     : 'outlined',
                readOnly        : true,
                max             : item.max,
                min             : item.min,
                format          : '#0',
                height          : 27,
                showSpinButtons : true,
            }).dxNumberBox("instance");
        }
        else {
            item.box = $("." + item.column).dxTextBox({
                width       : item.option,
                stylingMode : 'outlined',
                readOnly    : true,
                maxLength   : item.max,
                height      : 27,
            }).dxTextBox("instance");
            if(item.value){
                item.box.option("value",item.value);
            }
            if(item.method){
                item.box.on("valueChanged",item.method);
            }
        }
    })

    //버튼 박스 화면 세팅
    btnArr.map((item)=>{
        item.box = $("." + item.class).dxButton({
            icon              : item.icon,
            width             : item.option,
            text              : item.text,
            visible           : item.visible,
            disabled          : item.disabled,
            focusStateEnabled : false,
            stylingMode       : 'outlined',
            onClick(){
                if(item.method){
                    item.method();
                }
            }
        }).dxButton("instance")
    })
    
    logCnncPw.box.option('mode', 'password');
    doMap();
    getData( commonUri, _managerData);
    updateIcon();
    
     //소통정보 이력분석 테이블
     _managerTable = $(".manager-table").width('100%').height('100%').dxDataGrid({
        dataSource              : _managerData[0],
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        focusedRowEnabled       : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        keyExpr :'rse_ctlr_nmbr',
        
        headerFilter: {
            visible: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        columns:[
            {
                dataField    : "rse_ctlr_id",
                caption      : "DSRC ID",
                cssClass     : 'padding-ctrl',
                alignment    : "center",
            },
            {
                dataField    : "rse_nm",
                caption      : "명칭",
                cssClass     : 'padding-ctrl',
                alignment    : "center",
                cellTemplate(c,e){
                    c.css('text-align','left')
                    return c.text(e.displayValue);
                }
            },
        ],
        onRowDblClick(e){
            _selectFcltNmbr = e.data.rse_ctlr_nmbr;
            inputArr.map((item)=>{
                item.box.option('value', e.data[item.column])
            });
            
            btnArr.map((item) =>{
                item.box.option("disabled",item.dbdsb)
            });

            selectFcltObject(_selectFcltNmbr);
        }
    }).dxDataGrid("instance");
    fetchMnfcCmpyCdData();
})

/**
 * @TODO 전체 수집이상 기준 일괄 적용 API 필요
 * uri만 넣어주면 됨
 */
function hsTotApplyBtnClick(){
    const clctAbnrBasiVal = totClctAbnrBasi.getValue();
    confirmMessage('수집이상 기준 정보를 일괄 저장 하시겠습니까?').done((yes)=>{
        if (yes === true) {
            const result = putUpdate(commonUri + '/clct-abnr-basi/' + encodeURIComponent(clctAbnrBasiVal), clctAbnrBasiVal)
            if (result > 0) {
                alertConfirm(pageMsg + ' 수집이상 기준 정보를 일괄 저장 하였습니다.');
                _managerData = [];
                getData( commonUri, _managerData);
                const selectedData = _managerTable.getSelectedRowsData();
                _managerTable.option('dataSource', _managerData[0]);
                if (selectedData && selectedData.length > 0) {
                    clctAbnrBasi.box.option('value', clctAbnrBasiVal);
                }
            }
        }
    })
}
function fetchMnfcCmpyCdData(){
    getDataAsync('/api/database/code/cmmn-cd/RMF', recvMnfcCompyData);
}

function recvMnfcCompyData(jsonData){
    if (jsonData.length > 0){
        jsonData.map((item)=>{
            if (item.cmmn_cd) item.cmmn_cd = Number(item.cmmn_cd);
        })
    }   
     mnfcCmpyCd.box.option('dataSource', jsonData);
}

function editEvent(){
    cancleBtn.box.off('click');
    cancleBtn.box.on('click', () => editCancle());
    editFcltObject(_selectFcltNmbr, true);
    eventOn();
    
    btnArr.map((item)=>{
        item.box.option( 'visible', item.edit.click.visible   );
        item.box.option( 'disabled', item.edit.click.disabled );
    });
    saveBtn.box.off('click');
    saveBtn.box.on('click', () => saveEvent('edit'));
}

function getIdArr(){
    let idArr = [];
    if (_managerData[0].length > 0) {
        _managerData[0].map((obj)=>{
            if(obj.rse_ctlr_id)idArr.push(obj.rse_ctlr_id);
        })
    }
    return idArr;
}

/**
 * 저장 버튼 클릭 이벤트(DSRC 제어기 정보 저장)
 * @TODO save Api 필요
 * @param {*} type 추가/수정 구분
 * @returns 값이 유효하지 않을때 이벤트 정지
 */
function saveEvent(type) {
    _idArr = getIdArr();
    for (let input of inputArr) {
        const box   = input.box;
        const value = getValue(box);
        const must  = input.must;
        let   max   = input.max;
        if (input.type === 'number') {
            max = input.max.length;
        }
        const ip    = input.ip;
        const port  = input.port;
        const label = input.label;
        const empty = nullChecker(value) === "";
        if (empty) {
            if (must) {
                return alertWarning('필수 항목을 입력해주세요. [ ' + label +' ]', null, box);
            }
        }
        else {
            if (max && getByteLength(value) > max) {
                return alertWarning(max + ' 바이트 이내로 입력해주세요. [ ' + label +' ]', null, box);
            }
            if (ip && !_ipExpr.test(value)) {
                return alertWarning('IP 형식에 맞게 입력해주세요. [ ' + label +' ]', null, box);
            }
            if (port && isNaN(value)) {
                return alertWarning('PORT 형식에 맞게 입력해주세요. [ ' + label +' ]', null, box);
            }
            if (input.id && _idArr.includes(value) && !type) {
                return alertWarning( "DSRC ID : " + value + "<br>이미 사용중인 DSRC ID 입니다.", null, box);
            }

        }
    }

    let updateData = {..._updateColumns};
    if (type === 'edit') {
        const rowData = _managerTable.getSelectedRowsData()[0];
        for (let key in updateData){
            updateData[key] = rowData[key]; 
        }
        const idVal = getValue(dsrcCtlrId.box);
        if (_idArr.includes(idVal) && idVal !== rowData.rse_ctlr_id){
            return alertWarning( "DSRC ID : " + idVal + "<br>이미 사용중인 DSRC ID 입니다.", null, dsrcCtlrId.box);
        }
    }
    inputArr.map((item)=>{
        if (item.column) updateData[item.column] = item.box.option("value");
    })

    if (!type) {
       updateData.rse_nm = updateData.istl_lctn_nm;
    }
    /**
     * 여기 업데이트 API 
     */
    let result = postInsertUpdate(commonUri + "/" + updateData.rse_ctlr_nmbr, updateData);
    if (result > 0) {
        insResultMsg(pageMsg)
        _managerData = refresh(_managerTable, _managerData, commonUri);
        _managerTable.clearSelection();
        _managerTable.refresh().done(function(){
            _managerTable.selectRows(updateData.rse_ctlr_nmbr, true).done(()=>{
                _managerTable.option('focusedRowKey', updateData.rse_ctlr_nmbr);
                boxPull();
                buttonReset('add','selected');
                eventCancle();
            })
        })
    }
    
}

function editCancle(){
    eventCancle();
    boxPull();
    buttonReset( 'edit', 'cancle' );
}

function addCancle(){
   
    eventCancle();

    if(_managerTable.getSelectedRowsData().length > 0){
        boxPull();
        buttonReset('add','selected')
        return 
    }

    boxInit();
    buttonReset('add','unSelected');

}

/**
 * @TODO DSRC ID, 도로 지점 ID 생성 방법
 */
function addEvent(){
    
    eventOn();
    boxInit();
    let center = _mapManager.getCenter();
    cancleBtn.box.off('click');
    cancleBtn.box.on('click', () => addCancle());
    cctvX.box.option('value', center[0].toFixed(7));
    cctvY.box.option('value', center[1].toFixed(7));
    clctAbnrBasi.box.option('value', 1);
    let addNum = getNewNmbr();
    dsrcCtlrNmbr.box.option( 'value', addNum );
    let data = mnfcCmpyCd.box.option('dataSource');
    if (data.length > 0) {
        mnfcCmpyCd.box.option('value', data[0][mnfcCmpyCd.valueExpr])
    }
    addFcltObject(addNum);
    _selectFcltNmbr = addNum;
    btnArr.map((item)=>{
        item.box.option( 'visible', item.add.click.visible );
        item.box.option( 'disabled', item.add.click.disabled );
    });

    saveBtn.box.off('click');
    saveBtn.box.on('click', () => saveEvent());
    
}

function boxPull(){
    let selectedRow = _managerTable.getSelectedRowsData()[0]
    inputArr.map((item)=>{
        item.box.option('value', selectedRow[item.column]);
    })
}

function boxInit(){
    inputArr.map((item)=>{
        if(item.value) return item.box.option('value', item.value);
        item.box.option("value", null);
    })
}

function buttonReset(eventName, option){
    btnArr.map((item)=>{
        item.box.option( 'visible', item[eventName][option].visible   );
        item.box.option( 'disabled', item[eventName][option].disabled );
    })
}

function eventCancle(){
    updateIcon();
    dsblOffBtn(_managerTable);
    hsTotApplyBtn.setDisabled(false);
    inputArr.map((item)=>{
        item.box.option("readOnly", true);
    });

    if(_managerTable.getSelectedRowsData().length > 0){
        _selectFcltNmbr = _managerTable.getSelectedRowsData()[0].rse_ctlr_nmbr;
        selectFcltObject(_selectFcltNmbr);
    };
}

function eventOn(){
    dsblOnBtn(_managerTable);
    hsTotApplyBtn.setDisabled(true);
    inputArr.map((item)=>{
        item.box.option("readOnly", item.readOnly);
    })

}

/**
 * 신규 생성 ID 
 * @TODO 신규 ID 생성 Api 필요
 * @returns 신규 DSRC ID
 */
function getNewNmbr() {
    let newId = [];
    getData(commonUri + "/new-id", newId);
    if (nullChecker(newId[0]) !== ""){
        newId = newId[0].new_id;
    }
    else {
        newId = null;
    }
    return newId;
}

/**
 * 지도 인터페이스 함수........
 */
 function doMap() {
    _mapManager = new TMapMngr("traf-hs-map", "tooltip");
    _mapManager.setEditMode(_lyrIdx, true);
    _mapManager.showLayer(_lyrIdx, true);
    _mapManager.showFcltObjectText(_lyrIdx, true);
    _mapManager.onFcltDragEndFunc = onFcltDragEndFunc; // 객체(시설물) 편집시 객체 이동후 좌표 반환
    _mapManager.onMouseClickFunc = onMouseClickFunc; // 객체 마우스 클릭 이벤트 반환
    fetchMapIconBar($('.map-bar'), _mapManager, _lyrIdx, _pageName);
}
function onFcltDragEndFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY) {
    if (ALyrIdx != _lyrIdx) {
        return;
    }
    if (ANmbr === _selectFcltNmbr) {
        cctvX.box.option("value", ACoordX.toFixed(7));
        cctvY.box.option("value", ACoordY.toFixed(7));
    }
    //onsole.log(`onFcltDragEndFunc, ${ALyrIdx}, ${ALyrName}, ${ANmbr}, ${ACoordX}, ${ACoordY}`);
}
function onMouseClickFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY, X, Y) {
    if (ALyrIdx != _lyrIdx) {
        return;
    }
    //console.log(`onMouseClickFunc, ${ALyrIdx}, ${ALyrName}, ${ANmbr}, ${ACoordX}, ${ACoordY}, ${X}, ${Y}`);
    const obj = _mapManager.findLayerObject(ALyrIdx, ANmbr);
    if (!obj) {
        return;
    }
    else {
        if (_selectFcltNmbr === ANmbr) {
            return;
        }
        if (!editBtn.box.option('visible')) {
            return;
        }
        _selectFcltNmbr = ANmbr;
        selectFcltObject(_selectFcltNmbr);
        _managerTable.selectRows(ANmbr).done(()=>{
            _managerTable.option('focusedRowKey',ANmbr);
            const selectedData = _managerTable.getSelectedRowsData()[0];
            inputArr.map((item) => {
                item.box.option("value", selectedData[item.column]);
            });
            btnArr.map((item) => {
                item.box.option("disabled", item.dbdsb);
            });
        });
    }
}

/**
 * 지도에 시설물 객체 정보를 그린다.
 */
 function updateIcon() {
    // 기존 객체를 모두 삭제한다.
    _mapManager.removeLayerObject(_lyrIdx);
    if (_managerData[0] && _managerData[0].length > 0) {
        // 시설물 객체를 지도에 그린다.
        const objs = new Array();
        _managerData[0].forEach((obj) => {
            const item = new TFclt(obj.rse_ctlr_nmbr, obj.istl_lctn_nm, obj.x_crdn, obj.y_crdn);
            objs.push(item);
        });

        _mapManager.initFcltObject(_lyrIdx, objs);
    }
}
function selectFcltObject(ANmbr) {
    _mapManager.selectLayerObject(_lyrIdx, ANmbr);
}
function editFcltObject(ANmbr, AIsEdit) {
    _mapManager.editFcltObject(_lyrIdx, ANmbr, AIsEdit, AIsEdit ? "1" : "0");
}
function deleteFcltObject(ANmbr) {
    _mapManager.deleteFcltObject(_lyrIdx, ANmbr);
    _selectFcltNmbr = null;
}
function addFcltObject(ANmbr) {
    _mapManager.createFcltObject(_lyrIdx, ANmbr, "New", "New", "1" /*아이콘색결정,시설물유형_N.png*/ /*, x_crdn, y_crdn*/);
}



