<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ page session="false" %>
<!doctype html>
<html lang="ko" style="min-width:300px !important;overflow:hidden">
<head>
    <%@ include file="/WEB-INF/jsp/common.jsp" %>
    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <link rel="stylesheet" type="text/css" href="${contextRoot }/css/common.css"/>
    <link rel="stylesheet" type="text/css" href="${contextRoot }/css/main.css"/>
    <link rel="stylesheet" href="${contextRoot }/css/themes/default/style.css"/>
</head>
<body class="sang" style="min-width:305px !important;overflow:hidden">
<div class="leftMenu">
    <ul class="tabs">
        <li><a href="javascript:goIntMenu()" class="tab" id="tab1"><img src="images/tab01_on.png" alt="교차로메뉴"/></a></li>
        <!-- <li><a href="javascript:goGroupMenu()" class="tab" id="tab2"><img src="images/tab02_off.png" alt="신호그룹메뉴" /></a></li> -->
    </ul>
    <div id="onOffTree"></div>
    <div id="intTree"></div>
    <div id="groupTree"></div>
    <div class="treeLoading"><img src="/css/themes/classic/throbber.gif"/></div>
</div>
<script type="text/javascript" src="${contextRoot }/js/common/moment.js"></script>
<script src="${contextRoot }/js/common/common-all.js" type="text/javascript"></script>
<script src="${contextRoot }/js/signalInfo.js" type="text/javascript"></script>
<script src="${contextRoot }/js/common/jstree.min.js" type="text/javascript"></script>

