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.Cctv;

//우측 섹션 관련
let _managerData    = [];
let _managerTable   = null;
let _idArr          = [];
let cctvNo          = null;
let cctvNm          = null;
let cctvId          = null;
let cctvX           = null;
let cctvY           = null;
let ctrlIp          = null;
let ctlrPort        = null;
let lctnNm          = null;
let strmSesnNm      = null;
let camNo           = null;
let outRstp         = null;
let intrHttp        = null;
let webRtcId        = null;
let outHttp         = null;
let webRtcIp        = null;
let webRtcPort      = null;
let saveBtn         = null;
let cancleBtn       = null;
let addBtn          = null;
let delBtn          = null;
let editBtn         = null;
let addNum          = 0;
const ipExpr = /^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}$/;
const _updateColumns = {
    altt_imag_dspl_yn: "N",
    altt_imag_nmbr: 0,
    cctv_area_dvsn: "1",
    cctv_capt_ip : null,
    cctv_capt_port: null,
    cctv_ctlr_id: null,
    cctv_ctlr_ip: null,
    cctv_ctlr_local_no: 0,
    cctv_ctlr_nmbr: 0,
    cctv_ctlr_port: 0,
    cctv_id: null,
    cctv_nm: null,
    cctv_type_cd : null,
    fan_off_tmpr : 25,
    fan_on_tmpr : 30,
    hetr_off_tmpr : 25,
    hetr_on_tmpr : 5,
    del_yn : "N",
    intr_http_addr: null,
    istl_lctn_addr: null,
    istl_lctn_nm: null,
    link_id: 0,
    node_id: 0,
    strm_rtsp_addr:  null,
    strm_http_addr:  null,
    strm_sesn_nm: null,
    strm_svr_ip : null,
    strm_svr_port : 0,
    syop_cntl_yn:  "N",
    use_yn : "N",
    rtc_id : null,
    rtc_svr_ip : null,
    rtc_svr_port: 0,
    x_crdn: 0,
    y_crdn: 0,
};

