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

let _mapManager = null;
let _selectFcltNmbr = null;
const _lyrIdx = LayerIndex.CCam;
const _lyrType      = LayerType.LINK;
const _lyrLinkIdx   = LayerIndex.Link1;
const _crsLyrIdx = LayerIndex.Crs;
let ixrBtn;
let _modalText;
let _modalSaveBtn;
let _modalCancelBtn;
let _modalXBtn;

//우측 섹션 관련
let _managerData    = [];
let _managerTable   = null;
let _idArr          = [];
let cmraId          = null;
let cmraXCrdn       = null;
let cmraYCrdn       = null;
let cmraPort        = null;
let saveBtn         = null;
let cancleBtn       = null;
let addBtn          = null;
let delBtn          = null;
let editBtn         = null;
let istlLctn        = null;
let ixrId           = null;
let drctDvsnCd      = null;
let ixrNm           = null;
let cmraLognId      = null;
let cmraLognPw      = null;
let streUrl         = null;
let cmraIp          = null;
let srvcAnlyEn      = null;
let busDvrsLaneEn   = null;
let cmraAngl        = null;
let hmpgDsplEn      = null;
let laneCnt         = null;
let _crsData        = [];
const _ixrNameMap   = new Map();
const ipExpr        = /^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}$/;
const _updateColumns = {
    bus_dvrs_lane_en : 0,
    cmra_angl : 0,
    cmra_http_port : 0,
    cmra_id : null,
    cmra_ip : null,
    cmra_logn_id : null,
    cmra_logn_pw : null,
    cmra_port : null,
    cmra_type : 1,
    cmra_url : null,
    cmra_x_crdn : null,
    cmra_y_crdn : null,
    drct_dvsn_cd : 0,
    hmpg_dspl_en : 0,
    istl_lctn : null,
    ixr_id : null,
    srvc_anly_en : 0,
    stre_url : null,
    use_en : 0,
    lane_cnt : 0,
}

