////////////////////////////////////////////////////////////////////////////////////////
//Page 전역 변수
////////////////////////////////////////////////////////////////////////////////////////
var indexStatusSumList ;
var indexStatusHistory ;
var indexStatusHistoryDetail ;
//Document Ready
////////////////////////////////////////////////////////////////////////////////////////
function execDocReady() {
    let pluginGroups = [
        [
            "../reference/light-blue/lib/vendor/jquery.ui.widget.js",
            "../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Templates_js_tmpl.js",
            "../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Load-Image_js_load-image.js",
            "../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Canvas-to-Blob_js_canvas-to-blob.js",
            "../reference/light-blue/lib/jquery.iframe-transport.js",
            "../reference/light-blue/lib/jquery.fileupload.js",
            "../reference/light-blue/lib/jquery.fileupload-fp.js",
            "../reference/light-blue/lib/jquery.fileupload-ui.js"
        ],

        [
            "../reference/jquery-plugins/select2-4.0.2/dist/css/select2_lightblue4.css",
            "../reference/jquery-plugins/lou-multi-select-0.9.12/css/multiselect-lightblue4.css",
            "../reference/jquery-plugins/multiple-select-1.5.2/dist/multiple-select-bluelight.css",
            "../reference/jquery-plugins/select2-4.0.2/dist/js/select2.min.js",
            "../reference/jquery-plugins/lou-multi-select-0.9.12/js/jquery.quicksearch.js",
            "../reference/jquery-plugins/lou-multi-select-0.9.12/js/jquery.multi-select.js",
            "../reference/jquery-plugins/multiple-select-1.5.2/dist/multiple-select.min.js"
        ],

        [
            "../reference/jquery-plugins/datetimepicker-2.5.20/build/jquery.datetimepicker.min.css",
            "../reference/light-blue/lib/bootstrap-datepicker.js",
            "../reference/jquery-plugins/datetimepicker-2.5.20/build/jquery.datetimepicker.full.min.js",
            "../reference/lightblue4/docs/lib/widgster/widgster.js",
            "../reference/lightblue4/docs/lib/slimScroll/jquery.slimscroll.min.js",
            "../reference/lightblue4/docs/lib/jquery.sparkline/index.js",
            "../reference/lightblue4/docs/js/charts.js"
        ],

        [
            "../reference/jquery-plugins/dataTables-1.10.16/media/css/jquery.dataTables_lightblue4.css",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Responsive/css/responsive.dataTables_lightblue4.css",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Select/css/select.dataTables_lightblue4.css",
            "../reference/jquery-plugins/dataTables-1.10.16/media/js/jquery.dataTables.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Responsive/js/dataTables.responsive.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Select/js/dataTables.select.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/RowGroup/js/dataTables.rowsGroup.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/dataTables.buttons.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/buttons.html5.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/buttons.print.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/jszip.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/pdfmake.min.js",
            "../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/vfs_fonts.js",
            "../reference/jquery-plugins/kevalbhatt-timezone-picker-2.0.0/dist/timezone-picker.min.js",
            "../reference/jquery-plugins/kevalbhatt-timezone-picker-2.0.0/dist/styles/timezone-picker.css"
        ]
        // 추가적인 플러그인 그룹들을 이곳에 추가하면 됩니다.
    ];

    loadPluginGroupsParallelAndSequential(pluginGroups)
        .then(function () {
            console.log("모든 플러그인 로드 완료");

            // 사이드 메뉴 색상 설정
            $(".widget").widgster();
            setSideMenu("sidebar_menu_config", "sidebar_menu_config_esIndex");
            
            // 상단 인덱스 문서 상황 정보
            getIndexStatusSumInfo();

            // 인덱스 작업 현황 내역
            getIndexStatusJobHistory();

            renderJobHistoryDetail();
            
            // merge 버튼 클릭 이벤트 추가
            eventMerge();


        })
        .catch(function (error) {
            console.error("플러그인 로드 중 오류 발생");
            console.log(error);
        });
}

