const emptyStr = `<tr>
                    <td><span class="empty-content">조회 된 항목이 없습니다.</span></td>
                  </tr>`;

let _date, _atrdNm, _statStr, _type;

$(()=>{
    init();
    _statStr = $('.menu > div.active').text();
})

function init () {
    const $year   = $('.year');
    const $month  = $('.month');
    const $date   = $('.date');
    const $type   = $('.type');
    const $amBtn  = $('.button.amount');
    const $comBtn = $('.button.comm');
    const $conBtn = $('.button.congest');
    const $toggle = $('.table-toggle');

    const now      = new Date();
    const nowYear  = now.getFullYear();
    const nowMonth = now.getMonth() + 1;
    const nowDate  = now.getDate();

    $amBtn.on('click', () => searchStatisticsAmount());
    $comBtn.on('click', ()=> searchStatisticsComm());
    $conBtn.on('click', ()=> searchStatisticsCongest());

    $type.on('change', function(){
        const isDisabled = !($(this).val() === 'dd');
        $date.attr('disabled', isDisabled);
        const opacity = isDisabled ? 0 : 1;
        $date.css('opacity', opacity);
    })

    if ($year[0]) {
        let options = getDateOptions(2022, nowYear, '년');
        $year.html(options);
        $year.val(nowYear);
        $year.on('change', function() {
            const value = $(this).val();
            let lastMonth = 12;
            if (Number(value) === nowYear) {
                lastMonth = nowMonth;
            }

            if ($month[0]) {
                const monthOptions = getDateOptions(1, lastMonth, '월');
                const monthVal = $month.val();
                $month.html(monthOptions);

                if (Number(monthVal) > lastMonth) {
                    $month.val(1);
                    if ($date[0]) {
                        $date.val(1);
                    }
                }
                else {
                    $month.val(monthVal);
                }

                if (Number(monthVal) === nowMonth) {
                    const dateOptions = getDateOptions(1, nowDate, '일');
                    $date.html(dateOptions);
                    const dateVal = $date.val();
                    if (Number(dateVal) > nowDate) {
                        $date.val(1);
                    }
                }
            }
        })
    }

    if ($month[0]) {
        let options = getDateOptions(1, nowMonth, '월');
        $month.html(options);
        $month.val(nowMonth);
        $month.on('change', function() {
            const yearVal = $year.val();
            const monthVal = $(this).val();
            if ($date[0]) {
                const dateVal = $date.val();
                let lastDate = new Date(yearVal, monthVal, 0).getDate();

                if (Number(yearVal) === nowYear && Number(monthVal) === nowMonth) {
                    lastDate = nowDate;
                }

                const dateOptions = getDateOptions(1, lastDate, '일');
                $date.html(dateOptions);

                if (Number(dateVal) > nowDate) {
                    $date.val(1);
                }
                else {
                    $date.val(dateVal);
                }
            }
        })
    }

    if ($date[0]) {
        let options = getDateOptions(1, nowDate, '일');
        $date.html(options);
        $date.val(nowDate);
    }

    if ($toggle[0]) {
        $toggle.children().on('click', function() {
            const isActive = $(this).hasClass("active");
            if (isActive) return;
            $('.table-toggle .active').removeClass("active");
            $(this).addClass("active");
        })
    }

}

/**
 * Select 날짜 옵션값 생성
 * @param start 시작값
 * @param limit 종료값
 * @param word 구분 글자
 * @returns {string} option 문자
 */
function getDateOptions(start, limit, word) {
    if (isNaN(start) || isNaN(limit) || !word) {
        return;
    }
    else if (start > limit) {
        return;
    }

    let options = '';
    for (let ii = start; ii <= limit; ii++) {
        options += `<option value="${ii}">${ii} ${word}</option>`
    }
    return options;
}

/**
 * 교통량 통계 조회
 */
