<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>지역센터 제공/수집정보 이력</title>
    <link rel="stylesheet" href="/static/css/reset.css">
    <link rel="stylesheet" href="/static/css/common.css">
    <link rel="stylesheet" href="/static/css/rcv-send-center-statistics.css">
    <script src="/static/js/jquery-1.10.2.min.js"></script>
    <script src="/static/js/common.js"></script>
</head>
<body>
    <div class="wrap">
        <div class="top-bar">지역센터 제공/수집정보 이력</div>
        <div class="body-wrap">
            <div class="title">검색조건</div>
            <div class="container">
                <div>
                    <div>지역센터</div>
                    <select id="center-id" name="center-id">
                        <option th:each="item : ${centerInfo}" th:value="${item.centerId}" th:text="${item.centerInfo}"></option>
                    </select>
                </div>
                <div>
                    <div>조회일</div>
                    <input th:value="${#temporals.format(#temporals.createNow(), 'yyyy-MM-dd')}"
                           th:max="${#temporals.format(#temporals.createNow(), 'yyyy-MM-dd')}" type="date" id="search-dt" name="search-dt">
                </div>
                <div class="button-box">
                    <div class="button search" onclick="getPeriodCenterHistory()"><img src="/static/image/search.svg">조회</div>
                </div>
            </div>
            <div class="container-2">
                <div class="title">지역센터 제공/수집정보 이력</div>
                <div class="content">
                    <div>
                        <table>
                            <colgroup>
                                <col width="18px">
                                <col width="calc(18% - 18px)">
                                <col width="16%">
                                <col width="16%">
                                <col width="16%">
                                <col width="16%">
                                <col width="16%">
                            </colgroup>
                            <thead>
                                <tr>
                                    <th></th>
                                    <th>일시</th>
                                    <th>소통정보 수신</th>
                                    <th>돌발정보 수신</th>
                                    <th>소통정보 송신</th>
                                    <th>돌발정보 송신</th>
                                    <th>민간교통정보 송신</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                            <tfoot></tfoot>
                        </table>
                    </div>
                </div>
                <div class="pagination">
                    <div class="prev unactive">«</div>
                    <div class="active">1</div>
                    <div class="next unactive">»</div>
                </div>
                <div class="loading"><img src="/static/image/loading.gif" alt="로딩 이미지"></div>
            </div>
            <div class="bottom-box" onclick="download()">
                <div class="button"><img src="/static/image/download.svg">저장</div>
            </div>
        </div>
    </div>