//공통
let commonUri = "/api/scrs/tb_sc_ixr_cmra_mngm";
const _pageName = '카메라 기본정보 관리';
const pageMsg   = "카메라";
let ixrInfoTable;
const inputArr = [
    (ixrId = {
        box      : null,
        option   : 130,
        disabled : true,
        label    : "교차로 ID",
        must     : true,
        value    : null,
        column   : "ixr_id",
        max      : 10,
    }),
    (cmraId = {
        box      : null,
        option   : 130,
        disabled : true,
        label    : "카메라 ID",
        column   : "cmra_id",
        id       : true,
        max      : 10,
        must     : true,
    }),
    (istlLctn = {
        box      : null,
        option   : 352,
        disabled : false,
        label    : "설치 위치",
        column   : "istl_lctn",
        id       : true,
        max      : 40,
        must     : true,
    }),
    (streUrl = {
        box      : null,
        option   : 352,
        label    : "스트리밍 주소",
        disabled : false,
        column   : "stre_url",
        max      : 32,
    }),
    (cmraIp = {
        box      : null,
        option   : 130,
        label    : "카메라 IP",
        must     : true,
        disabled : false,
        column   : "cmra_ip",
        expr     : ipExpr,
        max      : 16,
    }),
    (cmraPort = {
        box      : null,
        option   : 130,
        label    : "포트번호",
        disabled : false,
        must     : true,
        column   : "cmra_port",
        port     : true,
        max      : 200,
    }),
    (cmraLognId = {
        box      : null,
        option   : 130,
        label    : "로그인 ID",
        disabled : false,
        column   : "cmra_logn_id",
        max      : 200,
    }),
    (cmraLognPw = {
        box      : null,
        option   : 130,
        label    : "비밀번호",
        disabled : false,
        column   : "cmra_logn_pw",
        max      : 200,
    }),
    (cmraXCrdn = {
        box      : null,
        option   : 130,
        label    : "X좌표",
        disabled : false,
        must     : true,
        value    : "0.0000000",
        method: function (e) {
            crdnChanges(e, 3);
        },
        column: "cmra_x_crdn",
        max: 20,
    }),
    (cmraYCrdn = {
        box      : null,
        option   : 130,
        disabled : false,
        label    : "Y좌표",
        must     : true,
        value    : "0.0000000",
        method: function (e) {
            crdnChanges(e, 2);
        },
        column: "cmra_y_crdn",
        max: 20,
    }),
    (drctDvsnCd = {
        box      : null,
        select   : true,
        option   : 130,
        disabled : false,
        label    : "방향",
        must     : true,
        value    : null,
        column   : "drct_dvsn_cd",
        valueExpr : "cmmn_cd",
        display  : "cmmn_cd_kor_nm",
        max      : null,
        data     : [],
    }),
    (srvcAnlyEn = {
        box      : null,
        select   : true,
        option   : 65,
        disabled : false,
        label    : "서비스분석 유무",
        must     : true,
        value    : null,
        valueExpr : 'srvc_anly_en',
        column   : "srvc_anly_en",
        display  : "desc",
        max      : null,
        data     :[
            {srvc_anly_en: 0, desc : 'N'},
            {srvc_anly_en: 1, desc : 'Y'}
        ] 
    }),
    (cmraAngl = {
        box      : null,
        no       : true,
        option   : 130,
        disabled : false,
        label    : "카메라 앵글",
        column   : "cmra_angl",
        max      : 999,
        must     : false,
    }),
    (busDvrsLaneEn = {
        box      : null,
        select   : true,
        option   : 65,
        disabled : false,
        label    : "버스전용차로 유무",
        must     : true,
        value    : null,
        valueExpr : 'bus_dvrs_lane_en',
        column   : "bus_dvrs_lane_en",
        display  : "desc",
        max      : null,
        data     : [
            {bus_dvrs_lane_en: 0, desc : 'N'},
            {bus_dvrs_lane_en: 1, desc : 'Y'}
        ]
    }),
    (hmpgDsplEn = {
        box      : null,
        select   : true,
        option   : 100,
        disabled : false,
        label    : "홈페이지 표출 유무",
        must     : true,
        value    : null,
        valueExpr : 'cmmn_cd',
        column   : "hmpg_dspl_en",
        display  : "cmmn_cd_kor_nm",
        max      : null,
        data     : []
    }),
    (laneCnt = {
        box      : null,
        no       : true,
        option   : 130,
        disabled : false,
        label    : "차선수",
        column   : "lane_cnt",
        max      : 99,
        must     : false,
    }),
];

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: "취소",
    }),
    (addBtn = {
        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();
        },
    }),
    (delBtn = {
        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 () {
            delEvent();
        },
    }),
    (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: "저장",
    }),
];

