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

<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="linkId" id="linkId" control-id="ControlID-3">
                                <option value="">검지기 목록</option>
                                <c:forEach var="item" items="${vdsCtlrList}" varStatus="status">
                                    <option value="${item.LINK_ID}">${item.STR_NAME} -> ${item.END_NAME}</option>
                                </c:forEach>
                            </select>
                            <label for="linkId"></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>
                                일
                                <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>
                                일
                            </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-stat-list-wrap">
                <ul class="traffic-stat-list">
                    <div style="height: 40px; display: flex; align-items: center;">
                        <span style="font-size: 32px;">교통량통계&nbsp;</span>
                        <span style="font-size: 24px; color: #004EA2;" class="vds-location-name"></span>
                        <span style="font-size: 24px; margin-left: 10px;">(단위:대)</span>
                    </div>
                    <br>
                    <li class="th">
                        <div class="sect">구분</div>
                        <div class="stats-time">00</div>
                        <div class="stats-time">01</div>
                        <div class="stats-time">02</div>
                        <div class="stats-time">03</div>
                        <div class="stats-time">04</div>
                        <div class="stats-time">05</div>
                        <div class="stats-time">06</div>
                        <div class="stats-time">07</div>
                        <div class="stats-time">08</div>
                        <div class="stats-time">09</div>
                        <div class="stats-time">10</div>
                        <div class="stats-time">11</div>
                        <div class="stats-time">12</div>
                        <div class="stats-time">13</div>
                        <div class="stats-time">14</div>
                        <div class="stats-time">15</div>
                        <div class="stats-time">16</div>
                        <div class="stats-time">17</div>
                        <div class="stats-time">18</div>
                        <div class="stats-time">19</div>
                        <div class="stats-time">20</div>
                        <div class="stats-time">21</div>
                        <div class="stats-time">22</div>
                        <div class="stats-time">23</div>
                        <div class="total">합계</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 = $('.traffic-stat-list > .tbody');
    const beginYear   = $('#begin-year');
    const beginDate   = $('#begin-date');
    const beginMonth  = $('#begin-month');
    const endYear     = $('#end-year');
    const endMonth    = $('#end-month');
    const endDate     = $('#end-date');
    const linkId      = $('#linkId');
    const vdsLctnName = $('.vds-location-name');
    let _excelData    = [];
    let _searchVdsName = '';
    let _searchStatisticsDate = '';

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

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

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

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

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

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


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

    const excelHandler = {
        getExcelFileName : function() {
            return _searchVdsName + '-' + _searchStatisticsDate + '_' + nowTime() + '.xlsx'; // 테이블이름
        },
        getSheetName : function() {
            return _searchVdsName; // 엑셀 하단 시트 이름
        },
        getExcelData : function() { // EXCEL로 변환하고자 하는 테이블 선택
            const table = createExcelTable(_excelData, _searchVdsName);
            return table[0];
        },
        getWorksheet : function() {
            return XLSX.utils.table_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 linkIdVal     = linkId.val();
        const vdsName       = $('#linkId option:selected').text();
        if (linkIdVal === null || linkIdVal === '' || linkIdVal === undefined) {
            alert('검지기 구간목록을 선택해주세요');
            return linkId.focus();
        }
        const beginYearVal  = beginYear.val();
        const beginMonthVal = beginMonth.val();
        const beginDateVal  = beginDate.val();
        const endYearVal    = endYear.val();
        const endMonthVal   = endMonth.val();
        const endDateVal    = endDate.val();

        let beginSearchDate = beginYearVal + beginMonthVal + beginDateVal + '000000';
        let endSearchDate   = endYearVal + endMonthVal + endDateVal + '235959';

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

        $.ajax({
            type : 'POST',
            url  : '/trafficStats/getVdsStatsInfo.do',
            data : {
                linkId        : linkIdVal,
                statsStrtDate : beginSearchDate,
                statsEndDate  : endSearchDate,
            },
            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 {
                    vdsLctnName.text("[" + vdsName + "]");
                    data.forEach((obj)=>{
                        str +=`<li>
                                    <div class="sect">
                                        \${obj.stat_dd} \${vdsName}
                                    </div>`;
                            for (let ii = 0; ii < obj.tfvlArr.length; ii++) {
                                let statValue = thousandFormatter(obj.tfvlArr[ii]);
                                str += `<div class="stats-time">
                                           \${statValue}
                                        </div>`;
                            }
                            str += `<div class="total">
                                        \${thousandFormatter(obj.tfvlSum)}
                                    </div>
                                </li>`;
                    });
                    // console.log(_excelData);
                    _searchStatisticsDate = beginSearchDate.substring(0,8) + '~' + endSearchDate.substring(0,8);
                    _searchVdsName = vdsName;
                    _excelData = [...data];
                    console.log(_excelData);
                }
                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;
    }

    function thousandFormatter(text) {
        if (text !== null && text !== undefined && text !== ""){
            return text.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",")
        }
        return '-';
    }

    function createExcelTable(jsonData, vdsName) {
        if (jsonData && jsonData.length > 0) {

        let table=
            `<table>
                <thead>
                    <tr>
                        <th>구분</th>
                        <th>00</th>
                        <th>01</th>
                        <th>02</th>
                        <th>03</th>
                        <th>04</th>
                        <th>05</th>
                        <th>06</th>
                        <th>07</th>
                        <th>08</th>
                        <th>09</th>
                        <th>10</th>
                        <th>11</th>
                        <th>12</th>
                        <th>13</th>
                        <th>14</th>
                        <th>15</th>
                        <th>16</th>
                        <th>17</th>
                        <th>18</th>
                        <th>19</th>
                        <th>20</th>
                        <th>21</th>
                        <th>22</th>
                        <th>23</th>
                        <th>합계</th>
                    </tr>
                </thead>
                <tbody>`
                 jsonData.forEach((obj)=>{
                     table += '<tr><td>' + obj.stat_dd + ' ' + vdsName
                     obj.tfvlArr.forEach((traffic)=>{
                        table += '<td>' + thousandFormatter(traffic) + '</td>';
                     })
                     table += '<td>' + thousandFormatter(obj.tfvlSum) + '</td></tr>'
                 })
            table += `</tbody>
            </table>`;
            return $(table);
        }
    }
</script>