//공통
let commonUri = "/api/cctv/manager/info";
const _pageName = 'CCTV 기본정보 관리';
const pageMsg = "CCTV";
const inputArr = [
    (cctvNo = {
        box      : null,
        option   : 80,
        disabled : true,
        label    : "CCTV 관리번호",
        column   : "cctv_ctlr_nmbr",
        max      : 10,
        must     : true,
    }),
    (cctvId = {
        box      : null,
        option   : 120,
        disabled : false,
        label    : "제어기 ID",
        column   : "cctv_ctlr_id",
        id       : true,
        max      : 10,
        must     : true,
    }),
    (camNo = {
        box      : null,
        option   : 60,
        disabled : false,
        label    : "카메라 번호",
        column   : "cctv_ctlr_local_no",
        number   : true,
        max      : 5,
        must     : true,
    }),
    (cctvNm = {
        box      : null,
        option   : 240,
        disabled : false,
        label    : "CCTV 명칭",
        column   : "cctv_nm",
        max      : 40,
        must     : true,
    }),
    (lctnNm = {
        box      : null,
        option   : 240,
        label    : "위치명",
        must     : true,
        disabled : false,
        column   : "istl_lctn_nm",
        max      : 40,
    }),
    (ctrlIp = {
        box      : null,
        option   : 140,
        label    : "제어기 IP",
        disabled : false,
        must     : true,
        expr     : ipExpr,
        column   : "cctv_ctlr_ip",
        max      : 20,
    }),
    (ctlrPort = {
        box      : null,
        option   : 80,
        label    : "제어기 PORT",
        disabled : false,
        must     : true,
        number   : true,
        column   : "cctv_ctlr_port",
        max      : 5,
    }),
    (cctvX = {
        box      : null,
        option   : 100,
        label    : "X좌표",
        disabled : false,
        must     : true,
        value    : "0.0000000",
        method: function (e) {
            crdnChanges(e, 3);
        },
        column: "x_crdn",
        max: 11,
    }),
    (cctvY = {
        box      : null,
        option   : 100,
        disabled : false,
        label    : "Y좌표",
        must     : true,
        value    : "0.0000000",
        method: function (e) {
            crdnChanges(e, 2);
        },
        column: "y_crdn",
        max: 10,
    }),
    (strmSesnNm = {
        box      : null,
        option   : 240,
        label    : "스트리밍 세션명",
        disabled : false,
        column   : "strm_sesn_nm",
        max      : 200,
    }),
    (outRstp = {
        class    : "out-rstp",
        box      : null,
        option   : 240,
        label    : "스트리밍 RSTP 주소",
        disabled : false,
        column   : "strm_rtsp_addr",
        max      : 200,
    }),
    (intrHttp = {
        box      : null,
        option   : 240,
        label    : "인터넷 HLS 주소",
        disabled : false,
        column   : "intr_http_addr",
        max      : 200,
    }),
    (outHttp = {
        box      : null,
        option   : 240,
        label    : "스트리밍 HTTP 주소",
        disabled : false,
        column   : "strm_http_addr",
        max      : 200,
    }),
    (webRtcId = {
        box      : null,
        option   : 240,
        label    : "WEB RTC ID",
        disabled : false,
        column   : "rtc_id",
        max      : 56,
    }),
    (webRtcIp = {
        box      : null,
        option   : 140,
        label    : "WEB RTC IP",
        disabled : false,
        column   : "rtc_svr_ip",
        expr     : ipExpr,
        max      : 20,
    }),
    (webRtcPort = {
        box      : null,
        option   : 80,
        label    : "WEB RTC PORT",
        number   : true,
        disabled : false,
        column   : "rtc_svr_port",
        max      : 5,
    }),

];

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 () {
            const cctvCtlrNmbr = _managerTable.getSelectedRowsData()[0].cctv_ctlr_nmbr;
            confirmMessage(pageMsg
                + "번호 : "
                + cctvCtlrNmbr
                + "<br>선택하신 " + pageMsg + " 정보를 삭제하시겠습니까?").done((yes)=>{
                if (yes === true) {
                    const result = deleteData(commonUri, cctvCtlrNmbr);
                    if (result > 0) {
                        delResultMsg(pageMsg);
                        boxInit();
                        buttonReset("add", "unSelected");
                        _managerTable.option("focusedRowKey", null);
                        _managerData = [];
                        getData(commonUri, _managerData);
                        dataSorting(_managerData[0], 'cctv_ctlr_id'); 
                        _managerTable.option('dataSource', _managerData[0]);
                        deleteFcltObject(cctvCtlrNmbr);
                    }
                }
            });
        },
    }),
    (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 typeCd = null;
let useYn  = null;
$(() => {
    typeCd = new dxSelect($('.cctv_type_cd'), 'outlined', 140, 27, 'cctv_type_cd_desc', 'cctv_type_cd', true, 'cctv_type_cd', 'CCTV 유형코드');

    useYn  = new dxCheck($('.use_yn'), null, false, true, null, 'use_yn');
    console.log(window.opener.$mapManager);
    //상단 닫기 버튼
    $(".cancle-button")
        .dxButton({
            text: "닫기",
            icon: "close",
            height: "30px",
            width: "80px",
            stylingMode: "outlined",
            onClick() {
                window.close();
            },
        })
        .dxButton("instance");

    inputArr.map((item) => {
        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);
    if (_managerData[0].length > 0) {
        dataSorting(_managerData[0], 'cctv_ctlr_id');
    }
    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: "cctv_ctlr_nmbr",

            headerFilter: {
                visible: true,
            },
            scrolling: {
                mode: "virtual",
            },
            columns: [
                {
                    dataField: "cctv_ctlr_id",
                    caption: "CCTV ID",
                    width: 120,
                    alignment: "center",
                },
                {
                    dataField: "istl_lctn_nm",
                    caption: "설치 위치",
                    alignment: "center",
                    cellTemplate(c, e) {
                        c.css("text-align", "left");
                        return c.text(e.displayValue);
                    },
                },
            ],
            onRowDblClick(e) {
                _selectFcltNmbr = e.data.cctv_ctlr_nmbr;
                selectFcltObject(_selectFcltNmbr);
                inputArr.map((item) => {
                    item.box.option("value", e.data[item.column]);
                });
                typeCd.setValue(e.data[typeCd.column]);
                useYn.setValue(e.data.use_yn === 'Y');
                btnArr.map((item) => {
                    item.box.option("disabled", item.dbdsb);
                });
            },
        })
        .dxDataGrid("instance");
        fetchTypeData();
});
function fetchTypeData(){
    getDataAsync('/api/database/code/cmmn-cd/CCTVT',(jsonData)=>{
        let typeCdData = [];
        jsonData.map((item)=>{
            typeCdData.push({
                cctv_type_cd : item.cmmn_cd,
                cctv_type_cd_desc : '[ ' + item.cmmn_cd +' ] ' + item.cmmn_cd_kor_nm,
            });
        })
        typeCd.setDataSource(typeCdData);
        typeCd.setValue(jsonData[0].cmmn_cd);
    });
}