const crosInfoModal = $(`
<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>교차로 정보</div>
                <div>
                    <div class="modal-cancle"></div>
                </div>
            </div>
            <div class="ixr-info">
                <div class="ixr-info-box b0 dx-theme-border-color">
                    <div class="serve-title dx-nav-item b2 dx-theme-border-color">교차로 목록</div>
                    <div>
                        <div class="ixr-info-table"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>`
)
const modalCancleBtn = $(crosInfoModal).children().eq(0).children().eq(0).children().eq(0).children().eq(1).children().eq(0);
const modalTableDiv = $(crosInfoModal).children().eq(0).children().eq(0).children().eq(1).children().eq(0).children().eq(1).children().eq(0);
$(() => {

    $("body").append(modalDiv);
    $(".modal-title").prepend($("<div>카메라 ID</div>"));
    $(".modal-background").css("display",'none');
    $(".modal-content").append($("<div class='modal-content-title'>")
        .html("카메라 ID를 입력하십시오."),$("<div class='modal-text'>"));
    
    _modalText      = new dxTxt($('.modal-text'), 'cmra_id', 10, '카메라 ID', 250, null, false, false, null);
    _modalSaveBtn   = new dxBtn($('.modal-save-Btn'),  '적용', 'check', 'outlined', null, null, false, true);
    _modalCancelBtn = new dxBtn($('.modal-cancle-Btn'),'취소', 'close', 'outlined', null, null, false, true);
    _modalXBtn      = new dxBtn($('.modal-cancle'), null, 'close', 'text', null, null, false, true);
    _modalText.onEnterKey(modalSaveEvent);
    _modalSaveBtn.onClick(modalSaveEvent);
    _modalCancelBtn.onClick(modalCloseEvent);
    _modalXBtn.onClick(modalCloseEvent);
    
    const closeBtn = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', null, null, false, true);
    closeBtn.onClick(()=>window.close());
    
    inputArr.map((item) => {
        if (item.select){
            item.box = new dxSelect($("." + item.column), 'outlined', item.option, 27, item.display, item.valueExpr, true, item.column, item.label);
            item.box.setDataSource(item.data);
            if (item.method){
                item.box.onValueChanged((e) => item.method(e))
            }
        }
        else if (item.no){
            item.box = new dxNumber($("." + item.column), 'outlined', item.option, 27, 1, item.max, false, null, item.column, "#", true);
        }
        else {
            item.box = new dxTxt($("." + item.column), item.column, item.max, item.label, item.option, 27, item.value, true, null);
            
            if (item.value) {
                item.box.setValue(item.value);
            }
            if (item.method) {
                item.box.onValueChanged(item.method);
            }
        }
    });
    cmraLognPw.box.text.option('mode', 'password');
    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");
    });

    $('body').append(crosInfoModal);
    crosInfoModal.css('display','none');

    //모달 창 닫기 
    $(modalCancleBtn).dxButton({
        icon : 'close',
        stylingMode: 'text',
        onClick(){
            crosInfoModal.css('display','none');
        }
    })
    ixrBtn = new dxBtn($('.ixr-btn'), '교차로 선택', null, 'outlined', null, 28, true, true);
    ixrBtn.onClick(()=>{
        crosInfoModal.css('display','flex')
        ixrInfoTable.refresh();
    });

    //제어기 선택 테이블
    ixrInfoTable = $(modalTableDiv).width("100%").height("100%").dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        showBorders             : true,
        allowColumnResizing     : true,
        rowAlternationEnabled   : true,
        focusedRowEnabled       : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        selection: {
            mode: 'single',
        },
        keyExpr : 'ixr_id',
        // headerFilter: {
        //     visible: true,
        // },
        scrolling: {
            mode: 'virtual',
        },
        columns:[
            {
                dataField: "ixr_id",
                caption: "교차로 ID",
                alignment: "center",
                sortOrder : 'asc',
                sortIndex : 1,
            },
            {
                dataField: "ixr_nm",
                caption: "교차로 명칭",
                alignment: "center",
                cellTemplate(c, e) {
                    return alignTemplate(c, e, 'left');
                },
            },
            {
                dataField: "phas_cnt",
                caption: "현시수",
                alignment: "center",
            },
            {
                dataField: "spot_fetr",
                caption: "지점 특성",
                alignment: "center",
            },
            {
                dataField: "ixr_x_crdn",
                caption: "X 좌표",
                alignment: "center",
            },
            {
                dataField: "ixr_y_crdn",
                caption: "Y 좌표",
                alignment: "center",
            },
            {
                dataField: "ixr_type",
                caption: "교차로 유형",
                alignment: "center",
            },
            {
                dataField: "dvsn",
                caption: "구분",
                alignment: "center",
                lookup : {
                    dataSource  : null,
                    valueExpr   : 'cmmn_cd',
                    displayExpr : 'cmmn_cd_kor_nm',
                }
            },
            {
                dataField: "use_en",
                caption: "사용 유무",
                alignment: "center",
                lookup : {
                    dataSource  : null,
                    valueExpr   : 'cmmn_cd',
                    displayExpr : 'cmmn_cd_kor_nm',
                }
            },
        ],
        onRowDblClick(e){
            const id = e.data.ixr_id;
            ixrId.box.setValue(id);
            //_mapManager.selectPos(e.data.x_crdn, e.data.y_crdn);
            e.component.clearSelection();
            e.component.option('focusedRowIndex', -1);
            $(".modal-background").css('display','none');
        }
    }).dxDataGrid("instance");

    // 시설물 정보를 읽어 온다.
    getData(commonUri + '/list', _managerData);
    
    getData('/api/scrs/tb_sc_ixr_mngm', _crsData);

    ixrInfoTable.option('dataSource', _crsData[0]);
    if ( _crsData[0] && _crsData[0].length > 0 ){
        _crsData[0].map((item)=>{
            _ixrNameMap.set(item.ixr_id, item);
        })
    }
    // 지도객체 생성
    doMap();
    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: ["ixr_id", "cmra_id", "drct_dvsn_cd"],

            headerFilter: {
                visible: true,
            },
            scrolling: {
                mode: "virtual",
            },
            columns: [
                {
                    dataField: "ixr_id",
                    caption: "교차로ID",
                    alignment: "center",
                    groupIndex : 0,
                    groupCellTemplate(c,e) {
                        if (e.data) {
                            const nameMap = _ixrNameMap.get(e.displayValue);
                            if (nullChecker(nameMap) !== "") {
                                const ixrNmVal = nameMap.ixr_nm;
                                if (nullChecker(ixrNmVal) !== "") {
                                    return c.text('교차로 : [' + e.displayValue + '] '+ixrNmVal);
                                }
                            }
                            else {
                                return c.text('교차로 : -')
                            }
                        }
                    }
                },
                {
                    dataField: "cmra_id",
                    caption: "카메라ID",
                    alignment: "center",
                },
                {
                    dataField: "istl_lctn",
                    caption: "설치위치",
                    alignment: "center",
                    cellTemplate(c, e) {
                        return alignTemplate(c, e, 'left');
                    },
                },
                {
                    dataField: "drct_dvsn_cd",
                    caption: "방향",
                    alignment: "center",
                    lookup : {
                        dataSource  : [],
                        valueExpr   : 'cmmn_cd',
                        displayExpr : 'cmmn_cd_kor_nm',
                    },
                },
                {
                    dataField: "cmra_x_crdn",
                    caption: "X좌표",
                    alignment: "center",
                },
                {
                    dataField: "cmra_y_crdn",
                    caption: "Y좌표",
                    alignment: "center",
                },
                {
                    dataField: "cmra_ip",
                    caption: "카메라IP",
                    alignment: "center",
                },
                {
                    dataField: "cmra_port",
                    caption: "포트번호",
                    alignment: "center",
                },
                {
                    dataField: "stre_url",
                    caption: "스트리밍 주소",
                    alignment: "center",
                },
                {
                    dataField: "bus_dvrs_lane_en",
                    caption: "버스전용차로 유무",
                    alignment: "center",
                    lookup : {
                        dataSource  : busDvrsLaneEn.data,
                        valueExpr   : 'bus_dvrs_lane_en',
                        displayExpr : 'desc',
                    },
                },
                {
                    dataField: "srvc_anly_en",
                    caption: "서비스 분석 유무",
                    alignment: "center",
                    lookup : {
                        dataSource  : srvcAnlyEn.data,
                        valueExpr   : 'srvc_anly_en',
                        displayExpr : 'desc',
                    },
                },
                {
                    dataField: "hmpg_dspl_en",
                    caption: "홈페이지 표출 유무",
                    alignment: "center",
                    lookup : {
                        dataSource  : [],
                        valueExpr   : 'cmmn_cd',
                        displayExpr : 'cmmn_cd_kor_nm',
                    },
                },
            ],
            onRowDblClick(e) {
                _selectFcltNmbr = e.data.cmra_id;
                selectFcltObject(_selectFcltNmbr);
                inputArr.map((item) => {
                    item.box.setValue(e.data[item.column]);
                });

                btnArr.map((item) => {
                    item.box.option("disabled", item.dbdsb);
                });
            },
        }).dxDataGrid("instance");
        fetchCdData();
});

