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

<div class="container">
    <div class="subHeader">
        <h1 class="logo">안동시 교통정보센터</h1>
        <div class="pageLocation">
            <%@ include file="/WEB-INF/jsp/egovframework/include/userSubMenu.jsp" %>
        </div>
    </div>
    <div class="trafficWrap">
        <div class="mapAreaWrap">
            <!-- 좌측목록 지도 영역 -->
            <div class="left-Area">
                <div class="left-list">
                    <div class="condition-box">
                        <div class="condition">
                            <select name="atrdName" id="atrdName" control-id="ControlID-3">
                                <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="atrdName"></label>
                        </div>
                        <div class="condition statisticList">
                            <select name="sTimeType" id="sTimeType" control-id="ControlID-4" onchange="searchTypeChanged()">
                                <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">
                            <label>검색선택</label>
                            <div>
                                <select name="begin-year" id="begin-year">
                                    <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="begin-year"></label>
                                년
                                <select name="begin-month" id="begin-month">
                                    <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="begin-month"></label>
                                월
                                <select name="begin-date" id="begin-date">
                                    <c:forEach begin="1" end="${thisDate}" 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="begin-date"></label>
                                일
                                <select name="begin-hours" id="begin-hours">
                                    <c:forEach begin="0" end="${thisHour}" 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="begin-hours"></label>
                                시 <span>~</span>
                            </div>
                            <div>
                                <select name="end-year" id="end-year">
                                    <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="end-year"></label>
                                년
                                <select name="end-month" id="end-month">
                                    <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="end-month"></label>
                                월
                                <select name="end-date" id="end-date">
                                    <c:forEach begin="1" end="${thisDate}" 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="end-date"></label>
                                일
                                <select name="end-hours" id="end-hours">
                                    <c:forEach begin="0" end="${thisHour}" 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="end-hours"></label>
                                시
                            </div>
                        </div>
                        <div class="btn-box statisticList">
                            <button type="button" value="소통 통계 조회" class="btn-main search-btn" onclick="selectData()" control-id="ControlID-13">소통 통계 조회</button>
                        </div>
                        <div class="btn-box statisticList">
                            <button type="button" value="엑셀" class="btn-sub excel-btn" onclick="excelDown()" control-id="ControlID-14">엑셀 저장</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- // 좌측목록 지도 영역 -->
            <div class="mapContent traffic-list-wrap">
                <ul class="traffic-list">
                    <li class="th">
                        <div class="roadName">도로명</div>
                        <div class="roadDetail">구간</div>
                        <div class="time">통계시각</div>
                        <div class="speed">속도</div>
                        <div class="min">통행시간</div>
                    </li>
                    <div class="tbody">

                    </div>
                </ul>
            </div>
        </div>
    </div>
</div>
<div id="loading">
    <img src="/images/ajax_loading.gif" alt="로딩중입니다.">
</div>

<script src="/js/xlsx-0.18.12.min.js"></script>
<script src="/js/fileSaver-1.3.8.min.js"></script>

