<%@ 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/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ page import="java.text.NumberFormat" %>
<%@ page import="java.util.Map" %>

<section class="main-container">
    <!-- 좌측목록 지도 영역 -->
    <article class="left-Area">
        <ul class="sub-Tab">
            <li class="on"><a href="#">교차로 교통량 통계</a></li>
        </ul>
        <div class="left-list">
            <div class="condition-box">
                <div class="search-box">
                    <input type="text" autocomplete="off" placeholder="검색어를 입력해주세요" id="searchText" alt="교차로 검색" onkeyup="searchEvent(event)">
                    <div id="searchBtn" onclick="searchEvent()">조회</div>
                </div>
                <div class="condition">
                    <div class="list-box">
                        <c:if test="${list.size() > 0}">
                            <c:forEach var="item" items="${list}" varStatus="status">
                             <input type="checkbox" value="${item.IXR_ID}" id="ixr_${item.IXR_ID}" style="display: none;" title="${item.IXR_NM}">
                             <label for="ixr_${item.IXR_ID}" ondblclick="moveEvent('selected-ixr', 'list-box')" onclick="setCenter('${item.IXR_ID}', 'ixr_${item.IXR_ID}')" title="${item.IXR_NM}">${item.IXR_ID}. ${item.IXR_NM}</label>
                            </c:forEach>
                        </c:if>
                    </div>
                    <div class="list-select">
                        <select name="infoList" id="infoList" onchange="optionChange(this)">
                            <option>교차로 목록</option>
                            <c:if test="${list.size() > 0}">
                                <c:forEach var="item" items="${list}" varStatus="status">
                                    <option value="${item.IXR_ID}">${item.IXR_ID}. ${item.IXR_NM}</option>
                                </c:forEach>
                            </c:if>
                        </select>
                        <label for="infoList" style="display: none;"></label>
                    </div>
                </div>

                <div class="button-box">
                    <div>
                        <div onclick="moveEvent('selected-ixr', 'list-box')">▼</div>
                        <div onclick="moveEvent('list-box', 'selected-ixr')">▲</div>
                    </div>
                    <div>
                        <div onclick="totMoveEvent('selected-ixr', 'list-box')">전체선택</div>
                        <div onclick="totMoveEvent('list-box', 'selected-ixr')">전체해제</div>
                    </div>
                </div>
                <div class="condition selected-ixr">
                    <div>
                        <c:if test="${list.size() > 0}">
                            <c:forEach var="item" items="${list}" varStatus="status">
                                <input type="checkbox" value="${item.IXR_ID}" id="ixr_${item.IXR_ID}_selected" style="display: none;" title="${item.IXR_NM}">
                                <label for="ixr_${item.IXR_ID}_selected" style="display: none;" ondblclick="moveEvent('list-box', 'selected-ixr')" onclick="setCenter('${item.IXR_ID}', 'ixr_${item.IXR_ID}_selected')" title="${item.IXR_NM}">${item.IXR_ID}. ${item.IXR_NM}</label>
                            </c:forEach>
                        </c:if>
                    </div>
                </div>
                <div class="condition statisticList">
                    <select name="sTimeType" id="sTimeType">
                        <option value="15M">15분 통계</option>
                        <option value="HH">시통계</option>
                        <option value="DD">일통계</option>
                        <option value="MN">월통계</option>
                    </select>
                    <label for="sTimeType"></label>
                </div>
                <div class="condition2 statisticList">
                    <label>검색선택</label>
                    <span>
                        <select id="infoYear" name="year" class="statis-search-select" onchange="selectDateChanger(true, false)" style="width: 70px;">
                            <c:forEach begin="2022" end="${thisYear}" varStatus="status">
                                    <option value="${status.current}" <c:if test="${status.current == thisYear}">selected</c:if>>${status.current}</option>
                        	</c:forEach>
                        </select>
                        <label for="infoYear">년</label>
                            <select id="infoMonth" name="month" class="statis-search-select" style="width: 50px;" onchange="selectDateChanger(false, false)">
                            <c:forEach begin="1" end="${thisMonth}" varStatus="status">
                                    <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisMonth}">selected</c:if>><fmt:formatNumber pattern="00" value="${status.current}"/></option>
                        </c:forEach>
                        </select>
                        <label for="infoMonth" class="infoMonth">월</label>
                        <select id="infoDate" name="date" class="statis-search-select" style="width: 50px;">
                        <c:forEach begin="1" end="${thisDate}" varStatus="status">
                                <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisDate - 1}">selected</c:if>><fmt:formatNumber pattern="00" value="${status.current}"/></option>
                        </c:forEach>
                        </select>
                        <label for="infoDate" class="infoDate">일</label>
                        <select id="infoHour" name="hour" class="statis-search-select" style="width: 50px;">
                        <c:forEach begin="0" end="23" varStatus="status">
                                <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == 0}">selected</c:if>><fmt:formatNumber pattern="00" value="${status.current}"/></option>
                        </c:forEach>
                        </select>
                        <label for="infoHour" class="infoHour">시</label>
                    </span>
                    <span>~</span>
                    <span>
                        <select id="infoYear2" name='year2' class="statis-search-select" style="width: 70px;" onchange="selectDateChanger(true, true)">
                        <c:forEach begin="2022" end="${thisYear}" varStatus="status">
                                <option value="${status.current}" <c:if test="${status.current == thisYear}">selected</c:if>>${status.current}</option>
                        </c:forEach>
                        </select>
                        <label for="infoYear2">년</label>

                        <select id="infoMonth2" name='month2' class="statis-search-select" style="width: 50px;" onchange="selectDateChanger(false, true)">
                        <c:forEach begin="1" end="${thisMonth}" varStatus="status">
                                <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisMonth}">selected</c:if>><fmt:formatNumber pattern="00" value="${status.current}"/></option>
                        </c:forEach>
                        </select>
                        <label for="infoMonth2" class="infoMonth2">월</label>

                        <select id="infoDate2" name='date2' class="statis-search-select" style="width: 50px;">
                        <c:forEach begin="1" end="${thisDate}" varStatus="status">
                                <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisDate - 1}">selected</c:if>><fmt:formatNumber pattern="00" value="${status.current}"/></option>
                        </c:forEach>
                        </select>
                        <label for="infoDate2" class="infoDate2">일</label>

                        <select id="infoHour2" name='hour2' class="statis-search-select" style="width: 50px;">
                        <c:forEach begin="0" end="23" varStatus="status">
                                <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == 23}">selected</c:if>><fmt:formatNumber pattern="00" value="${status.current}"/></option>
                        </c:forEach>
                        </select>
                        <label for="infoHour2" class="infoHour2">시</label>
                    </span>
                </div>
                <div class="btn-box statisticList">
                    <button type="button"  value="통계조회" class="btn-main search-btn" onclick="selectData()">통계 조회</button>
                </div>
                <div class="btn-box statisticList">
                    <button type="button"  value="엑셀" class="btn-sub excel-btn" onclick="excelDown()">엑셀 저장</button>
                    <button type="button" value="엑셀" class="btn-sub csv-btn" onclick="csvDown()">텍스트 저장</button>
                    <a class='csv-a' style="display:none;"></a>
                </div>
                <div style="display: flex; gap: 10px; align-items: center; justify-content: flex-end; margin-top: 5px; padding: 2px; margin-left: auto;">
                    <label for="limit" style="font-size: 16px;">조회된 라인 수</label><input style="width: 150px; box-sizing: border-box;  padding-right: 10px; text-align: right;" id="limit" disabled type="text" name="limit" value="0" title="조회된 라인 수">
                </div>
            </div>
        </div>
    </article>
    <!-- // 좌측목록 지도 영역 -->
    <!-- 서브 지도 영역 -->
    <article class="mapArea statistics">
        <div id="statistics_map"></div>
        <div class="move-up" onclick="move(this)"></div>
        <div class="mapContent statistics">
            <div class="check-text">※ 교통량과 방향 확인 후 이용하시기 바랍니다.</div>
            <div class="road_info-box sub-road_info">
                <img alt="loading" src="/images/ajax_loading.gif" id="loading" style="display:none;position:absolute;left:calc(50% - 25px);top:calc(50%);z-index:10; width: 50px; height: 50px;"/>
                <table id ="info-road-list" class="info-road-list">
                    <colgroup>
                        <col width="3%">
                        <col width="10%">
                        <col width="10%">
                        <col width="5%">
                        <col width="7%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                        <col width="5%">
                    </colgroup>
                    <thead>
                    <tr style="border-bottom: 1px solid white;">
                        <th scope="col" rowspan="2">ID</th>
                        <th scope="col" rowspan="2">교차로명</th>
                        <th scope="col" rowspan="2">카메라방향</th>
                        <th scope="col" rowspan="2">방향</th>
                        <th scope="col" rowspan="2">통계시각</th>
                        <th scope="col" colspan="3">좌회전</th>
                        <th scope="col" colspan="3">직진</th>
                        <th scope="col" colspan="3">우회전</th>
                        <th scope="col" colspan="3">유턴</th>
                        <th scope="col" rowspan="2">합계</th>
                    </tr>
                    <tr>
                        <th scope="col">소형</th>
                        <th scope="col">중형</th>
                        <th scope="col">대형</th>
                        <th scope="col">소형</th>
                        <th scope="col">중형</th>
                        <th scope="col">대형</th>
                        <th scope="col">소형</th>
                        <th scope="col">중형</th>
                        <th scope="col">대형</th>
                        <th scope="col">소형</th>
                        <th scope="col">중형</th>
                        <th scope="col">대형</th>
                    </tr>
                    </thead>
                    <tbody class="content">
	                    <tr>
	                        <td colspan="18" class="nodata" style="height:141px; text-align: center;">표출할 정보가 없습니다.</td>
	                    </tr>
                    </tbody>
                </table>
                <div class="pagination"></div>
            </div>
        </div>
    </article>
    <!-- // 서브 지도 영역 -->