function fetchCdData(){
    getDataAsync('/api/database/code/cmmn-cd/DRCT', recvCdData, [drctDvsnCd, 3]);
    getDataAsync('/api/database/code/cmmn-cd/WEBDSPL', recvCdData, [hmpgDsplEn, 11]);
    getDataAsync('/api/database/code/cmmn-cd/DVSN', recvIxrCdData, 7);
    getDataAsync('/api/database/code/cmmn-cd/USEEN', recvIxrCdData,8);
}
function recvIxrCdData(jsonData, idx){
    ixrInfoTable.option('columns['+ idx + '].lookup.dataSource', jsonData);
}
function recvCdData(jsonData, args){
    if (jsonData.length > 0) {
        jsonData.map((item)=>{
            if (item.cmmn_cd) item.cmmn_cd = Number(item.cmmn_cd);
        })
    }
    const box = args[0];
    const idx = args[1];
    box.data = jsonData;
    box.box.setDataSource(jsonData);
    _managerTable.option('columns['+ idx + '].lookup.dataSource', jsonData);
}
/**
 * 삭제 버튼 클릭
 */
function delEvent(){
    const selectedData = _managerTable.getSelectedRowsData()[0];
    const idxIdVal = selectedData.cmra_id;
    confirmMessage(pageMsg
        + " ID : "
        + idxIdVal
        + "<br>선택하신 " + pageMsg + " 정보를 삭제하시겠습니까?").done((yes)=>{
        if (yes === true) {
            const result = deleteDataIds(commonUri, [{ixrid:idxIdVal, cmraid : selectedData.cmra_id, drctdvsncd : selectedData.drct_dvsn_cd}]);
            console.log(result);
            if (result > 0) {
                delResultMsg(pageMsg);
                boxInit();
                buttonReset("add", "unSelected");
                _managerTable.option("focusedRowKey", null);
                _managerData = refresh(_managerTable, _managerData, commonUri + '/list');
                deleteFcltObject(selectedData.cmra_id);
            }
        }
    });
}

