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.Vds;
const _pageName = 'VDS 제어기 관리';
//우측 섹션 관련
let _managerData     = [];
let _managerTable     = null;
let ctlrMngmNmbr     = null;
let vdsCtlrId        = null;
// let ctlrClctCycl     = null;
let cctvX            = null;
let cctvY            = null;
let trmnPort         = null;
let saveBtn          = null;
let cancleBtn        = null;
let valdYn           = null;
let _idArr           = null;
let vdsTypeCd        = null;
let groupNo          = null;
let vdsCtlrLocalNo   = null;
let detectLanes      = null;
let istlLctnNm       = null;
let istlLctnAddr     = null;
let editBtn          = null;

const _ipExpr        = /^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}$/;
const _updateColumns = {
    del_yn : 'N',
    detect_lanes : 0,
    fan_mode : 2,
    fan_run_tmpr : 30,
    group_no: 0,
    hetr_mode : 2,
    hetr_run_tmpr : 0,
    istl_lctn_addr : null,
    istl_lctn_nm : null,
    stts_clct_cycl : 30,
    traf_clct_cycl : 30,
    vald_yn : 'N',
    vds_ctlr_id: null,
    vds_ctlr_ip : null,
    vds_ctlr_local_no : 0,
    vds_ctlr_nmbr : 0,
    vds_ctlr_port : 0,
    vds_nm : null,
    vds_type_cd : 'I',
    x_crdn: 0,
    y_crdn: 0
  }

//공통
let commonUri        = '/api/vds/manager/info';
const pageMsg        = 'VDS'
const inputArr = [
    ctlrMngmNmbr = {
        box      : null,
        option   : 230,
        readOnly : true,
        column   : "vds_ctlr_nmbr",
        must     : true,
        label    : "관리번호",
        max      : 20,
    },
    vdsCtlrId = {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        label    : "제어기 ID",
        column   : "vds_ctlr_id",
        id       : true,
        max      : 30,
    },
    {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        label    : "VDS 명칭",
        column   : "vds_nm",
        max      : 100,
    },
    vdsTypeCd = {
        box         : null,
        option      : 230,
        readOnly    : false,
        column      : "vds_type_cd",
        type        : 'select',
        valueExpr   : 'cmmn_cd',
        displayExpr : 'cmmn_cd_kor_nm',
        value       : "I",
        dataSource  : [],
    },
    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,
    },
    {
        box      : null,
        option   : 230,
        readOnly : false,
        column   : "vds_ctlr_ip",
        must     : true,
        ip       : true,
        label    : "제어기 IP",
        max      : 15,
    },
    trmnPort = {
        box      : null,
        option   : 230,
        readOnly : false,
        must     : true,
        port     : true,
        label    : "PORT",
        column   : "vds_ctlr_port",
        max      : 5,
    },
    groupNo        ={
        box      : null,
        option   : 100,
        readOnly : false,
        label    : '그룹번호',
        column   : 'group_no',
        value    : 1,
        min      : 0,
        max      : 99999,
        type     : 'number',
    },
    vdsCtlrLocalNo ={
        box      : null,
        option   : 100,
        readOnly : false,
        label    : '지역번호',
        value    : 1,
        min      : 0,
        column   : 'vds_ctlr_local_no',
        max      : 99999,
        type     : 'number',
    },
    detectLanes    ={
        box      : null,
        option   : 100,
        readOnly : false,
        label    : '검지기 차로수',
        must     : true,
        column   : 'detect_lanes',
        value    : 1,
        min      : 1,
        max      : 99,
        type     : 'number',
    },
    istlLctnNm     ={
        box      : null,
        option   : 230,
        readOnly : false,
        label    : '설치 위치',
        column   : 'istl_lctn_nm',
        max      : 40,
    },
    istlLctnAddr   ={
        box      : null,
        option   : 230,
        readOnly : false,
        label    : '설치 주소',
        column   : 'istl_lctn_addr',
        max      : 200,
    },
    valdYn = {
        box        : null,
        option     : 80,
        readOnly   : false,
        column     : "vald_yn",
        type       : 'select',
        value      : 'Y',
        dataSource : ['Y', 'N'],
    },
]

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(){
            confirmMessage(pageMsg 
                        + " 제어기 관리 번호 : " 
                        + _managerTable.getSelectedRowsData()[0].vds_ctlr_nmbr 
                        + "<br>선택하신 " 
                        + pageMsg 
                        + " 정보를 삭제하시겠습니까?").done((yes)=>{
                            if (yes === true){
                                const result = deleteData(commonUri, _managerTable.getSelectedRowsData()[0].vds_ctlr_nmbr)
                                if (result > 0) {
                                    delResultMsg(pageMsg);
                                    boxInit();
                                    buttonReset('add','unSelected');
                                    deleteFcltObject(_managerTable.getSelectedRowsData()[0].vds_ctlr_nmbr);
                                    _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        : "저장",
    },
   
];

$(()=>{

    //상단 닫기 버튼
    $(".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,
                height          : 27,
                showSpinButtons : true,
            }).dxNumberBox("instance");

            item.box.on('valueChanged', (e)=>{
                if (e.value === null) {
                    setValue(e.component, 1);
                }
            })
        }
        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")
    })
    
    
    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 :'vds_ctlr_nmbr',
        
        headerFilter: {
            visible: true,
        },
        scrolling: {
            mode: 'virtual',
        },
        columns:[
            {
                dataField    : "vds_ctlr_nmbr",
                caption      : "관리번호",
                cssClass     : 'padding-ctrl',
                width        : 100,
                alignment    : "center",
            },
            {
                dataField    : "vds_nm",
                caption      : "제어기 명칭",
                cssClass     : 'padding-ctrl',
                alignment    : "center",
                width        : 130,
                cellTemplate(c,e){
                    c.css('text-align','left')
                    return c.text(e.displayValue);
                }
            },
            {
                dataField    : "vds_ctlr_ip",
                caption      : "제어기 IP",
                cssClass     : 'padding-ctrl',
                width        : 100,
                alignment    : "center",
            },
            {
                dataField    : "vds_ctlr_port",
                caption      : "PORT",
                width        : 80,
                cssClass     : 'padding-ctrl',
                alignment    : "center",
            },
        ],
        onRowDblClick(e){
            console.log(e.data);
            _selectFcltNmbr = e.data.vds_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");
    fetchCdData();
})
function fetchCdData(){
    getDataAsync('/api/database/code/cmmn-cd/VDST', recvCdData);
}