function searchStatisticsAmount() {
    const $roadNmbr = $('.road_nmbr');
    const $type     = $('.type');
    const $year     = $('.year');
    const $month    = $('.month');
    const $date     = $('.date');
    const $thead    = $('.thead');
    const $tbody    = $('.table-content');
    const $table    = $('.table-box table')
    const type      = $type.val();
    const roadNmbr  = $roadNmbr.val();
    const year      = Number($year.val());
    const month     = Number($month.val());
    const date      = Number($date.val());

    let fromDt = "";
    let toDt   = "";
    let limit  = 23;
    let start  = 0;
    const dateValue = getSearchDateValue(year, month, date);
    fromDt = dateValue + '000000';
    toDt   = dateValue + '235959';
    if (type === 'mn') {
        _date =
        fromDt = getSearchDateValue(year, month, 1) + '000000';
        toDt = getSearchDateValue(year, month, new Date(year, month, 0).getDate()) + '235959';
        limit = new Date(year, month, 0).getDate();
        start = 1;
    }

    const param = {
        roadNmbr : roadNmbr,
        fromDt   : fromDt,
        toDt     : toDt,
    }

    let height = '100%';
    $table.css('height', height);
    $tbody.html('<tr><td><span><img src="/images/icon/loading.gif"></span></td></tr>');
    let str = emptyStr;
    let thead = "";
    if (limit) {
        thead = '<tr><th>구간</th>';
        for (let ii = start; ii <= limit; ii++) {
            thead += '<th>'+ii+'</th>';
        }
        thead += '</tr>';
    }
    getDataAsync('/api/statistics/amount/' + type, "POST", param, null, (jsonData)=>{
        if (jsonData && jsonData.length > 0) {
            _atrdNm = $(".road_nmbr option:checked").text();
            _type   = $('.type option:checked').text();
            _date   = dateValue;
            if (type === "mn") _date = dateValue.substring(0,6);
            str = "";
            jsonData.forEach((obj)=>{
                const { strt_name, end_name } = obj;

                str +=`<tr>
                        <td>${strt_name} -> ${end_name}</td>`
                for (let ii = start; ii <= limit; ii++) {
                    let value = ii;
                    if (value < 10) value = "0" + ii;
                    value = obj['t' + value];
                    if (value === '0' || !value) value = '-';
                    str += `<td>${value}</td>`
                }
                str += `</tr>`
            });
            height = 'auto';
            $table.css('height', height);
        }
        $thead.html(thead);
        $tbody.html(str);

    }, (err)=>{
        sendErrorMsg(err);
        $thead.html(thead);
        $tbody.html(emptyStr);
    });
}

/**
 * 소통 통계 조회
 */
function searchStatisticsComm() {
    const $atrdNm   = $('.atrd_nm');
    const $type     = $('.type');
    const $year     = $('.year');
    const $month    = $('.month');
    const $date     = $('.date');
    const $thead    = $('.thead');
    const $tbody    = $('.table-content');
    const $table    = $('.table-box table');
    const $active   = $('.table-toggle .active');
    const active    = $active.text();
    const type      = $type.val();
    const atrdNm    = $atrdNm.val();
    const year      = Number($year.val());
    const month     = Number($month.val());
    const date      = Number($date.val());


    let fromDt = "";
    let toDt   = "";
    let limit  = 23;
    let start  = 0;
    const dateValue = getSearchDateValue(year, month, date);
    fromDt = dateValue + '000000';
    toDt   = dateValue + '235959';

    if (type === 'mn') {
        fromDt = getSearchDateValue(year, month, 1) + '000000';
        toDt = getSearchDateValue(year, month, new Date(year, month, 0).getDate()) + '235959';
        limit = new Date(year, month, 0).getDate();
        start = 1;
    }

    const param = {
        atrdNm   : atrdNm,
        fromDt   : fromDt,
        toDt     : toDt,
    }

    let height = '100%';
    let url = "/speed";
    $table.css('height', height);
    $tbody.html('<tr><td><span><img src="/images/icon/loading.gif"></span></td></tr>');
    if (active === '지/정체통계') url = '/grade';

    let thead = "";
    if (limit) {
        thead = '<tr><th>구간</th>';
        for (let ii = start; ii <= limit; ii++) {
            thead += '<th>'+ii+'</th>';
        }
        thead += '</tr>';
    }
    getDataAsync('/api/statistics' + url + '/' + type, "POST", param, null, (jsonData)=>{
        let str = emptyStr;

        if (jsonData && jsonData.length > 0) {
            str = "";
            _atrdNm = $(".atrd_nm option:checked").text();
            _type   = $('.type option:checked').text();
            _date   = dateValue;
            if (type === "mn") _date = dateValue.substring(0,6);
            jsonData.forEach((obj)=>{
                const { strt_name, end_name } = obj;

                str +=`<tr>
                        <td>${strt_name} -> ${end_name}</td>`
                for (let ii = start; ii <= limit; ii++) {
                    let value = ii;
                    if (value < 10) value = "0" + ii;
                    value = obj['t' + value];
                    if (url === '/grade') {
                        let text = "●";
                        if (!value) {
                            text = "○";
                        }
                        str += '<td class="LTC'+ value+'">' + text + '</td>'
                    }
                    else {
                        if (value === '0' || !value) value = '-';
                        str += `<td>${value}</td>`
                    }
                }
                str += `</tr>`
            });
            height = 'auto';
            $table.css('height', height);
        }

        $thead.html(thead);
        $tbody.html(str);

    }, (err)=>{
        // console.log(err);
        sendErrorMsg(err);
        $thead.html(thead);
        $tbody.html(emptyStr);
    });
}