</body>
</html>
<script>
   const searchDt = $('#search-dt');
   const centerId = $('#center-id');
   let _centerId  = null;
   let _searchDt  = null;
   const tfooter  = $('tfoot');
   const tbody    = $('tbody');
   let _searchedData = [];
    function timeFormatter(value) {
        return String(value).padStart(2, '0');
    }

    function getPeriodCenterHistory() {
        const searchDtVal = searchDt.val();
        const centerIdVal = centerId.val();
        if (!searchDtVal) {
            alert("조회일을 선택해주세요.");
            return false;
        }

        if (!centerIdVal) {
            alert("지역센터를 선택해주세요.");
            return false;
        }

        if (new Date(centerIdVal) > new Date()) {
            alert("현재 날짜 이후로는 검색 할 수 없습니다.");
            return false;
        }

        _centerId = centerIdVal;
        _searchDt = searchDtVal;
        const params = {centerId : centerIdVal, searchDt : searchDtVal};
        callApi("/api/statistics/getPeriodCenterRcvSendStatistics", 'POST', params, callBackPeriodCenterHistory, errCallBack, 'container-2');
    }

    function callBackPeriodCenterHistory(data) {
        let str = "";
        let cnt = '-';
        tfooter.empty();
        _searchedData = data;
        if (data && data.length) {
            cnt = data.length.toLocaleString();
            let rTCntTot = 0;
            let rICntTot = 0;
            let sTCntTot = 0;
            let sICntTot = 0;
            let sMCntTot = 0;

            data.forEach((obj, idx)=>{
                let rTCnt = Number(obj.rtcnt) || 0;
                let rICnt = Number(obj.ricnt) || 0;
                let sTCnt = Number(obj.stcnt) || 0;
                let sICnt = Number(obj.sicnt) || 0;
                let sMCnt = Number(obj.smcnt) || 0;
                rTCntTot += rTCnt;
                rICntTot += rICnt;
                sTCntTot += sTCnt;
                sICntTot += sICnt;
                sMCntTot += sMCnt;
            });
            tfooter.html(`<tr>
                             <td></td>
                             <td>합계</td>
                             <td>${rTCntTot.toLocaleString()}</td>
                             <td>${rICntTot.toLocaleString()}</td>
                             <td>${sTCntTot.toLocaleString()}</td>
                             <td>${sICntTot.toLocaleString()}</td>
                             <td>${sMCntTot.toLocaleString()}</td>
                           </tr>`);
            const lastPage = getLastPage();
            let end = 10;
            end = lastPage > end ? end : lastPage
            makePageStr(false, lastPage > 10, 1, end, 1, drawTable);
        }
        else {
            makePageStr(false, false, 1, 1, 1, drawTable);
        }
        $('.data-cnt').text(cnt);
    }
    function drawTable(data) {
        if (!data || !data.length) return tbody.html(`<tr><td></td><td colspan="8" class="empty-box">표출 정보 없음</td></tr>`);
        let str = '';
        data.forEach((obj, idx)=>{
            let rTCnt = Number(obj.rtcnt) || 0;
            let rICnt = Number(obj.ricnt) || 0;
            let sTCnt = Number(obj.stcnt) || 0;
            let sICnt = Number(obj.sicnt) || 0;
            let sMCnt = Number(obj.smcnt) || 0;

            str += `<tr onclick="rowClick(this, 'container-2 table tbody')" >
                    <td><input style="display: none" type="checkbox" id="check_${idx}" onchange="checkEvent(this, 'container-2 table tbody')"></td>
                    <td>${obj.logDate}</td>
                    <td>${rTCnt.toLocaleString()}</td>
                    <td>${rICnt.toLocaleString()}</td>
                    <td>${sTCnt.toLocaleString()}</td>
                    <td>${sICnt.toLocaleString()}</td>
                    <td>${sMCnt.toLocaleString()}</td>
                </tr>`;
        });
        tbody.html(str);
    }

    function errCallBack(error)  {
        alert('도로공사 돌발정보 수집 이력 조회 중 오류가 발생하였습니다.');
        let str = `<tr><td></td><td colspan="6" class="empty-box">표출 정보 없음</td></tr>`;
        $('.data-cnt').text('-');
        tbody.html(str);
    }

    function rowClick(el, tbody) {
        $('.' + tbody).find('tr input[type="checkbox"]:checked').prop('checked', false);
        const check = $(el).children().eq(0).find('input[type="checkbox"]');
        check.prop('checked', true).trigger('change');
    }

    function download() {
        if (!_centerId || !_searchDt || $('.empty-box').length || !tbody.length) {
            return alert("검색된 데이터 정보를 찾을 수 없습니다.");
        }
        if (!new Date(_searchDt).getTime()) {
            return alert("날짜 형식이 잘못되었습니다.");
        }

        const sheetName = '지역센터 제공-수집정보 이력';
        const params = {searchDt : _searchDt, centerId : _centerId, sheetName : sheetName};
        fetch('/api/report/center/download', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(params)
        })
        .then(res => {
            if (!res.ok) {
                // 서버 응답이 실패 상태인 경우
                return res.text().then(errorMessage => {
                    throw new Error(errorMessage || `HTTP error! status: ${res.status}`);
                });
            }
            return res.blob();
        })
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = sheetName + '_' + getNowStr() + '.xlsx';
            a.click();
        })
        .catch(error => {
            console.log(error);
        });
    }

    function getNowStr() {
        const now  = new Date();
        const yyyy = now.getFullYear();
        const MM   = String(now.getMonth() + 1).padStart(2, '0');
        const dd   = String(now.getDate()).padStart(2, '0');
        const hh   = String(now.getHours()).padStart(2, '0');
        const mm   = String(now.getMinutes()).padStart(2, '0');
        const ss   = String(now.getSeconds()).padStart(2, '0');
        return yyyy + MM + dd + hh + mm + ss;
    }
</script>