<script type="text/javascript">

    var treeJson = null;
    var groupTreeJson = null;
    var treeCtrl;
    var onlineCenterStatusCheckId;
    var offlineCenterStatusCheckId;
    var onlineIntStatusCheckId;
    var offlineIntStatusCheckId;
    var _RegionCdArr = [];
    var _GroupNoArr = [];
    var intGroupLineArr = [];
    var intGroupCircleArr = [];
    var _groupTreeListCallBackData;

    var onlineCenterStatusData;
    var offlineCenterStatusData;
    var onlineIntStatusData;
    var offlineIntStatusData;
    let _regionMap = new Map();

    function setAddrMap(data) {
        _regionMap.clear();
        for (let ii = 0; ii < data.length; ii++) {
            if (data[ii].addr1 == null || data[ii].addr1 == '-') {
                continue;
            }
            _regionMap.set(data[ii].addr1, data[ii].regionid);
        }
    }

    function getAddrSi() {
        return Array.from(_regionMap.keys());
    }
    function getEngAddr(addr){
        let region_id = _regionMap.get(addr);
        if (region_id === null || region_id === undefined) {
            return "U99"
        }
        return region_id;
    }

    setTreeList();
    getIntTreeList();

    var timeout = setInterval(controllerOnOffFuc, 1000);

    /*
    * 신호 제어기 상태 정보
    * 1 : 정상, 2: 교차로 시각 오류 0: 마지막통신 시간 3초이상 지연시
     */
    function controllerOnOffFuc() {

        var addrArr = getAddrSi();

        for(var ll = 0; ll < addrArr.length; ll++) {

            var ctnlCount =0;
            var errorCount=0;
            var now = new Date();
            var preDate = moment(now.getTime()).add("-30", "s").format("YYYY-MM-DD HH:mm:ss");
            var nxtDate = moment(now.getTime()).add("30", "s").format("YYYY-MM-DD HH:mm:ss");

            window.parent._signalInfoArr.forEach(function (el) {
                if (el.addr1 == addrArr[ll]) {
                    ctnlCount++;
                    if (el.commDate == null) {
                        el.status = 0;  // 데이터 없음(현재 통신하고 있지 않음)
                        errorCount++;
                    }
                    else {
                        if ((now.getSeconds() - el.commDate.getSeconds()) <= 3) {
                            // 마지막 통신시각이 현재시각보다 3초 이내이면 통신 정상
                            el.status = 1;
                            // 로컬시각이 현재시각과 차이날 경우 아이콘의 색을 노랑색으로 변경하도록 한다.
                            var localDate = moment(el.date).format('YYYY-MM-DD HH:mm:ss');
                            if (localDate < preDate || localDate > nxtDate) { //시간이 null거나 3초전이거나
                                el.status = 2; // 교차로 시각 오류 (노랑색 아이콘으로 표출)
                            }
                        }
                        else {
                            // 마지막 통신시각이 현재시각보다 3초 이후이면 통신 Off Line 으로 판단
                            el.status = 0;
                            errorCount++;
                        } //
                    }

                    var commOnOffImg = 'background-image:url("images/intStatus_' + el.status + '.png");background-position:center center';
                    /*if (el.status == 1) {
                        commOnOffImg = 'background-image:url("images/intStatusOn.png");background-position:center center';
                    } else if(el.status == 2) {
                        //errorCount++;
                        commOnOffImg = 'background-image:url("images/intStatusOff.png");background-position:center center';
                    }else{
                        //errorCount++;
                        commOnOffImg = 'background-image:url("images/intStatusNull.png");background-position:center center';
                    }*/
                    $('#' + el.nodeId + ' .jstree-anchor .jstree-icon').attr('style', commOnOffImg);
                }
            });
            $('#intErrCnt_'+getEngAddr(addrArr[ll])).text(errorCount);
            $('#intTotal_'+getEngAddr(addrArr[ll])).text(ctnlCount);
        }
    }

    function setTreeList() {
        /**
         ** ****************************************************
         ** 레이어 리스트 Tree 생성
         ** ****************************************************
         */
        treeCtrl = treeCtrl || (function () {

            var Node = function (nodeName, data, id, icon) {
                return {
                    id: id,
                    icon: icon,
                    text: nodeName,
                    state: {'opened': false, 'selected': false},
                    data: data,         // @type: ol.Layer
                    children: []
                };
            };

            var _root = new Node('ROOT', 'item');

            var findChild = function (parent, nodeName) {
                for (var i = 0; i < parent.children.length; i++) {
                    var child = parent.children[i];
                    if (child.text == nodeName) {
                        return child;
                    }
                }

                return null;
            };

            // find parent which save item
            var getParent = function (parent, group, data, id, icon, opt_make) {
                opt_make = (typeof opt_make === 'undefined') ? true : false;

                for (var i = 0; i < group.length; i++) {
                    var child = findChild(parent, group[i]);
                    // 없으면 Node 생성
                    if (!child) {
                        if (!opt_make) return null;
                        child = new Node(group[i], data);
                        parent.children.push(child);
                    }
                    parent = child;
                }

                return parent;
            }

            // group에 layer 아이템 저장
            var _set = function (key, item) {
                key.forEach(function (el) {
                    var group = el.split('-');
                    var parent = getParent(_root, group, item.data, item.id, item.icon);
                    var child = new Node(item.name, item.data, item.id, item.icon);
                    parent.children.push(child);
                    return child;
                });
            };

            // item인 node들만 반환 (=layer)
            var _get = function (key) {
                var group = key.split('-');
                var parent = getParent(_root, group);
                return parent.children.filter(function (node) {
                    return node.type == 'item'
                });
            };

            var _clear = function () {
                _root.children = [];
            };

            var _setState = function (key, state) {
                var group = key.split('-');
                var node = getParent(_root, group, false);
                if (!node) return false;

                node['state'] = state;
                return true;
            };

            var _toTreeJson = function () {
                return _root.children;
            };

            return {
                'root': _root,
                'set': _set,
                'get': _get,
                'setState': _setState,
                'toTreeJson': _toTreeJson,
                'clear': _clear,
            };

        })(treeCtrl);
    }

    function getIntTreeList() {
        $('.treeLoading').show();
        var url = 'getIntTreeList.do';
        requestService(url, '', getIntTreeListCallback);
    }
    function nameSort(a, b) {
        var x = a.name.toLowerCase();
		var y = b.name.toLowerCase();
		return x < y ? -1 : x > y ? 1 : 0;
    }


    function getIntTreeListCallback(data) {
        //console.log(data);
        treeCtrl.clear();

        var nodeId;
        var name;
        var lat;
        var lng;
        var addr1;
        var addr2;
        var addr3;
        var ipAddr;

        var nameCntOn;
        data.sort(nameSort);

        //TODO: 20230221
        setAddrMap(data);

        for (var i = 0; i < data.length; i++) {
            if (data[i].addr1 == null || data[i].addr1 == '-') {
                continue;
            }

            nodeId = data[i].nodeid;
            name = data[i].name;
            lat = data[i].lat;
            lng = data[i].lng;
            addr1 = data[i].addr1;
            addr2 = data[i].addr2;
            addr3 = data[i].addr3;
            ipAddr = data[i].ipaddr;

            //console.log('nodeid :'+nodeId+' , name : '+name+', lat : '+lat+', lng : '+lng+', addr1 : '+addr1);
            var signal = new SignalInfo(nodeId, name, lat, lng, addr1, addr2, addr3);
            //부모 변수에 저장
            //iframe이라서 직접 접근이 안됨
            window.parent._signalInfoArr.push(signal);

            var engAddr = getEngAddr(addr1);

            nameCntOn = '&nbsp;<strong class="centerNm_' + engAddr + '">' + addr1 + '</strong>&nbsp;( 전체 : <span class="intTotal" id="intTotal_'+engAddr+'" style="color:#0000FF"></span> / 이상 : '+
					  '<span class="intErrCnt" id="intErrCnt_'+engAddr+'" style="color:#FF0000"></span> )';

            //guTitleOff = nameCntOn + '-' + addr2 + '&nbsp;';

            var intNm = nodeId + '_' + name;
            var intStatus = getStatus(signal.status);

            function getStatus(stts){
                if(stts == 1){
                    return "On"; //정상
                }else if( stts == 2){
                    return "Off"; //교차로시각이상
                }else{
                    return "Null"; // 통신시간 3초이상
                }

            }

            treeCtrl.set([nameCntOn], {
                name: name+" ("+nodeId+")",
                id: nodeId,
                icon: "images/comm" + intStatus + ".png",
                data: {
                    'line': 'offline',
                    'intNo': nodeId, 'intNm': name,
                    'lat': lat, 'lng': lng,
                }
            });

        }


        treeJson = treeCtrl.toTreeJson();


        $('#intTree').jstree({
            'core': {
                'data': treeJson,
                "themes": {"stripes": true},
            },
            "plugins": ["wholerow"]
        });


        // jsTree 클릭 이벤트 : 레이어 setVisible
        $('#intTree').bind('select_node.jstree', function (event, data) {

            var parentNd = data.node.parent;
            var children = data.node.children;

            //parent._RegionCd = data.node.data.regionCd;

            if (parentNd == '#') //시도 선택
            {
                //console.log("시도 선택했음");
            } else if (parentNd != '#' && children.length > 0) //구 선택
            {
                //console.log("구 선택했음");
            } else {
                var intNm = data.node.data.intNm;
                var lng = data.node.data.lng;
                var lat = data.node.data.lat;

                if(parent._Level > 3) parent.map.setLevel(1);
                parent.map.panTo(new parent.kakao.maps.LatLng(lat, lng));
                setTimeout(
                    function() {
                        parent.getSignalInfo();
                        parent.customOverlayFnc(intNm,lng,lat);
                    }, 100 * 2);
            }

        });

        $('.treeLoading').hide();
    }

    //유선 센터상테 체크..
    function onlineCenterStatusCheck() {

        if (onlineCenterStatusCheckId != null) clearTimeout(onlineCenterStatusCheckId);
        onlineCenterStatusCheckId = setTimeout('onlineCenterStatusCheck()', 5 * 1000);

        var url = 'getOnlineCenterStatus.do';
        requestService(url, '', onlineCenterStatusCheckCallback);
    }

    function onlineCenterStatusCheckCallback(data) {
        onlineCenterStatusData = data;
        drawCenterStatus(0, data);
    }

    //무선 센터상테 체크..
    function offlineCenterStatusCheck() {

        if (offlineCenterStatusCheckId != null) clearTimeout(offlineCenterStatusCheckId);
        offlineCenterStatusCheckId = setTimeout('offlineCenterStatusCheck()', 5 * 1000);

        var url = 'getOfflineCenterStatus.do';
        requestService(url, '', offlineCenterStatusCheckCallback);
    }

    function offlineCenterStatusCheckCallback(data) {
        offlineCenterStatusData = data;
        drawCenterStatus(1, data);
    }

    function drawCenterStatus(network, data) {
        var regionCd;
        var totCnt;
        var errCnt;
        var commState;
        var commImg = '';

        for (var ii = 0; ii < data.length; ii++) {
            regionCd = data[ii].REGION_CD;
            totCnt = data[ii].TOT;
            errCnt = data[ii].ERR_CNT;
            commState = data[ii].COMM_STATE;

            if (commState == 1) {
                commImg = 'images/commOff.png';
                $('.intErrCnt_' + network + '_' + regionCd).text(totCnt);
            } else {
                commImg = 'images/commOn.png';
                $('.intErrCnt_' + network + '_' + regionCd).text(errCnt);
            }
            if (network == 0) $('.regionComm_' + network + '_' + regionCd).attr('src', commImg);

            $('.intTotal_' + network + '_' + regionCd).text(totCnt);
        }
    }

    //유선 제어기 상태 체크..
    function onlineIntStatusCheck() {
        if (_RegionCdArr.length > 0) {
            if (onlineIntStatusCheckId != null) clearTimeout(onlineIntStatusCheckId);
            onlineIntStatusCheckId = setTimeout('onlineIntStatusCheck()', 5 * 1000);

            var url = 'getOnlineIntStatus.do';
            var param = 'regionCd=' + _RegionCdArr;
            requestService(url, param, onlineIntStatusCheckCallback);
        }
    }

    function onlineIntStatusCheckCallback(data) {
        onlineIntStatusData = data;
        drawIntStatus(0, data);
    }

    //무선 제어기 상태 체크..
    function offlineIntStatusCheck() {
        if (_RegionCdArr.length > 0) {
            if (offlineIntStatusCheckId != null) clearTimeout(offlineIntStatusCheckId);
            offlineIntStatusCheckId = setTimeout('offlineIntStatusCheck()', 5 * 1000);

            var url = 'getOfflineIntStatus.do';
            var param = 'regionCd=' + _RegionCdArr;
            requestService(url, param, offlineIntStatusCheckCallback);
        }
    }

    function offlineIntStatusCheckCallback(data) {
        offlineIntStatusData = data;
        drawIntStatus(1, data);
    }

    function drawIntStatus(network, data) {
        var commState;
        if (network == 0) {
            for (var i = 0; i < onlineCenterStatusData.length; i++) {
                if (onlineCenterStatusData[i].REGION_CD == data[0].REGION_CD) {
                    commState = onlineCenterStatusData[i].COMM_STATE;
                    break;
                }
            }
        } else {
            commState = 0;
        }

        var regionCd;
        var siguguCd;
        var intNoArr;
        var commOnOffFlagArr;
        var commOnOffImg;

        for (var ii = 0; ii < data.length; ii++) {
            regionCd = data[ii].REGION_CD;
            sigunguCd = data[ii].SIGUNGU_CD;
            intNoArr = data[ii].INT_NO.split('|');
            commOnOffFlagArr = data[ii].COMM_ON_OFF_FLAG.split('|');

            $('.guIntTotal_' + network + '_' + sigunguCd).text(intNoArr.length);

            //sigunguCd = 41190 부천시 , 41430 의왕시, 41410 군포시

            //commState = 1;

            //시군구 코드가 없으면 상태정보이미지가 없데이트가 안된다...
            if (commState == 0) {
                var guIntErrCnt = 0;
                for (var jj = 0; jj < intNoArr.length; jj++) {
                    if (commOnOffFlagArr[jj] == 1) {
                        guIntErrCnt++;
                        commOnOffImg = 'background-image:url("images/intStatusOff.png");background-position:center center';
                    } else {
                        commOnOffImg = 'background-image:url("images/intStatusOn.png");background-position:center center';
                    }
                    $('#' + regionCd + '_' + network + '_' + intNoArr[jj] + ' .jstree-anchor .jstree-icon').attr('style', commOnOffImg);
                }
                $('.guIntErrCnt_' + network + '_' + sigunguCd).text(guIntErrCnt);
            } else {
                for (var j = 0; j < intNoArr.length; j++) {
                    commOnOffImg = 'background-image:url("images/intStatusOff.png");background-position:center center';
                    $('#' + regionCd + '_' + network + '_' + intNoArr[j] + ' .jstree-anchor .jstree-icon').attr('style', commOnOffImg);
                }
                $('.guIntErrCnt_' + network + '_' + sigunguCd).text(intNoArr.length);
            }

        }
    }

</script>
</body>
</html>

