<%@ 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" %>

<section class="main-container">
    <!-- 좌측목록 지도 영역 -->
    <article class="left-Area">
        <ul class="sub-Tab">
            <li class="on"><a href="/trafficStats/info.do">소통통계</a></li>
<%--            <li><a href="#">교차로교통량</a></li>--%>
        </ul>
        <div class="left-list">
            <div class="condition-box">
                <div class="condition">
                    <select  name="infoList" id="infoList2">
                        <option value="">도로목록</option>
                        <c:forEach var="item" items="${atrdNmList}" varStatus="status">
                            <option value="${item.ATRD_NM}">${item.ATRD_NM}</option>
                        </c:forEach>
                    </select>
                    <label for="infoList2"></label>
                </div>
                <div class="condition statisticList">
                    <select name="sTimeType" id="sTimeType">
                        <option value="sTime">시통계</option>
                        <option value="sDay">일통계</option>
                        <option value="sMonth">월통계</option>
                        <option value="sYear">년통계</option>
                    </select>
                    <label for="sTimeType"></label>
                </div>
                <div class="condition2 statisticList">
                    <label>검색선택</label>
                    <span>
                        <select id="infoYear" name="year" class="statis-search-select" 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;">
                            <c:forEach begin="1" end="12" 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="${lastDate}" varStatus="status">
                                    <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisDate}">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 == thisHour}">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;">
                        <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;">
                        <c:forEach begin="1" end="12" 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="${lastDate}" varStatus="status">
                                <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisDate}">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 == thisHour}">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>
        </div>
    </article>
    <!-- // 좌측목록 지도 영역 -->
    <!-- 서브 지도 영역 -->
    <article class="mapArea statistics">
        <div class="mapContent statistics">
            <div class="road_info-box sub-road_info">
                <img alt="loading" src="/images/ajax_loading.gif" id="loading" style="display:none;position:absolute;left:45%;top:30%;z-index:10"/>
                <table id ="info-road-list" class="info-road-list">
                    <colgroup>
                        <col width="20%">
                        <col width="30%">
                        <col width="20%">
                        <col width="15%">
                        <col width="15%">
                    </colgroup>
                    <thead>
                    <tr>
                        <th  scope="col">도로명</th>
                        <th  scope="col">구간</th>
                        <th  scope="col">통계시각</th>
                        <th  scope="col">속도(km/h)</th>
                        <th  scope="col">통행시간(min)</th>
                    </tr>
                    </thead>
                    <tbody class="content">
	                    <tr>
	                        <td colspan="5" class="nodata" style="height:200px; text-align: center;">데이터가 없습니다.</td>
	                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </article>
    <!-- // 서브 지도 영역 -->
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.3/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script type="text/javascript">

    function excelDown(){
    	if ($('.nodata')[0]) {
    		return alert('조회된 소통정보가 없습니다.');
    	}
        exportExcel();
    }
    const excelHandler = {
        getExcelFileName : function() {
            return _AtrdNm + '-' + $('#sTimeType option:checked').text() + '_' + nowTime() + '.xlsx'; // 테이블이름
        },
        getSheetName : function() {
            return 'Table Sheet'; // 엑셀 하단 시트 이름
        },
        getExcelData : function() { // EXCEL로 변환하고자 하는 테이블 선택
            return document.getElementById('info-road-list');
        },
        getWorksheet : function() {
            return XLSX.utils.table_to_sheet(this.getExcelData());
        }
    }
    function s2ab(s) {
        var buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
        var view = new Uint8Array(buf);  //create uint8array as viewer
        for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
        return buf;
    }
    function exportExcel() {
        var wb = XLSX.utils.book_new(); // step 1. workbook 생성
        var newWorksheet = excelHandler.getWorksheet(); // step 2. 시트 만들기
        XLSX.utils.book_append_sheet(wb, newWorksheet, excelHandler.getSheetName()); // step 3. workbook에 새로만든 워크시트에 이름을 주고 붙인다.
        var wbout = XLSX.write(wb, {bookType:'xlsx',  type: 'binary'}); // step 4. 엑셀 파일 만들기
        saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), excelHandler.getExcelFileName()); // step 5. 엑셀 파일 내보내기
    }
    
	function csvDown(){
		if ($('.nodata')[0]) {
    		return alert('조회된 소통정보가 없습니다.');
    	}
    	var csv = [];
    	var row = [];
    	
    	//1열에는 컬럼명
    	row.push(
			 "도로명",
             "구간",
             "통계시각",
             "속도(km/h)",
             "통행시간(min)"
    	);
    	  
    	csv.push(row.join(","));
    	for (let ii = 0; ii < $('.content').children().length; ii++) {
    		let tr = $('.content').children().eq(ii);
   			row = [];
    		for (let jj = 0; jj < tr.children().length; jj ++) {
    			row.push(tr.children().eq(jj).text());
    		}
    	    csv.push(row.join(","));
    	}
    	csv = csv.join("\n");
    	
    	const filename = _AtrdNm + '-' + $('#sTimeType option:checked').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();
	}
	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;
	}
    var thisYear = "<fmt:formatNumber pattern="00" value="${thisYear}"/>";
    var thisMonth = "<fmt:formatNumber pattern="00" value="${thisMonth}"/>";
    var thisDate = "<fmt:formatNumber pattern="00" value="${thisDate}"/>";
    var thisHour = "<fmt:formatNumber pattern="00" value="${thisHour}"/>";

    $('#infoList2').change(function(){
        let infoListVal = $('#infoList2 option:selected').val();
        _AtrdNm = infoListVal
        //$('#infoList').val(infoListVal);
        //selectAtrdName(infoListVal);
    });

    $('#sTimeType').change(function(){
        sTimeTypeVal = $('#sTimeType option:selected').val();
        if(sTimeTypeVal == 'sDay')
        {
            $('#infoMonth').show();
            $('.infoMonth').show();
            $('#infoDate').show();
            $('.infoDate').show();
            $('#infoHour').hide();
            $('.infoHour').hide();

            $('#infoMonth2').show();
            $('.infoMonth2').show();
            $('#infoDate2').show();
            $('.infoDate2').show();
            $('#infoHour2').hide();
            $('.infoHour2').hide();
        }
        else if(sTimeTypeVal == 'sMonth')
        {
            $('#infoMonth').show();
            $('.infoMonth').show();
            $('#infoDate').hide();
            $('.infoDate').hide();
            $('#infoHour').hide();
            $('.infoHour').hide();

            $('#infoMonth2').show();
            $('.infoMonth2').show();
            $('#infoDate2').hide();
            $('.infoDate2').hide();
            $('#infoHour2').hide();
            $('.infoHour2').hide();
        }
        else if(sTimeTypeVal == 'sYear')
        {
            $('#infoMonth').hide();
            $('.infoMonth').hide();
            $('#infoDate').hide();
            $('.infoDate').hide();
            $('#infoHour').hide();
            $('.infoHour').hide();

            $('#infoMonth2').hide();
            $('.infoMonth2').hide();
            $('#infoDate2').hide();
            $('.infoDate2').hide();
            $('#infoHour2').hide();
            $('.infoHour2').hide();
        }
        else
        {
            $('#infoMonth').show();
            $('.infoMonth').show();
            $('#infoDate').show();
            $('.infoDate').show();
            $('#infoHour').show();
            $('.infoHour').show();

            $('#infoMonth2').show();
            $('.infoMonth2').show();
            $('#infoDate2').show();
            $('.infoDate2').show();
            $('#infoHour2').show();
            $('.infoHour2').show();
        }
    });

    var sTimeTypeVal = 'sTime';
    var _AtrdNm= ''


    function selectAtrdName(atrdName){
        $('#infoList2').val(atrdName);
        $('#infoList').val(atrdName);
        _AtrdNm = atrdName;
        getStartZoomInfo = true;
        firstSearch = true;
        selectData();
    }
    
	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(){
        var year = $("#infoYear").val();
        var month = $("#infoMonth").val();
        var date = $("#infoDate").val();
        var hour = $("#infoHour").val();
        var yyyymmddhh;

        var year2 = $("#infoYear2").val();
        var month2 = $("#infoMonth2").val();
        var date2 = $("#infoDate2").val();
        var hour2 = $("#infoHour2").val();
        var yyyymmddhh2;

        if (sTimeTypeVal == 'sTime') {
            yyyymmddhh = year+month+date+hour;
            yyyymmddhh2 = year2+month2+date2+hour2;
        }
        else if (sTimeTypeVal == 'sDay') {
            yyyymmddhh = year+month+date;
            yyyymmddhh2 = year2+month2+date2;
        }
        else if (sTimeTypeVal == 'sMonth') {
            yyyymmddhh = year+month;
            yyyymmddhh2 = year2+month2;
        }
        else if (sTimeTypeVal == 'sYear') {
            yyyymmddhh = year;
            yyyymmddhh2 = year2;
        }
		
        if (yyyymmddhh > yyyymmddhh2) {
			return alert("검색 시작 일이 종료 일보다 큽니다.");
		}
        
        if(false)
        {
            var xCrdnMin = map.getBounds().minX();
            var xCrdnMax = map.getBounds().maxX();
            var yCrdnMin = map.getBounds().minY();
            var yCrdnMax = map.getBounds().maxY();

            var xCrdnMin2 = xCrdnMin-0.02;
            var xCrdnMax2 = xCrdnMax+0.02;
            var yCrdnMin2 = yCrdnMin-0.02;
            var yCrdnMax2 = yCrdnMax+0.02;

            var url="/common/getVertexHistory.do";
            var params="level="+level+"&xCrdnMin="+xCrdnMin2+"&xCrdnMax="+xCrdnMax2+"&yCrdnMin="+yCrdnMin2+"&yCrdnMax="+yCrdnMax2+"&yyyymmddhh="+yyyymmddhh+"&atrdNm="+_AtrdNm+"&sTimeTypeVal="+sTimeTypeVal;
            
            $.ajax({
                type:'POST',
                url:url,
                data:params,
                success: function(data){
                    vertexData = data;
                    if(_AtrdNm != '' && firstSearch == true && vertexData.length != 0)
                    {
                        var halfData = Math.round(vertexData.length);
                        var halfData = Math.round(vertexData.length / 2);
                        var crdnArrX = vertexData[halfData].X_CRDN.split(",");
                        var crdnArrY = vertexData[halfData].Y_CRDN.split(",");

                        var halfDataLeng = Math.round(crdnArrX.length / 2);
                        map.setCenter(new naver.maps.LatLng(crdnArrY[halfDataLeng],crdnArrX[halfDataLeng]));
                        firstSearch = false;
                    }

                    drawVertex();

                    //var timeText = year + "년 " + month + "월 " + date + "일 " + hour + "시 (소통상황통계)";
                    //$("#statisticDay").text(timeText);

                },
                beforeSend : function(){
                    $('#loading').show();
                },
                complete : function(){
                    $('#loading').hide();
                }
            });
        }
        else
        {
            var excelEle = '';
            excelEle += '<label for="statisticDay" id="statisticDay"></label>';
            excelEle += '<input type="button" value="통계조회" class="search-btn" onclick="selectData()">';
            excelEle += '<input type="button" value="엑셀" class="excel-btn" onclick="infoWriteExcel()">';
            $('#search-area').empty().append(excelEle);

            var url="/trafficStats/getVertexHistoryText.do";
            var params="atrdNm="+_AtrdNm+"&yyyymmddhh="+yyyymmddhh+"&yyyymmddhh2="+yyyymmddhh2+"&sTimeTypeVal="+sTimeTypeVal;
            $.ajax({
                type:'POST',
                url:url,
                data:params,
                success: function(data){
                	const cnt = data.length.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
                	alert("데이터 " + cnt + "건이 조회되었습니다.");
                    vertexData = data;

                    var atrdArr = [];
                    var strtNmArr = [];
                    var endNmArr = [];
                    var prcnDtArr = [];
                    var spedArr = [];
                    var trvlHhArr = [];
                    var str = '';
                    var grad_cd = '';
					const tbody = $('.content');
					
					tbody.empty();
                    
					if (data.length == 0) {
                    	tbody.append($('<tr><td colspan="5" class="nodata" style="height:200px">데이터가 없습니다.</td></tr>'));
                    }
                    else {
                        for (var ii = 0; ii < vertexData.length; ii++) {
                            var yyyy = vertexData[ii].STAT_DT.substring(0,4);
                            var mm = vertexData[ii].STAT_DT.substring(4,6);
                            var dd = vertexData[ii].STAT_DT.substring(6,8);
                            var hh = vertexData[ii].STAT_DT.substring(8,10);
                            var mi = vertexData[ii].STAT_DT.substring(10,12);
                            var ss = vertexData[ii].STAT_DT.substring(12,14);
                            var prcnDt = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + mi + ':' + ss;

                            str += '<tr>';
                            str += '<td>'+vertexData[ii].ROAD_NM+'</td>';
                            str += '<td>'+vertexData[ii].STRT_NM+' - '+vertexData[ii].END_NM+'</td>';
                            str += '<td>'+prcnDt+'</td>';
                            str += '<td>'+vertexData[ii].SPED+'</td>';
                            str += '<td>'+vertexData[ii].TRVL_HH+'</td>';
                            str += '</tr>';

                            atrdArr.push(vertexData[ii].ROAD_NM);
                            strtNmArr.push(vertexData[ii].STRT_NM);
                            endNmArr.push(vertexData[ii].END_NM);
                            prcnDtArr.push(prcnDt);
                            spedArr.push(vertexData[ii].SPED);
                            trvlHhArr.push(vertexData[ii].TRVL_HH);
                        }
                        str += '<input type="hidden" name="atrdNm" value="'+atrdArr+'" />';
                        str += '<input type="hidden" name="strtNm" value="'+strtNmArr+'" />';
                        str += '<input type="hidden" name="endNm" value="'+endNmArr+'" />';
                        str += '<input type="hidden" name="prcnDt" value="'+prcnDtArr+'" />';
                        str += '<input type="hidden" name="sped" value="'+spedArr+'" />';
                        str += '<input type="hidden" name="trvlHh" value="'+trvlHhArr+'" />';
                        tbody.html(str);
                    }
                },
                beforeSend : function(){
                    $('#loading').show();
                    btnActiveState(true);
                },
                complete : function(){
                    $('#loading').hide();
                    btnActiveState(false);
                }
            });
        }

    }

</script>