// 데이터 테이블 열 클릭 이벤트
function dataTableClick(tempDataTable, selectedData) {
    let tableId = tempDataTable.context[0].sInstance;
    if (tableId === "indexStatusHistory") {
        dataLoadJobHistoryBySelected(selectedData);
    }
}
// 데이터 테이블 렌더링 후 콜백 함수
function dataTableCallBack(settings, json) {
    let table = $('#indexStatusHistory').DataTable();
    if (table.rows().count() === 0) {

    } else {
        table.row(0).select();
        var firstRow = table.row(0).node();
        $(firstRow).trigger('click');
        $(firstRow).addClass('selected');
    }
}

// 데이터 테이블 재그리기 후 콜백 함수
function dataTableDrawCallback(tableInfo) {
    console.log(tableInfo);
    $("#" + tableInfo.sInstance)
        .DataTable()
        .columns.adjust()
        .responsive.recalc();
}

function eventMerge(){
    $("#indexStatusSumList").on('click', '.alm-issue-merge-btn', function(event) {
        $.ajax({
            url: "/auth-sche/schedule/es-index/alm-issue/merge",
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            progress: false,
            statusCode: {
                200: function(data) {

                }
            }
        });
    });

    $("#indexStatusSumList").on('click', '.fluentd-merge-btn', function(event) {
        $.ajax({
            url: "/auth-sche/schedule/es-index/fluentd/merge",
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            progress: false,
            statusCode: {
                200: function(data) {

                }
            }
        });
    });
}

////////////////////////////////
//데이터 테이블 렌더링 & Ajax 호출 시작
////////////////////////////////
function getIndexStatusSumInfo() {
    let columnList = [
        {
            title: "인덱스 명",
            data: "indexName",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-center",
            visible: true
        },
        {
            title: "인덱스 개수",
            data: "indexCount",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-center",
            visible: true
        },
        {
            title: "문서 개수",
            data: "docsCount",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-center",
            visible: true
        },
        {
            title: "삭제 문서 개수",
            data: "docDeleted",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-center",
            visible: true
        },
        {
            name: "edit",
            title: "실행",
            data: null,
            render: function (data, type, row, meta) {
                if(data.indexName==="jiraissue"){
                    return `
                    <div style="text-align: center;">
                        <button  type="button" class="btn btn-success btn-sm alm-issue-merge-btn">
                            Merge
                        </button>
                    </div>`;
                }
                if(data.indexName==="fluentd"){
                    return `
                    <div style="text-align: center;">
                        <button  type="button" class="btn btn-success btn-sm fluentd-merge-btn">
                            Merge
                        </button>
                    </div>`;
                }

            },
            className: "dt-body-left",
            visible: true
        }
    ];

    let rowsGroupList = [];
    let columnDefList = [{
        "defaultContent": "<div style='color: #f8f8f8'>N/A</div>",
        "targets": "_all"
    }];
    let orderList = [];
    let jquerySelector = "#indexStatusSumList";


    let ajaxUrl = "/auth-user/api/arms/backoffice/es-index/sum-list";
    let jsonRoot = "response";
    let buttonList = [];
    let selectList = {};
    let isServerSide = false;

    // DataTable 생성
    indexStatusSumList = dataTable_build(
        jquerySelector,
        ajaxUrl,
        jsonRoot,
        columnList,
        rowsGroupList,
        columnDefList,
        selectList,
        orderList,
        buttonList,
        isServerSide
    );
}