/**
 * 모달 가리기
 */
function modalCloseEvent(){
    modalDiv.css('display', 'none');
    _modalText.setValue(null);
}

/**
 * 편집 모드
 */
function editEvent() {
    console.log(_selectFcltNmbr);
    editFcltObject(_selectFcltNmbr, true);
    cancleBtn.box.off("click");
    cancleBtn.box.on("click", () => editCancel());

    eventOn();

    btnArr.map((item) => {
        item.box.option("visible", item.edit.click.visible);
        item.box.option("disabled", item.edit.click.disabled);
    });
    ixrId.box.setReadOnly(true);
    saveBtn.box.off('click');
    saveBtn.box.on('click', () => saveEvent('edit'));
}

/**
 * 편집 모드 취소
 */
function editCancel() {
    updateIcon();
    eventCancel();
    boxPull();
    buttonReset("edit", "cancle");
}

/**
 * 카메라 ID 전체 가져오기
 * @returns 카메라 ID 배열
 */
function getIdArr(){
    let idArr = [];
    if (_managerData[0].length > 0) {
        _managerData[0].map((obj)=>{
            if(obj.cmra_id)idArr.push(obj.cmra_id);
        })
    }
    return idArr;
}

/**
 * 저장 버튼 클릭 이벤트
 * @param {*} type 수정 모드인지 구분
 * @returns 저장 데이터가 유효하지 않다면 종료
 */