</section>
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=${key}"></script>
<script src="/js/exceljs-4.3.0.min.js"></script>
<%--<script src="/js/xlsx-0.18.12.min.js"></script>--%>
<script src="/js/fileSaver-1.3.8.min.js"></script>
<script type="text/javascript">
    let _statLimit = ${statLimit};
    let listInfo = '${list}';

    const matches = [...listInfo.matchAll(/IXR_ID=(\w+).*?CMRA_COUNT=(\d+)/g)];

    // Map 객체 생성
    const idToCameraCount = new Map(matches.map(match => [match[1], Number(match[2])]));
    let _ixrMap = new Map();
    let _seletData = [];
    let _Param = null;
    let _type = "";
    const sizeArr = [48, 48, 48, 36, 36, 32, 32, 24, 24, 24, 24];
    const mapContainer = document.getElementById('statistics_map'), // 지도를 표시할 div
        mapOption = {
            center: new kakao.maps.LatLng('37.01423130393533', '126.93995173968553'), // 평택지도의 중심좌표
            maxLevel: 9,
            minLevel: 1,
            level: 10, // 지도의 확대 레벨
            disableDoubleClickZoom: true
    };


    _Map = new kakao.maps.Map(mapContainer, mapOption);

    const mapTypeControl = new kakao.maps.MapTypeControl();
    const zoomControl = new kakao.maps.ZoomControl();
    _Map.addControl(mapTypeControl, kakao.maps.ControlPosition.RIGHT);
    _Map.addControl(zoomControl, kakao.maps.ControlPosition.RIGHT);


    kakao.maps.event.addListener(_Map, 'zoom_changed', function () {
        // 지도의 현재 레벨을 얻어옵니다
        _Level = _Map.getLevel();
        setStyle();
    });

    function move(el) {
        $('.mapContent.statistics').toggleClass('on');
        $('#statistics_map').toggleClass('on');
        $(el).toggleClass('on');
    }

    function optionChange(el) {
        const value = $(el).val();
        totMoveEvent('list-box', 'selected-ixr');
        if (value) {
            $('label[for="ixr_'+value+'"]').click();
            $('label[for="ixr_'+value+'"]').dblclick();
        }
    }
    /**
     * 좌측 상단 도로명 위, 아래 이동 이벤트
     * @param show 보여주는 박스
     * @param hide 가리는 박스
     */
    function moveEvent(show, hide) {
        const hideEl = $("." + hide + ' input[type="checkbox"]:checked');
        const hideLabel = hideEl.next();
        const showEl =  $('.' + show + ' input[value="'+hideEl.val()+'"]');
        const showLabel = showEl.next();
        hideLabel.css('display', 'none');
        showLabel.css('display', 'inline-block');
        showEl.prop('checked', true);
    }

    /**
     * 좌측 상단 도로명 전체 선택, 해제 이벤트
     * @param show 보여주는 박스
     * @param hide 가리는 박스
     */
    function totMoveEvent(show, hide) {
        const showEl = $("." + show + ' input[type="checkbox"]');
        const showLabel = showEl.next();
        const hideEl = $("." + hide + ' input[type="checkbox"]');
        const hideLabel = hideEl.next();
        hideLabel.css('display', 'none');
        showLabel.css('display', 'inline-block');

        const checked = $('.' + hide + ' input[type="checkbox"]:checked');
        if (checked.length) {
            $('.' + show + ' input[value="'+checked.val()+'"]').prop('checked', true);
        }
    }

    getIxrInfo();

    /**
     * 도로 정보
     */
    function getIxrInfo() {
        $.ajax({
            method: "POST",
            url: '/statistics/getIxrList.do',
            success: function (data) {

                if (data && data.length) {
                    data.forEach((obj)=>{
                        _ixrMap.set(obj.ixr_id, new IxrObj(obj));
                    });
                }
            },
            complete: function () {
                drawMarker();
            },
            error: function (request, status, error) {
            },
        });
    }

    function getAtrdLevel() {
        let level = _Level;

        if (level <= 7) {
            level = 5;
        }
        else {
            level = 6;
        }

        return level;
    }

    /**
     * 도로 표출 Object
     */
    class IxrObj {
        constructor(obj) {
            this.id = obj.ixr_id;
            this.nm = obj.ixr_nm;
            this.x_crdn = obj.ixr_x_crdn;
            this.y_crdn = obj.ixr_y_crdn;
            this.obj = obj;
            this.content = null;
            this.marker = null;
            this.makeMarkers();
            this.isClick = false;
        }

        makeMarkers() {
            const imageSrc = '/images/intersection.png';
            const size = sizeArr[_Level];
            const imageSize = new daum.maps.Size(size, size);
            const imageOption = {
                offset: new daum.maps.Point(size/2, size/2)
            };

            const markerImage = new daum.maps.MarkerImage(imageSrc, imageSize, imageOption);
            const markerPosition = new daum.maps.LatLng(this.y_crdn, this.x_crdn); // 마커가 표시될 위치입니다
            this.marker = new daum.maps.Marker({position: markerPosition, image: markerImage, zIndex: 5});
            const obj = this;
            this.content = new kakao.maps.CustomOverlay({
                position: new kakao.maps.LatLng(this.y_crdn, this.x_crdn),
                content: '<div style="background-color: white; border: 1px solid #cccccc; padding: 2px;">' + this.nm + '<div>',
                yAnchor: 2,
                zIndex: 10,
            });

            daum.maps.event.addListener(this.marker, 'mouseover', function () {
                obj.content.setMap(_Map);

                daum.maps.event.addListener(obj.marker, 'mouseout', function () {
                    obj.content.setMap(null);
                });
            });
        }


        /**
         * 보이기/숨기기
         * @param isShow : _Map or null
         */
        showHide(isShow) {
            if (this.marker) {
                this.marker.setMap(isShow);
            }
        }

        click(id) {
            const selected = _ixrMap.get('click')
            if (selected) {
                if (selected.id === this.id) return $('#' + id).prop('checked', false);
                const imageSrc = '/images/intersection.png';
                const size = sizeArr[_Level];
                const imageSize = new daum.maps.Size(size, size);
                const imageOption = {
                    offset: new daum.maps.Point(size/2, size/2)
                };

                const markerImage = new daum.maps.MarkerImage(imageSrc, imageSize, imageOption);
                selected.marker.setImage(markerImage);
                selected.isClick = false;
                selected.id
            }
            $('input[type="checkbox"]:not(#'+id+')').prop('checked', false);
            _Map.setCenter(new kakao.maps.LatLng(this.y_crdn, this.x_crdn));
            const imageSrc = '/images/intersection2.png';
            const size = sizeArr[_Level];
            const imageSize = new daum.maps.Size(size, size);
            const imageOption = {
                offset: new daum.maps.Point(size/2, size/2)
            };

            const markerImage = new daum.maps.MarkerImage(imageSrc, imageSize, imageOption);
            this.marker.setImage(markerImage);
            this.isClick = true;
            _ixrMap.set('click', this);
        }
    }

    /**
     * 지도에 도로 표출
     */
    function drawMarker() {
        if (_ixrMap.size) {
            _ixrMap.forEach((obj)=>{
                obj.showHide(_Map);
            })
        }
    }


    function setStyle() {
        const size = sizeArr[_Level];
        _ixrMap.forEach((obj)=>{
            let imageSrc = '/images/intersection';
            if (obj.isClick) {
                imageSrc += '2';
            }
            imageSrc += '.png';
            const imageSize = new daum.maps.Size(size, size);
            const imageOption = {
                offset: new daum.maps.Point(size/2, size/2)
            };

            const markerImage = new daum.maps.MarkerImage(imageSrc, imageSize, imageOption);
            obj.marker.setImage(markerImage);
        })
    }

    function setCenter(ixrId, id) {
       if (_ixrMap.get(ixrId)) {
           _ixrMap.get(ixrId).click(id);
           _Map.setLevel(5);
       }
    }

    function excelDown(){
    	if (!_seletData || !_seletData.list || !_seletData.list.length) {
    		return alert('조회된 교차로 교통량 정보가 없습니다.');
    	}
        exportExcel();
    }

    function exportExcel() {
        const fileName = '교차로 교통량 통계 - ' + $('option[value="'+_type+'"]').text() + '_' + nowTime() + '.xlsx';
        const link = document.createElement('a');
        const blob = base64ToBlob(_seletData.excel, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        const url = URL.createObjectURL(blob);

        link.href = url;
        link.download = fileName;  // 다운로드할 파일 이름 설정
        link.click();
        URL.revokeObjectURL(url);  // URL 객체 해제
    }

    function base64ToBlob(base64, mimeType) {
        const byteCharacters = atob(base64);  // Base64를 디코딩
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += 1024) {
            const slice = byteCharacters.slice(offset, offset + 1024);
            const byteNumbers = new Array(slice.length);

            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            const byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }

        return new Blob(byteArrays, { type: mimeType });
    }
    
	function csvDown(){
        if (!_seletData || !_seletData.list || !_seletData.list.length) {
            return alert('조회된 교차로 교통량 정보가 없습니다.');
        }
    	//1열에는 컬럼명
        let csv = [
            [ "ID," +
              "교차로명," +
              "카메라방향," +
              "방향," +
              "통계시각," +
              "좌회전(소형)," +
              "좌회전(중형)," +
              "좌회전(대형)," +
              "직진(소형)," +
              "직진(중형)," +
              "직진(대형)," +
              "우회전(소형)," +
              "우회전(중형)," +
              "우회전(대형)," +
              "유턴(소형)," +
              "유턴(중형)," +
              "유턴(대형)," +
              "합계"
            ]
       ];

        for (let obj of _seletData.list) {
            let tot_tfvl        = numberComma(obj.tot_tfvl);
            let smal_go_tfvl    = numberComma(obj.smal_go_tfvl);
            let mddl_go_tfvl    = numberComma(obj.mddl_go_tfvl);
            let lrg_go_tfvl     = numberComma(obj.lrg_go_tfvl);
            let smal_left_tfvl  = numberComma(obj.smal_left_tfvl);
            let mddl_left_tfvl  = numberComma(obj.mddl_left_tfvl);
            let lrg_left_tfvl   = numberComma(obj.lrg_left_tfvl);
            let smal_right_tfvl = numberComma(obj.smal_rght_tfvl);
            let mddl_right_tfvl = numberComma(obj.mddl_rght_tfvl);
            let lrg_right_tfvl  = numberComma(obj.lrg_rght_tfvl);
            let smal_uturn_tfvl = numberComma(obj.smal_uturn_tfvl);
            let mddl_uturn_tfvl = numberComma(obj.mddl_uturn_tfvl);
            let lrg_uturn_tfvl  = numberComma(obj.lrg_uturn_tfvl);

            const statDt = obj.clct_dt;
            let yyyy = statDt.substring(0,4);
            let mm   = statDt.substring(4,6);
            let dd   = statDt.substring(6,8);
            let hh   = statDt.substring(8,10);
            let mi   = statDt.substring(10,12);
            let ss   = statDt.substring(12,14);
            let clctDt = '-';
            if (_type === 'MN') {
                clctDt = yyyy + '년 ' + mm + '월';
            }
            else if (_type === 'DD') {
                clctDt = yyyy + '/' + mm + '/' + dd;
            }
            else {
                clctDt = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + mi + ':' + ss;
            }


            const row = [ obj.ixr_id + "," +
                          obj.ixr_nm + "," +
                          obj.cmra_nm + "," +
                          obj.drct_dvsn_cd_r + "," +
                          clctDt + "," +
                          smal_left_tfvl + "," +
                          mddl_left_tfvl + "," +
                          lrg_left_tfvl  + "," +
                          smal_go_tfvl + "," +
                          mddl_go_tfvl + "," +
                          lrg_go_tfvl  + "," +
                          smal_right_tfvl + "," +
                          mddl_right_tfvl + "," +
                          lrg_right_tfvl  + "," +
                          smal_uturn_tfvl + "," +
                          mddl_uturn_tfvl + "," +
                          lrg_uturn_tfvl + "," +
                          tot_tfvl ];
            csv.push(row);
        }
    	csv = csv.join("\n");
    	
    	const filename = '교차로 교통량 통계 - '+ $('option[value="'+_type+'"]').text() + '_' + nowTime() + '.csv';
    	
		var csvFile;
		var downloadLink;
		
		//한글 처리를 해주기 위해 BOM 추가하기
		const BOM = "\uFEFF";
		csv = BOM + csv;
		
		csvFile = new Blob([csv], { type: "text/csv" });
		downloadLink = document.querySelector(".csv-a");
		downloadLink.download = filename;
		downloadLink.href = window.URL.createObjectURL(csvFile);
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);
		downloadLink.click();
        downloadLink.remove();
	}
	function nowTime() {
		let now = new Date();
	    let year = now.getFullYear().toString();
	    let month = timeFormmater(now.getMonth() + 1).toString();
	    let date = timeFormmater(now.getDate()).toString();
	    let hour = timeFormmater(now.getHours()).toString();
	    let minutes = timeFormmater(now.getMinutes()).toString();
	    let seconds = timeFormmater(now.getSeconds()).toString();
	    return year + month + date + hour + minutes + seconds;
	}
	
	//시간 한자리 경우 2자리로 세팅
	function timeFormmater(time) {
	    let result = time < 10 ? "0" + time.toString() : time.toString();
	    return result;
	}

    /**
     * 통계 타입에 따른 보이기 감추기
     * @param visible 보이는 목록
     * @param hide 가리는 목록
     */
    function inputVisible(visible, hide) {
        if (visible && visible.length) {
            visible.forEach((el)=>{
                $('#' + el).show();
                $('.' + el).show();
            });
        }

        if (hide && hide.length) {
            hide.forEach((el)=>{
                $('#' + el).hide();
                $('.' + el).hide();
            });
        }
    }

    $('#sTimeType').change(function(){
        let sTimeTypeVal = $('#sTimeType option:selected').val();
        if(sTimeTypeVal === 'DD')
        {
            inputVisible(['infoMonth', 'infoDate', 'infoMonth2', 'infoDate2'], ['infoHour', 'infoHour2']);
        }
        else if(sTimeTypeVal === 'MN')
        {
            inputVisible(['infoMonth', 'infoMonth2'], ['infoDate', 'infoDate2', 'infoHour', 'infoHour2']);
        }
        else
        {
            inputVisible(['infoMonth', 'infoMonth2', 'infoDate', 'infoDate2', 'infoHour', 'infoHour2'], []);
        }
    });

	function btnActiveState(stts){
    	const searchBtn = $('.btn-main.search-btn');
    	const excelBtn  = $('.btn-sub.excel-btn');
    	const csvBtn    = $('.btn-sub.csv-btn');
		searchBtn.prop('disabled', stts);
    	excelBtn.prop('disabled', stts);
    	csvBtn.prop('disabled', stts);
	}
	
    function selectData(){
        const type = $('#sTimeType').val();
        const selectList = $('.list-select');
        // let ids = "";
        let ids = [];
        if (selectList.css('display') === 'none') {
            const checkArr = $('.selected-ixr input[type="checkbox"]');
            for (let ii = 0; ii < checkArr.length; ii++) {
                const check = checkArr.eq(ii);
                if (check.next().css('display') !== 'none') {
                    const ixrId = check.val();
                    // ids += ixrId + ',';
                    ids.push(ixrId);
                }
            }
        }
        else {
            const infoList = $('#infoList');
            if (infoList.val() !== '교차로 목록') {
                ids.push(infoList.val());
            }
        }

        const selectSize = ids.length;
        if (selectSize === 0) return alert('교차로 목록을 선택해주세요.');// 선택 도로목록 확인

        let year  = $("#infoYear").val();
        let month = $("#infoMonth").val();
        let date  = $("#infoDate").val();
        let hour  = $("#infoHour").val();
        let from;
        const year2El  = $("#infoYear2");
        const month2El = $("#infoMonth2");
        const date2El  = $("#infoDate2");
        const hour2El  = $("#infoHour2");

        let year2  = year2El.val();
        let month2 = month2El.val();
        let date2  = date2El.val();
        let hour2  = hour2El.val();
        let to;
        let fromDate;
        let toDate;
        let fromDateWord;
        if (type === '15M' || type === 'HH') {
            from = year+month+date+hour + '0000';
            to = year2+month2+date2+hour2 + '5959';
            toDate = new Date(year2 + "-" +month2 + "-" + date2 + " " + hour2 + ":59:59");
            fromDateWord = year + "-" +month + "-" + date + " " + hour + ":00:00";
            fromDate = new Date(fromDateWord);
            fromDate.setDate(new Date(fromDate).getDate() - 1);
            fromDate.setSeconds(new Date(fromDate).getSeconds() - 1);
        }
        else if (type === 'DD') {
            from = year+month+date + '000000';
            to = year2+month2+date2 + '235959';
            toDate = new Date(year2 + "-" +month2 + "-" + date2 + " 23:59:59");
            fromDateWord = year + "-" +month + "-" + date + " 00:00:00";
            fromDate = new Date(fromDateWord);
            fromDate.setDate(new Date(fromDate).getDate() - 1);
            fromDate.setSeconds(new Date(fromDate).getSeconds() - 1);
        }
        else if (type === 'MN') {
            const lastDate = new Date(year2, month2, 0);
            const last = lastDate.getDate();
            from = year+month + '01000000';
            to = year2+month2 + last + '235959';
            toDate = new Date(year2 + "-" +month2 + "-" + last + " 23:59:59");
            fromDateWord = year + "-" +month + "-01 00:00:00";
            fromDate = new Date(fromDateWord);
            fromDate.setDate(new Date(fromDate).getDate() - 1);
            fromDate.setSeconds(new Date(fromDate).getSeconds() - 1);
        }

        if (from > to) {
			return alert("검색 시작 일이 종료 일보다 큽니다.");
		}

        const limitDate = getLimitDate(selectSize, type, fromDate, ids);

        if (toDate > limitDate) {
            const yyyy = limitDate.getFullYear();
            const MM = String(limitDate.getMonth() + 1).padStart(2, '0');
            const dd = String(limitDate.getDate()).padStart(2, '0');
            const HH = String(limitDate.getHours()).padStart(2, '0');
            const mm = String(limitDate.getMinutes()).padStart(2, '0');
            const ss = String(limitDate.getSeconds()).padStart(2, '0');
            const formattedDate = `\${yyyy}-\${MM}-\${dd} \${HH}:\${mm}:\${ss}`;
            if (confirm("현재 조회 기간이 데이터 조회 최대 기간을 초과하였습니다.\n조회 기간을 변경하여 데이터를 조회하시겠습니까?" +
                "\n검색 기간 : " + fromDateWord + " ~ " + formattedDate)) {
                to = yyyy + MM + dd + HH + mm + ss;
                year2El.val(yyyy).change();
                month2El.val(MM).change();
                date2El.val(dd);
                hour2El.val(HH);
            }
            else {
                return;
            }
        }

        const params = {
            ixrIds : ids,
            from : from,
            to : to,
            type : type,
        }
        const tbody = $('.content');

        tbody.empty();
        const pagination = $('.pagination');
        pagination.empty();
        _seletData = null;
        _type = null;
        const limit = $('#limit');
        limit.val(0);
        $.ajax({
            type:'POST',
            url: "/statistics/getIxrTrafficStat.do",
            traditional: true,
            data: params,
            success: function(data){
                _seletData = data;
                _type = type;
                const cnt = data.list.length.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
                alert("데이터 " + cnt + "건이 조회되었습니다.");
                limit.val(cnt);
            },
            error : (error)=> {
                console.log(error);
                alert("데이터 조회중 오류가 발생했습니다.\n" + error.responseJSON.message);
            },
            beforeSend : function(){
                $('#loading').show();
                btnActiveState(true);
            },
            complete : function(){
                $('#loading').hide();
                btnActiveState(false);
                drawTable(1);
                // loadPage(1);
            }
        });
    }

    // let currentPage = 1;
    // const tableContainer = $('.road_info-box.sub-road_info');
    // tableContainer.on('scroll', function(){
    //     if ($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight - 5) {
    //         currentPage++;
    //         loadPage(currentPage);
    //     }
    // })

    function appendDataToTable(startIndex, endIndex) {
        const tbody = $('.content');
        const table = $('.info-road-list');
        if (_seletData.list.length === 0) {
            table.css('height', '100%');
            tbody.append($('<tr><td colspan="18" class="nodata" style="height:141px">표출할 정보가 없습니다.</td></tr>'));
        }
        else {
            table.css('height', 'auto');
            const paginatedData = _seletData.list.slice(startIndex, endIndex);

            paginatedData.forEach(item => {
                const row = document.createElement('tr');
                const obj = item;
                const statDt = obj.clct_dt;
                let yyyy = statDt.substring(0, 4);
                let mm = statDt.substring(4, 6);
                let dd = statDt.substring(6, 8);
                let hh = statDt.substring(8, 10);
                let mi = statDt.substring(10, 12);
                let ss = statDt.substring(12, 14);

                let clctDt = '-';
                if (_type === 'MN') {
                    clctDt = yyyy + '년 ' + mm + '월';
                } else if (_type === 'DD') {
                    clctDt = yyyy + '/' + mm + '/' + dd;
                } else {
                    clctDt = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + mi + ':' + ss;
                }

                let tot_tfvl = numberComma(obj.tot_tfvl);
                let smal_go_tfvl = numberComma(obj.smal_go_tfvl);
                let mddl_go_tfvl = numberComma(obj.mddl_go_tfvl);
                let lrg_go_tfvl = numberComma(obj.lrg_go_tfvl);
                let smal_left_tfvl = numberComma(obj.smal_left_tfvl);
                let mddl_left_tfvl = numberComma(obj.mddl_left_tfvl);
                let lrg_left_tfvl = numberComma(obj.lrg_left_tfvl);
                let smal_right_tfvl = numberComma(obj.smal_rght_tfvl);
                let mddl_right_tfvl = numberComma(obj.mddl_rght_tfvl);
                let lrg_right_tfvl = numberComma(obj.lrg_rght_tfvl);
                let smal_uturn_tfvl = numberComma(obj.smal_uturn_tfvl);
                let mddl_uturn_tfvl = numberComma(obj.mddl_uturn_tfvl);
                let lrg_uturn_tfvl = numberComma(obj.lrg_uturn_tfvl);

                row.innerHTML = `<td>\${obj.ixr_id}</td>
                                 <td>\${obj.ixr_nm}</td>
                                 <td>\${obj.cmra_nm}</td>
                                 <td>\${obj.drct_dvsn_cd_r}</td>
                                 <td>\${clctDt}</td>
                                 <td>\${smal_left_tfvl}</td>
                                 <td>\${mddl_left_tfvl}</td>
                                 <td>\${lrg_left_tfvl}</td>
                                 <td>\${smal_go_tfvl}</td>
                                 <td>\${mddl_go_tfvl}</td>
                                 <td>\${lrg_go_tfvl}</td>
                                 <td>\${smal_right_tfvl}</td>
                                 <td>\${mddl_right_tfvl}</td>
                                 <td>\${lrg_right_tfvl}</td>
                                 <td>\${smal_uturn_tfvl}</td>
                                 <td>\${mddl_uturn_tfvl}</td>
                                 <td>\${lrg_uturn_tfvl}</td>
                                 <td>\${tot_tfvl}</td>`
                tbody.append(row);
            });
        }
    }

    function loadPage(page) {
        const rowsPerPage = 10;

        const startIndex = (page - 1) * rowsPerPage;
        const endIndex = page * rowsPerPage;
        appendDataToTable(startIndex, endIndex);
    }



    function getLimitDate(selectSize, type, startDate, ids) {
        const limits = (type === '15M') ? 4 : 1;

        let tot = 0;
        for(let id of ids) {
            tot += idToCameraCount.get(id) || 0;
        }

        const limitRate = Math.floor(_statLimit / (tot * limits));
        const date = new Date(startDate);
        let setMethod = "Hours";
        if (type === 'DD') {
            setMethod = "Date";
        }
        else if (type === 'MN') {
            setMethod = "Month";
        }

        return new Date(date["set" + setMethod](date["get" + setMethod]() + limitRate));
    }

    function drawTable(idx) {
        const tbody = $('.content');
        let str = '';
        const table = $('.info-road-list');
        const pagination = $('.pagination');
        pagination.hide();
        const rowsPerPage = 12;
        const pagesPerGroup = 10;
        if (!_seletData || !_seletData.list || _seletData.list.length === 0) {
            table.css('height', '100%');
            str = '<tr><td colspan="18" class="nodata" style="height:141px">표출할 정보가 없습니다.</td></tr>';
        }
        else {

            table.css('height', 'auto');
            let start = (idx - 1) * rowsPerPage;
            let end = start + rowsPerPage;
            let max = _seletData.list.length;

            if (max < end) end = max;
            let pageStr = "";
            if (max > rowsPerPage) {
                const totalPage = Math.ceil(max / rowsPerPage);
                const currentGroup = Math.ceil(idx / pagesPerGroup);
                const startPage = (currentGroup - 1) * pagesPerGroup + 1;
                const endPage = Math.min(startPage + pagesPerGroup - 1, totalPage);
                pagination.css('display', 'flex');
                if (startPage > 10) {
                    pageStr += "<div onclick='drawTable("+(startPage - 1)+")'>[PREV]</div>";
                }

                for (let ii = startPage; ii <= endPage; ii++) {
                    let className = "";
                    if (ii === idx) {
                        className = "on";
                    }
                    pageStr += "<div class='"+className+"' onclick='drawTable("+ ii +")'>["+ii+"]</div>";
                }

                if (totalPage > endPage) {
                    pageStr += "<div onclick='drawTable("+(endPage + 1)+")'>[NEXT]</div>";
                }
                pagination.html(pageStr);
            }


            for (let ii = start; ii < end; ii++) {
                const obj = _seletData.list[ii];
                const statDt = obj.clct_dt;
                let yyyy = statDt.substring(0, 4);
                let mm = statDt.substring(4, 6);
                let dd = statDt.substring(6, 8);
                let hh = statDt.substring(8, 10);
                let mi = statDt.substring(10, 12);
                let ss = statDt.substring(12, 14);

                let clctDt = '-';
                if (_type === 'MN') {
                    clctDt = yyyy + '년 ' + mm + '월';
                } else if (_type === 'DD') {
                    clctDt = yyyy + '/' + mm + '/' + dd;
                } else {
                    clctDt = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + mi + ':' + ss;
                }

                let tot_tfvl = numberComma(obj.tot_tfvl);
                let smal_go_tfvl = numberComma(obj.smal_go_tfvl);
                let mddl_go_tfvl = numberComma(obj.mddl_go_tfvl);
                let lrg_go_tfvl = numberComma(obj.lrg_go_tfvl);
                let smal_left_tfvl = numberComma(obj.smal_left_tfvl);
                let mddl_left_tfvl = numberComma(obj.mddl_left_tfvl);
                let lrg_left_tfvl = numberComma(obj.lrg_left_tfvl);
                let smal_right_tfvl = numberComma(obj.smal_rght_tfvl);
                let mddl_right_tfvl = numberComma(obj.mddl_rght_tfvl);
                let lrg_right_tfvl = numberComma(obj.lrg_rght_tfvl);
                let smal_uturn_tfvl = numberComma(obj.smal_uturn_tfvl);
                let mddl_uturn_tfvl = numberComma(obj.mddl_uturn_tfvl);
                let lrg_uturn_tfvl = numberComma(obj.lrg_uturn_tfvl);

                str += '<tr>';
                str += '<td>' + obj.ixr_id + '</td>';
                str += '<td>' + obj.ixr_nm + '</td>';
                // str += '<td>'+obj.cmra_nm + ' (' + obj.drct_dvsn_cd + ')' +'</td>';
                str += '<td>' + obj.cmra_nm + '</td>';
                str += '<td>' + obj.drct_dvsn_cd_r + '</td>';
                str += '<td>' + clctDt + '</td>';
                str += '<td>' + smal_left_tfvl + '</td>';
                str += '<td>' + mddl_left_tfvl + '</td>';
                str += '<td>' + lrg_left_tfvl + '</td>';
                str += '<td>' + smal_go_tfvl + '</td>';
                str += '<td>' + mddl_go_tfvl + '</td>';
                str += '<td>' + lrg_go_tfvl + '</td>';
                str += '<td>' + smal_right_tfvl + '</td>';
                str += '<td>' + mddl_right_tfvl + '</td>';
                str += '<td>' + lrg_right_tfvl + '</td>';
                str += '<td>' + smal_uturn_tfvl + '</td>';
                str += '<td>' + mddl_uturn_tfvl + '</td>';
                str += '<td>' + lrg_uturn_tfvl + '</td>';
                str += '<td>' + tot_tfvl + '</td>';
                str += '</tr>';

            }
        }
        tbody.html(str);
    }

    function numberComma(dely_hh) {
        let delyHh = 0;
        if (dely_hh && !isNaN(Number(dely_hh))) {
            delyHh = Number(dely_hh);
            delyHh = delyHh.toLocaleString('ko-KR');
        }
        return delyHh;
    }

    function getExcelTable(fileName) {
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet("교차로 교통량 통계");
        worksheet.addRow(["ID", "교차로명", "카메라방향", "방향", "통계시각", "좌회전(소형)", "좌회전(중형)", "좌회전(대형)", "직진(소형)",
            "직진(중형)", "직진(대형)", "우회전(소형)", "우회전(중형)", "우회전(대형)", "유턴(소형)", "유턴(중형)", "유턴(대형)", "합계"]);
        for (let obj of _seletData) {
            const statDt = obj.clct_dt;
            let yyyy = statDt.substring(0,4);
            let mm   = statDt.substring(4,6);
            let dd   = statDt.substring(6,8);
            let hh   = statDt.substring(8,10);
            let mi   = statDt.substring(10,12);
            let ss   = statDt.substring(12,14);
            let clctDt = '-';
            if (_type === 'MN') {
                clctDt = yyyy + '년 ' + mm + '월';
            }
            else if (_type === 'DD') {
                clctDt = yyyy + '/' + mm + '/' + dd;
            }
            else {
                clctDt = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + mi + ':' + ss;
            }

            const row = [
                 obj.ixr_id,
                 obj.ixr_nm,
                 obj.cmra_nm,
                 obj.drct_dvsn_cd_r,
                 clctDt,
                 obj.smal_left_tfvl,
                 obj.mddl_left_tfvl,
                 obj.lrg_left_tfvl,
                 obj.smal_go_tfvl,
                 obj.mddl_go_tfvl,
                 obj.lrg_go_tfvl,
                 obj.smal_rght_tfvl,
                 obj.mddl_rght_tfvl,
                 obj.lrg_rght_tfvl,
                 obj.smal_uturntfvl,
                 obj.mddl_uturntfvl,
                 obj.lrg_uturntfvl,
                 obj.tot_tfvl
            ]
            worksheet.addRow(row);
        }
        excelJsDowload(workbook, fileName);
    }

    async function excelJsDowload(workbook, fileName) {
        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const anchor = document.createElement('a');
        anchor.href = url;
        anchor.download = fileName + '.xlsx';
        anchor.click();
        window.URL.revokeObjectURL(url);
    }


    /**
     * 년도 날짜에 따른 월, 일 범위값 설정
     * @param(boolean) isSetMonth 일만 변경할건지
     */
    function selectDateChanger(isSetMonth, isTo) {
        const year          = $("#infoYear");
        const month         = $("#infoMonth");
        const day           = $("#infoDate");
        const toYear        = $("#infoYear2");
        const toMonth       = $("#infoMonth2");
        const toDay         = $("#infoDate2");

        let now 	 		= new Date();
        let nowDay   		= now.getDate();
        let nowYear  		= now.getFullYear();
        let nowMonth 		= now.getMonth() + 1;
        let dayVal   		= day.val();
        let monthVal 		= month.val();
        let yearVal         = year.val();
        let monthEl         = month;
        let dayEl           = day;
        if (isTo) {
            dayVal  = toDay.val();
            monthVal = toMonth.val();
            yearVal = toYear.val();
            monthEl = toMonth;
            dayEl  = toDay;
        }

        let lastDate        = new Date(yearVal, monthVal, 0);
        let minDay 	    	= lastDate.getDate();
        let minMonth        = 12;

        if (nowYear.toString() === yearVal) {
            minMonth = nowMonth;
            if (nowMonth === Number(monthVal)) minDay = nowDay;
        }
        if (isSetMonth) {
            setSelectOption(minMonth, monthVal, monthEl);
        }
        setSelectOption(minDay, dayVal, dayEl);
    }

    /**
     * 날짜 Select Box option Setting
     * @param min 마지막 값
     * @param value 현재 값
     * @param target 요소
     * @param word 날짜 글자
     */
    function setSelectOption(min, value, target) {
        let option = getOption(min);
        target.html(option);
        if (min < Number(value)) {
            target.val('01');
        }
        else {
            target.val(value);
        }
    }

    /**
     * 날짜 Select option for문
     * @param rate 종료 값
     * @param word 날짜 글짜
     * @returns {string}
     */
    function getOption(rate) {
        let option = ''
        for ( let ii = 1; ii <= rate; ii++) {
            let value = ii;
            if (ii < 10) {
                value = ('0'+ii);
            }
            option += '<option value="'+value+'">'+value + '</option>';
        }
        return option;
    }

    /**
     * 교차로 검색 이벤트
     * @param el
     */
    function searchEvent(ev) {
        if (!ev || ev.key === 'Enter') {
            const searchText = $('#searchText').val();
            if (searchText === "") {
                return alert('검색어를 입력해주세요');
            }
            const labelArr = $('.list-box label');
          //  totMoveEvent('list-box', 'selected-ixr');
            for (let ii = 0; ii < labelArr.length; ii++) {
                const label = labelArr.eq(ii);
                if (label.text().includes(searchText)) {
                    label.click();
                    label.dblclick();
                }
            }
        }
    }

</script>