function getIndexStatusJobHistory() {
    let columnList = [
        {
            title: "작업 아이디",
            data: "jobId",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-left",
            visible: true
        },
        {
            title: "인덱스 명",
            data: "indexAliasName",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-left",
            visible: true
        },
        {
            title: "작업 이전 인덱스 개수",
            data: "beforeIndexCount",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-center",
            visible: true
        },
        {
            title: "작업 이후 인덱스 개수",
            data: "afterIndexCount",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-center",
            visible: true
        },
        {
            title: "작업 시작 시간",
            data: "jobStartTime",
            render: function (data, type, row, meta) {
                let displayText = dateFormat(data);
                return data ? "<span style='color: #a4c6ff'>"+displayText+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-left",
            visible: true
        },
        {
            title: "작업 종료 시간",
            data: "jobEndTime",
            render: function (data, type, row, meta) {
                let displayText = dateFormat(data);
                return data ? "<span style='color: #a4c6ff'>"+displayText+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-left",
            visible: true
        }
    ];

    let rowsGroupList = [];
    let columnDefList = [{
        "defaultContent": "<div style='color: #f8f8f8'>N/A</div>",
        "targets": "_all"
    }];
    let orderList = [];
    let jquerySelector = "#indexStatusHistory";

    let ajaxUrl = "/auth-user/api/arms/backoffice/es-index/index-status/histories";
    let jsonRoot = "response";
    let buttonList = [];
    let selectList = {};
    let isServerSide = false;

    // DataTable 생성
    indexStatusHistory = dataTable_build(
      jquerySelector,
      ajaxUrl,
      jsonRoot,
      columnList,
      rowsGroupList,
      columnDefList,
      selectList,
      orderList,
      buttonList,
      isServerSide
    );

}

function dataLoadJobHistoryBySelected(selectedData){
    let table = $("#indexStatusHistoryDetail").DataTable();
    let jobHistories = selectedData["jobHistories"];

    const flattenedJobHistories = jobHistories.map(({ beforeIndexStatusVO = {}, afterIndexStatusVO = {} }) => {
        // 구조 분해 할당을 사용해 기본 값을 설정
        const { indexName: beforeIndexName = "N/A", docsCount: beforeDocsCount = 0, timestamp: beforeTimestamp = 0 } = beforeIndexStatusVO;
        const { indexName: afterIndexName = "N/A", docsCount: afterDocsCount = 0, timestamp: afterTimestamp = 0 } = afterIndexStatusVO;

        const finalBeforeIndexName = (beforeIndexName === "N/A") ? afterIndexName : beforeIndexName;

        return {
            finalBeforeIndexName,
            beforeDocsCount,
            beforeTimestamp,
            afterIndexName,
            afterDocsCount,
            afterTimestamp
        };
    });

    console.log(flattenedJobHistories);
    table.clear();
    table.rows.add(flattenedJobHistories);
    table.draw();
}


function renderJobHistoryDetail() {
    let columnList = [
        {
            title: "인덱스 명",
            data: "finalBeforeIndexName",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-left",
            visible: true
        },
        {
            title: "작업 이전 문서 개수",
            data: "beforeDocsCount",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-center",
            visible: true
        },
        {
            title: "작업 이후 문서 개수",
            data: "afterDocsCount",
            render: function (data, type, row, meta) {
                return data ? "<span style='color: #a4c6ff'>"+data+"</span>" : "<span style='color: #aaa'>N/A</span>";
            },
            className: "dt-body-center",
            visible: true
        }
    ];

    let rowsGroupList = [];
    let columnDefList = [{
        "defaultContent": "<div style='color: #f8f8f8'>N/A</div>",
        "targets": "_all"
    }];
    let orderList = [];
    let jquerySelector = "#indexStatusHistoryDetail";

    let ajaxUrl = "";
    let jsonRoot = "response";
    let buttonList = [];
    let selectList = {};
    let isServerSide = false;

        indexStatusHistoryDetail = dataTable_build(
          jquerySelector,
          ajaxUrl,
          jsonRoot,
          columnList,
          rowsGroupList,
          columnDefList,
          selectList,
          orderList,
          buttonList,
          isServerSide,
          {},
          [],
          false
        );
}
////////////////////////////////
//데이터 테이블 렌더링 & Ajax 호출 종료
////////////////////////////////
