/****************************************************************************
 * 로그 히스토리 목록 - Tabulator Grid
 ****************************************************************************/

let logHistoryTable;
let currentPage = 1;
let pageSize = 50;

/****************************************************************************
 * 초기화
 ****************************************************************************/
$(document).ready(function () {
    fn_initTable();
    fn_initEvent();
    fn_setDefaultDate();
    fn_selectLogHistoryList(1);
});

/****************************************************************************
 * 기본 날짜 설정 (오늘 기준 7일 전 ~ 오늘)
 ****************************************************************************/
function fn_setDefaultDate() {
    let today = new Date();
    let weekAgo = new Date();
    weekAgo.setDate(today.getDate() - 7);

    $("#searchEndDate").val(fn_formatDate(today));
    $("#searchStartDate").val(fn_formatDate(weekAgo));
}

function fn_formatDate(date) {
    let y = date.getFullYear();
    let m = String(date.getMonth() + 1).padStart(2, "0");
    let d = String(date.getDate()).padStart(2, "0");
    return y + "-" + m + "-" + d;
}

/****************************************************************************
 * Tabulator 초기화
 ****************************************************************************/
function fn_initTable() {
    logHistoryTable = new Tabulator("#logHistoryGrid", {
        height: "calc(100vh - 350px)",
        layout: "fitColumns",
        placeholder: "조회된 데이터가 없습니다.",
        columns: [
            {
                title: "No",
                field: "rowNum",
                hozAlign: "center",
                headerHozAlign: "center",
                width: 60,
                headerSort: false
            },
            {
                title: "날짜",
                field: "writeDate",
                hozAlign: "center",
                headerHozAlign: "center",
                width: 110
            },
            {
                title: "시간",
                field: "writeTime",
                hozAlign: "center",
                headerHozAlign: "center",
                width: 90
            },
            {
                title: "기능명",
                field: "funcName",
                headerHozAlign: "center",
                minWidth: 160
            },
            {
                title: "서비스명",
                field: "serviceName",
                headerHozAlign: "center",
                minWidth: 160
            },
            {
                title: "URL",
                field: "url",
                headerHozAlign: "center",
                minWidth: 200
            },
            {
                title: "결과",
                field: "resultCode",
                hozAlign: "center",
                headerHozAlign: "center",
                width: 90,
                formatter: function (cell) {
                    let val = cell.getValue();
                    if (val === "SUCCESS") {
                        return '<span class="result-success">SUCCESS</span>';
                    } else if (val === "ERROR") {
                        return '<span class="result-error">ERROR</span>';
                    }
                    return val || "";
                }
            },
            {
                title: "사용자ID",
                field: "muMemberId",
                hozAlign: "center",
                headerHozAlign: "center",
                width: 100
            },
            {
                title: "접속IP",
                field: "visitIp",
                hozAlign: "center",
                headerHozAlign: "center",
                width: 130
            }
        ]
    });
}

/****************************************************************************
 * 이벤트 바인딩
 ****************************************************************************/
function fn_initEvent() {
    // 조회 버튼
    $("#btnSearch").on("click", function () {
        fn_selectLogHistoryList(1);
    });

    // Enter 키 검색
    $("#searchKeyword").on("keyup", function (e) {
        if (e.keyCode === 13) {
            fn_selectLogHistoryList(1);
        }
    });
}

/****************************************************************************
 * 로그 히스토리 목록 조회
 ****************************************************************************/
function fn_selectLogHistoryList(page) {
    currentPage = page;
    let start = (page - 1) * pageSize;

    let paramData = {
        "menuClass": menuClass,
        "start": start,
        "limit": pageSize,
        "searchKeyword": $("#searchKeyword").val(),
        "resultCode": $("#searchResultCode").val(),
        "startDate": $("#searchStartDate").val(),
        "endDate": $("#searchEndDate").val()
    };

    $.ajax({
        url: encodeURI("/logHistory/getLogHistoryList.do"),
        data: JSON.stringify(paramData),
        dataType: "json",
        contentType: "application/json",
        type: "POST",
        async: true,
        success: function (data) {
            if ("0" == data.msgCode) {
                let totalCount = data.totalCount || 0;
                $("#totalCount").text(totalCount.toLocaleString());

                if (data.rows && data.rows.length > 0) {
                    logHistoryTable.setData(data.rows);
                } else {
                    logHistoryTable.setData([]);
                }

                fn_setPagination(totalCount);
            } else {
                alert(data.msgDesc || "조회 중 오류가 발생하였습니다.");
            }
        },
        error: function () {
            alert("서버 통신 오류가 발생하였습니다.");
        }
    });
}

/****************************************************************************
 * 페이지네이션
 ****************************************************************************/
function fn_setPagination(totalCount) {
    let totalPages = Math.ceil(totalCount / pageSize);
    if (totalPages < 1) totalPages = 1;

    $("#logHistoryPagination").twbsPagination("destroy");
    $("#logHistoryPagination").twbsPagination({
        totalPages: totalPages,
        startPage: currentPage,
        visiblePages: 10,
        initiateStartPageClick: false,
        first: "<<",
        prev: "<",
        next: ">",
        last: ">>",
        onPageClick: function (event, page) {
            fn_selectLogHistoryList(page);
        }
    });
}