function saveEvent(type) {
    _idArr = getIdArr();
    for (let input of inputArr) {
        const box   = input.box;
        const value = box.getValue();
        const max   = input.max;
        const label = input.label;
        const empty = nullChecker(value) === "";
        if (empty) {
            if (input.must) {
                return  alertWarning( "필수 항목을 입력해주세요. [ " + label +" ]", null, box);
            }
        }
        else {
            if (max && getByteLength(value) > max) {
                return alertWarning( max + " 바이트 이내로 입력해주세요. [ " + label +" ]", null, box);
            }
            if (input.expr && !input.expr.test(value)) {
                return alertWarning("IP 형식에 맞게 입력해주세요. [ " + label +" ]", null, box);
            }
            if (input.port && isNaN(value)) {
                return alertWarning("PORT 형식에 맞게 입력해주세요. [ " + label + " ]", null, box);
            }
            if (input.id && _idArr.includes(value) && type === "add") {
                    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 = cmraId.box.getValue();
        if (_idArr.includes(idVal) && idVal !== rowData.cmra_id){
            return alertWarning( "제어기 ID : " + idVal + "<br>이미 사용중인 제어기 ID 입니다.", null, cmraId.box);
        }
    }

    inputArr.map((item) => {
        if (item.column) {
            updateData[item.column] = item.box.getValue();
        }
    });

    console.log(updateData);
    let result = postInsertUpdate(commonUri, [updateData]);
    const keys = {
        ixr_id :  updateData.ixr_id,
        cmra_id :  updateData.cmra_id,
        drct_dvsn_cd :  updateData.drct_dvsn_cd,
    }
    if (result > 0) {
        insResultMsg(pageMsg);
        _managerData = refresh(_managerTable, _managerData, commonUri);
        _managerTable.clearSelection();
        _managerTable.refresh().done(function () {
            _managerTable.selectRows(keys).done(()=>{
                _managerTable.option("focusedRowKey", keys);
                boxPull();
                buttonReset("add", "selected");
                //newNums();
                updateIcon();
                eventCancel();
            });
        });
    }
}

/**
 * 추가 모드 취소
 */
function addCancel() {
    updateIcon();
    eventCancel();

    if (_managerTable.getSelectedRowsData().length > 0) {
        boxPull();
        buttonReset("add", "selected");
    }
    else {
        boxInit();
        buttonReset("add", "unSelected");
    }
}

/**
 * 추가 모드
 */
function addEvent() {
    modalDiv.css('display', 'flex');
    _modalText.focus();
}

/**
 * 모달 카메라 ID 값 넣기
 * @returns cmra_id 값이 유효하지 않다면 alert 메시지
 */
function modalSaveEvent(){
    const idArr = getIdArr();
    const cmraIdVal = _modalText.getValue();
    if (_modalText.isNull()) {
        return alertWarning("카메라 ID를 입력해주세요.", null, _modalText);
    }
    else if (idArr.includes(cmraIdVal)) {
        return alertWarning("카메라 ID : " + cmraIdVal + "<br>이미 사용중인 카메라 ID입니다.", null, _modalText);
    }
    else if (_modalText.getByte() > _modalText.max){
        return alertWarning("카메라 ID를 "+ _modalText.max +"바이트 이내로 입력해주세요.", null, _modalText);
    }
    else  {
        modalCloseEvent();
        eventOn();
        boxInit();
        cmraId.box.setValue(cmraIdVal);
        let center = _mapManager.getCenter();
        cancleBtn.box.off("click");
        cancleBtn.box.on("click", () => addCancel());
        cmraXCrdn.box.setValue(center[0].toFixed(8));
        cmraYCrdn.box.setValue(center[1].toFixed(8));
        
        inputArr.map((item) => {
            if (item.select) {
                if (item.box.getDataSource().length > 0) {
                    item.box.setValue(item.box.getDataSource()[0][item.valueExpr]);
                }
            }
        });
        addFcltObject(cmraIdVal);
        _selectFcltNmbr = cmraIdVal;
        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('add'));
    }
}

/**
 * 테이블 리스트에서 데이터 input 박스로 가져오기
 */
function boxPull() {
    let selectedRow = _managerTable.getSelectedRowsData()[0];
    inputArr.map((item) => {
        item.box.setValue(selectedRow[item.column]);
    });
}

/**
 * input 데이터 초기화
 */
function boxInit() {
    inputArr.map((item) => {
        if (item.value) return item.box.setValue(item.value);
        item.box.setValue(null);
    });
}

/**
 * CRUD 버튼 보이기/감추기, 활성화/비활성화
 * @param {*} eventName add/edit(추가/편집)
 * @param {*} option add - selected/unSelected(테이블 리스트 기존 선택, 미선택), edit - cancle (편집 모드 종료)
 */
function buttonReset(eventName, option) {
    btnArr.map((item) => {
        item.box.option("visible", item[eventName][option].visible);
        item.box.option("disabled", item[eventName][option].disabled);
    });
}

/**
 * CRUD 작업 모드 종료
 */
function eventCancel() {
    dsblOffBtn(_managerTable);
    ixrBtn.setDisabled(true);
    _selectFcltNmbr = null;
    inputArr.map((item) => {
        item.box.setReadOnly(true);
    });

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

/**
 * CRUD 작업 모드 실행
 */
function eventOn() {
    dsblOnBtn(_managerTable);
    ixrBtn.setDisabled(false);
    inputArr.map((item) => {
        item.box.setReadOnly(item.disabled);
    });
}

/**
 * 제어기 신규 ID 조회
 */
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) {
        cmraXCrdn.box.setValue(ACoordX.toFixed(8));
        cmraYCrdn.box.setValue(ACoordY.toFixed(8));
    }
    //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;
    }
}

/**
 * 지도에 시설물 객체 정보를 그린다.
 */
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.cmra_id, obj.istl_lctn, obj.cmra_x_crdn, obj.cmra_y_crdn);
            objs.push(item);
        });
        _mapManager.initFcltObject(_lyrIdx, objs);
    }
}

function selectFcltObject(ANmbr) {
    _mapManager.selectLayerObject(_lyrIdx, ANmbr);
}
function editFcltObject(ANmbr, AIsEdit) {
    console.log(ANmbr)
    _mapManager.editFcltObject(_lyrIdx, ANmbr, AIsEdit, AIsEdit ? "1" : "0");
    console.log(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*/);
}