function editEvent() {
    editFcltObject(_selectFcltNmbr, true);
    cancleBtn.box.off("click");
    cancleBtn.box.on("click", () => editCancel());
    eventOn();
    
    cctvId.box.option('readOnly', true);
    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 editCancel() {
    updateIcon();
    eventCancel();
    boxPull();
    buttonReset("edit", "cancle");
}
function getIdArr(){
    let idArr = [];
    if (_managerData[0].length > 0) {
        _managerData[0].map((obj)=>{
            if(obj.cctv_ctlr_id)idArr.push(obj.cctv_ctlr_id);
        })
    }
    return idArr;
}
function saveEvent(type) {
    _idArr = getIdArr();
    for (let input of inputArr) {
        const box   = input.box;
        const value = getValue(box);
        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.number && isNaN(value)) {
                return alertWarning("해당 항목은 숫자만 입력이 가능합니다. [ " + 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];
        }
        console.log('edit mode...')
    }

    // 수정모드인 경우와 추가 모드 비교해야함...
    inputArr.map((item) => {
        if (item.column) {
            updateData[item.column] = item.box.option("value");
        }
    });

    updateData.cctv_type_cd = typeCd.getValue();
    updateData.use_yn = useYn.getValue() ? "Y" : "N";

    console.log(updateData);
    //ctrlIpNum
    let result = postInsertUpdate(commonUri + "/" + updateData.cctv_ctlr_nmbr, updateData);
    if (result > 0) {
        insResultMsg(pageMsg);
        _managerData = [];
        getData(commonUri, _managerData);
        dataSorting(_managerData[0], 'cctv_ctlr_id'); 
        _managerTable.option('dataSource', _managerData[0]);
        _managerTable.clearSelection();
        _managerTable.refresh().done(function () {
            _managerTable.selectRows(updateData.cctv_ctlr_nmbr, true).done(()=>{
                _managerTable.option("focusedRowKey", updateData.cctv_ctlr_nmbr);
                boxPull();
                buttonReset("add", "selected");
                updateIcon();
                eventCancel();
            });
        });
    }
}

function addCancel() {
    updateIcon();
    eventCancel();

    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", () => addCancel());
    cctvX.box.option("value", center[0].toFixed(7));
    cctvY.box.option("value", center[1].toFixed(7));
    addNum = getNewNmbr();
    const lastData = _managerData[0][_managerData[0].length - 1]
    setValue(camNo.box, lastData.cctv_ctlr_local_no + 1);
    let idVal = lastData.cctv_ctlr_id;
    if (idVal.length){
        let idNo = idVal.substring(idVal.indexOf('V') + 1, idVal.length);
        if (!isNaN(idNo)) {
            let cctvIdVal = 'CCTV' + (Number(idNo) + 10);
            setValue(cctvId.box, cctvIdVal);
        }
    }
    addFcltObject(addNum);
    cctvNo.box.option("value", 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('add'));
}

function boxPull() {
    let selectedRow = _managerTable.getSelectedRowsData()[0];
    inputArr.map((item) => {
        item.box.option("value", selectedRow[item.column]);
    });
    typeCd.setValue(selectedRow[typeCd.valueExpr]);
    useYn.setValue(selectedRow.use_yn === "Y");
}

function boxInit() {
    inputArr.map((item) => {
        if (item.value) return item.box.option("value", item.value);
        item.box.option("value", null);
    });
    useYn.setValue(false);
    typeCd.setValue(typeCd.getDataSource()[0][typeCd.valueExpr])
}

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

function eventCancel() {
    dsblOffBtn(_managerTable);

    inputArr.map((item) => {
        item.box.option("readOnly", true);
    });
    typeCd.setReadOnly(true);
    useYn.setReadOnly(true);
    if(_managerTable.getSelectedRowsData().length > 0){
        _selectFcltNmbr = _managerTable.getSelectedRowsData()[0].cctv_ctlr_nmbr;
        selectFcltObject(_selectFcltNmbr);
    }
}

function eventOn() {
    dsblOnBtn(_managerTable);
    typeCd.setReadOnly(false);
    useYn.setReadOnly(false);
    inputArr.map((item) => {
        item.box.option("readOnly", 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) {
        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]);
            });
            typeCd.setValue(selectedData[typeCd.column]);
            useYn.setValue(selectedData.use_yn === 'Y');
            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.cctv_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*/);
}