<script type="text/javascript">
    const noDataText = `<li style="justify-content: center; height:100%;">
                            <div class="no-data" style="font-size: 18px;">
                                <img src="/images/main/no_info_icon.png" width="50">표출할 정보가 없습니다.
                            </div>
                        </li>`;

    const trafficList = $('.tbody');
    const beginYear   = $('#begin-year');
    const beginDate   = $('#begin-date');
    const beginMonth  = $('#begin-month');
    const beginHours  = $('#begin-hours');
    const endYear     = $('#end-year');
    const endMonth    = $('#end-month');
    const endDate     = $('#end-date');
    const endHours    = $('#end-hours');
    const searchType  = $('#sTimeType');
    const atrdName    = $('#atrdName');
    let _excelData    = [];
    let _searchAtrdName = '';
    let _searchAtrdType = '';

    /**
     * 날짜 선택 시 허용 범위 설정
     */
    $('#begin-year, #begin-date, #begin-month').on('change', ()=>{
        yearChanged(beginYear, beginMonth, beginDate, beginHours);
    });

    $('#end-year, #end-date, #end-month').on('change', ()=>{
        yearChanged(endYear, endMonth, endDate, endHours);
    });

    function yearChanged(year, month, date, hours) {
        const now      = new Date();
        const nowYear  = now.getFullYear();
        const nowMonth = now.getMonth() + 1;
        const nowDate  = now.getDate();
        const nowHours = now.getHours();
        const yearVal  = year.val();

        let monthVal    = month.val();
        let dateVal     = date.val();
        let hoursVal    = hours.val();
        let lastDate    = new Date(yearVal, monthVal, 0).getDate();
        let lastMonth   = 12;
        let lastHours   = 23;

        if (Number(yearVal) === nowYear) {
            lastMonth = nowMonth;
            if (Number(monthVal) >= nowMonth) {
                monthVal = nowMonth;
                lastDate = nowDate;
                if (Number(dateVal) >= nowDate) {
                    dateVal = nowDate;
                    lastHours = nowHours;
                    if (Number(hoursVal) >= nowHours) {
                        hoursVal = nowHours;
                    }
                }
            }
        }

        const monthOption = getOption(1, lastMonth, monthVal);
        const dateOption  = getOption(1, lastDate, dateVal);
        const hourOption  = getOption(1, lastHours, hoursVal);
        month.html(monthOption);
        date.html(dateOption);
        hours.html(hourOption);
    }

    /**
     * 통계 조회 별 날짜 검색 막기
     */
    function searchTypeChanged() {
        const searchVal = searchType.val();
        switch (searchVal) {
            case 'sTime':
                beginMonth.attr('disabled', false);
                beginDate.attr('disabled', false);
                beginHours.attr('disabled', false);
                endMonth.attr('disabled', false);
                endDate.attr('disabled', false);
                endHours.attr('disabled', false);
                break;
            case 'sDay':
                beginMonth.attr('disabled', false);
                endMonth.attr('disabled', false);
                endDate.attr('disabled', false);
                beginDate.attr('disabled', false);
                beginHours.attr('disabled', true);
                endHours.attr('disabled', true);
                break;
            case 'sMonth':
                beginMonth.attr('disabled', false);
                endMonth.attr('disabled', false);
                endDate.attr('disabled', true);
                beginDate.attr('disabled', true);
                beginHours.attr('disabled', true);
                endHours.attr('disabled', true);
                break;
            case 'sYear':
                beginMonth.attr('disabled', true);
                endMonth.attr('disabled', true);
                endDate.attr('disabled', true);
                beginDate.attr('disabled', true);
                beginHours.attr('disabled', true);
                endHours.attr('disabled', true);
                break;
        }
    }

    function excelDown(){
        if (_excelData.length === 0) {
            return alert('조회된 소통정보가 없습니다.');
        }
        exportExcel();
    }

    const excelHandler = {
        getExcelFileName : function() {
            return _searchAtrdName + '-' + _searchAtrdType + '_' + nowTime() + '.xlsx'; // 테이블이름
        },
        getSheetName : function() {
            return _searchAtrdName; // 엑셀 하단 시트 이름
        },
        getExcelData : function() { // EXCEL로 변환하고자 하는 테이블 선택
            return _excelData;
        },
        getWorksheet : function() {
            return XLSX.utils.json_to_sheet(this.getExcelData());
        }
    }

    function s2ab(s) {
        const buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
        const view = new Uint8Array(buf);  //create uint8array as viewer
        for (let ii=0; ii < s.length; ii++) view[ii] = s.charCodeAt(ii) & 0xFF; //convert to octet
        return buf;
    }

    function exportExcel() {
        const wb = XLSX.utils.book_new(); // step 1. workbook 생성
        const newWorksheet = excelHandler.getWorksheet(); // step 2. 시트 만들기
        XLSX.utils.book_append_sheet(wb, newWorksheet, excelHandler.getSheetName()); // step 3. workbook에 새로만든 워크시트에 이름을 주고 붙인다.
        const wbout = XLSX.write(wb, {bookType:'xlsx',  type: 'binary'}); // step 4. 엑셀 파일 만들기
        saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), excelHandler.getExcelFileName()); // step 5. 엑셀 파일 내보내기
    }

    function nowTime() {
        let now = new Date();
        let year = now.getFullYear().toString();
        let month = timeFormatter(now.getMonth() + 1).toString();
        let date = timeFormatter(now.getDate()).toString();
        let hour = timeFormatter(now.getHours()).toString();
        let minutes = timeFormatter(now.getMinutes()).toString();
        let seconds = timeFormatter(now.getSeconds()).toString();
        return year + month + date + hour + minutes + seconds;
    }

    //시간 한자리 경우 2자리로 세팅
    function timeFormatter(time) {
        let result = time < 10 ? "0" + time.toString() : time.toString();
        return result;
    }

    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 atrdNameVal   = atrdName.val();
        const searchTypeVal = searchType.val();
        if (atrdNameVal === null || atrdNameVal === '' || atrdNameVal === undefined) {
            alert('도로목록을 선택해주세요');
            return atrdName.focus();
        }
        const beginYearVal  = beginYear.val();
        const beginMonthVal = beginMonth.val();
        const beginDateVal  = beginDate.val();
        const beginHoursVal = beginHours.val();
        const endYearVal    = endYear.val();
        const endMonthVal   = endMonth.val();
        const endDateVal    = endDate.val();
        const endHoursVal   = endHours.val();

        let beginSearchDate = beginYearVal + beginMonthVal + beginDateVal + beginHoursVal;
        let endSearchDate   = endYearVal + endMonthVal + endDateVal + endHoursVal;

        switch (searchTypeVal) {
            case 'sTime' :
                beginSearchDate += '0000';
                endSearchDate += '0000';
                break;
            case 'sDay' :
                beginSearchDate = beginSearchDate.substr(0, 8) + '000000';
                endSearchDate   = endSearchDate.substr(0, 8) + '235959';
                break;
            case 'sMonth' :
                beginSearchDate = beginSearchDate.substr(0, 6) + '01000000';
                const lastDate  = new Date(endYearVal, endMonthVal, 0).getDate()
                endSearchDate   = endSearchDate.substr(0, 6) + lastDate + '235959';
                break;
            case 'sYear' :
                beginSearchDate = beginYearVal + '0101000000';
                endSearchDate   = endYearVal   + '1231235959';
                break;
        }

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

        $.ajax({
            type : 'POST',
            url  : '/trafficStats/getVertexHistoryText.do',
            data : {
                atrdName   : atrdNameVal,
                begin      : beginSearchDate,
                end        : endSearchDate,
                searchType : searchTypeVal,
            },
            success: function(data){
                const cnt = data.length.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
                alert("데이터 " + cnt + "건이 조회되었습니다.");
                let str = '';
                _excelData = [];

                if (data.length == 0) {
                    str += noDataText;
                }
                else {
                    data.forEach((obj)=>{
                        str +=`<li>
                                    <div class="roadName">
                                        <span class="small-title">도로명&nbsp;:&nbsp;</span>\${obj.ROAD_NM}
                                    </div>
                                    <div class="roadDetail">
                                        <span class="small-title">구간명 :</span>
                                        <span>\${obj.STRT_NM}</span>
                                        <span class="arrow">화살표</span>
                                        <span>\${obj.END_NM}</span>
                                    </div>
                                    <div class="time">
                                        <span class="small-title">통계시각&nbsp;:&nbsp;</span>\${obj.STAT_DT}
                                    </div>
                                    <div class="speed">
                                        <span class="small-title">속도&nbsp;:&nbsp;</span>\${obj.SPED} km/h
                                    </div>
                                    <div class="min">
                                        <span class="small-title">통행시간&nbsp;:&nbsp;</span>\${obj.TRVL_HH} sec
                                    </div>
                                </li>`;
                        _excelData.push({
                            도로명   : obj.ROAD_NM,
                            구간명   : obj.STRT_NM + ' -> ' + obj.END_NM,
                            통계시각 : obj.STAT_DT,
                            속도     : obj.SPED + ' km/h',
                            통행시간 : obj.TRVL_HH + ' sec'
                        })
                    });
                    _searchAtrdType = $('#sTimeType option:checked').text();
                    _searchAtrdName = atrdNameVal;
                }
                trafficList.html(str);
            },
            beforeSend : function(){
                $('#loading').css('display', 'flex');
                btnActiveState(true);
            },
            complete : function(){
                $('#loading').css('display', 'none');
                btnActiveState(false);
            },
            error : function() {
                alert('교통량 통계 조회 중 오류가 발생하였습니다.');
            }
        });

    }

    function getOption(start, rate, dateValue) {
        if (rate < dateValue) {
            dateValue = rate;
        }

        let option = ''
        for ( let ii = start; ii <= rate; ii++) {
            let value = ii;
            if (ii < 10) {
                value = ('0'+ii);
            }
            if (Number(dateValue) === ii) {
                option += '<option value="'+value+'" selected>'+value +'</option>';
            }
            else{
                option += '<option value="'+value+'">'+value +'</option>';
            }
        }

        return option;
    }

</script>