/**
 * 정체 통계 조회
 */
function searchStatisticsCongest() {
    const $type     = $('.type');
    const $day      = $('.day');
    const $tbody    = $('.table-content');
    const $table    = $('.table-box table');
    const type      = $type.val();
    const day       = $day.val();
    const agoDate   = new Date(new Date().setMonth(new Date().getMonth() - Number(type)));
    let year        = agoDate.getFullYear().toString();
    let month       = (agoDate.getMonth() + 1);

    if (month < 10) {
        month = "0" + month;
    }
    const statYm    = year + month;

    const param = {
        statYm   : statYm,
        day      : day,
    }

    let height = '100%';
    $table.css('height', height);
    $tbody.html('<tr><td><span><img src="/images/icon/loading.gif"></span></td></tr>');


    getDataAsync('/api/statistics/congest' , "POST", param, null, (jsonData)=>{
        let str = emptyStr;

        if (jsonData && jsonData.length > 0) {
            _atrdNm = null;
            _type   = $('.type option:checked').text();
            _date   = nowTime();
            if (type === "mn") _date = dateValue.substring(0,6);
            str = "";
            jsonData.forEach((obj)=>{
                const { road_nm, strt_nm, end_nm, strt_tm, end_tm, sped, crtn_ymd} = obj;

                str += `<tr>
                            <td>${road_nm}</td>
                            <td>${strt_nm}</td>
                            <td>${end_nm}</td>
                            <td>${crtn_ymd}</td>
                            <td>${strt_tm}</td>
                            <td>${end_tm}</td>
                            <td>${sped} km</td>
                        </tr>`
            });
            height = 'auto';
            $table.css('height', height);
        }
        $tbody.html(str);
    }, (err)=>{
        sendErrorMsg(err);
        $tbody.html(emptyStr);
    });
}

/**
 * 조회 날짜 값 포맷
 * @param year 년도
 * @param month 월
 * @param date 일
 * @returns {*} 포맷 문자
 */
function getSearchDateValue(year, month, date) {
    if (!year || !month || !date) {
        return;
    }
    if (isNaN(year) || isNaN(month) || isNaN(date)) {
        return;
    }

    year = year.toString();
    month = (month < 10 ? ('0'+ month) : month);
    date = (date < 10 ? ('0'+ date) : date);
    return  year + month + date;
}


function excelDown(){
    if ($('.empty-content')[0]) {
        return alertError('조회 된 항목이 없습니다.', 'Excel 다운로드');
    }
    exportExcel();
}
const excelHandler = {
    getExcelFileName : function() {
        let front = "";
        if (_atrdNm) {
            front = _atrdNm + ' - ';
        }
        return  front + _statStr + '('+ _type +')' + '_' + _date + '.xlsx'; // 테이블이름
    },
    getSheetName : function() {
        return _statStr; // 엑셀 하단 시트 이름
    },
    getExcelData : function() { // EXCEL로 변환하고자 하는 테이블 선택
        return document.getElementById('table');
    },
    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 nowTime() {
    let now = new Date();
    return getSearchDateValue(now.getFullYear(), now.getMonth() + 1, now.getDate());
}