function recvCdData(jsonData){
    vdsTypeCd.box.option('dataSource', jsonData);
    console.log(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.vds_ctlr_id)idArr.push(obj.vds_ctlr_id);
        })
    }
    return idArr;
}

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( "제어기 ID : " + value + "<br>이미 사용중인 제어기 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(vdsCtlrId.box);
        if (_idArr.includes(idVal) && idVal !== rowData.vds_ctlr_id){
            return alertWarning( "제어기 ID : " + idVal + "<br>이미 사용중인 제어기 ID 입니다.", null, vdsCtlrId.box);
        }
    }
    inputArr.map((item)=>{
        if (item.column) updateData[item.column] = item.box.option("value");
    })
    console.log(updateData);
    //ctrlIpNum
    let result = postInsertUpdate(commonUri + "/" + updateData.vds_ctlr_nmbr, updateData);
    if (result > 0) {
        insResultMsg(pageMsg)
        _managerData= refresh(_managerTable, _managerData, commonUri);
        _managerTable.clearSelection();
        _managerTable.refresh().done(function(){
            _managerTable.selectRows(updateData.vds_ctlr_nmbr, true).done(()=>{
                _managerTable.option('focusedRowKey', updateData.vds_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');

}

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));
    trmnPort.box.option('value', 6001);
    setValue(valdYn.box, "Y");
    let addNum = getNewNmbr();
    ctlrMngmNmbr.box.option( 'value', addNum );
    addFcltObject(addNum);
    if (nullChecker(addNum) !== "" && addNum.toString().length >= 4) {
        let id = addNum.toString();
        id = id.substring(id.length-3, id.length);
        setValue(vdsCtlrId.box, "VDS0" + id);
    }
    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);
    inputArr.map((item)=>{
        item.box.option("readOnly", true);
    });

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

function eventOn(){
    dsblOnBtn(_managerTable);

    inputArr.map((item)=>{
        item.box.option("readOnly", item.readOnly);
    })

}

function getNewNmbr() {
    let newId = [];
    getData(commonUri + "/new-id", newId);
    _selectFcltNmbr = newId[0].new_id;
    return _selectFcltNmbr;
}

/**
 * 지도 인터페이스 함수........
 */
 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));
    }
    console.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.vds_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*/);
}

