document.addEventListener("DOMContentLoaded", function () {
    loadDataHeightSubDistrict("2021");

    const btnSpanExcel = document.getElementById("btn-span-excel");
    $("#choiceYear").on("change", function () {
        year = $(this).val();

        $("#span-year").text(year);
        loadDataHeightSubDistrict(year);
    });

    btnSpanExcel.addEventListener("click", function () {
        const year = $("#choiceYear").val();
        var url = "/parameter-ketinggian-kecamatan/" + year;

        window.open(url, "_self");
    });
});

let gridInstance;
function loadDataHeightSubDistrict(years) {
    const tableContainerHeightSubDistrict = document.getElementById(
        "table-height-sub-district"
    );

    if (tableContainerHeightSubDistrict) {
        tableContainerHeightSubDistrict.innerHTML = "";
    }

    $.ajax({
        url: `/parameter-ketinggian-kecamatan/getDataHeightSubDistrict`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const TableDataHeightSubDistrict = data["allSubDistrict"].map(
                (item, index) => [
                    index + 1,
                    item["sub_district"],
                    item["latitude"],
                    item["longitude"],
                ]
            );

            if (gridInstance) {
                gridInstance
                    .updateConfig({
                        data: TableDataHeightSubDistrict,
                    })
                    .forceRender();
            } else {
                gridInstance = new gridjs.Grid({
                    columns: ["No", "Kecamatan", "Latitude", "Longitude"],
                    data: TableDataHeightSubDistrict,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerHeightSubDistrict);
            }
        },
    });
}
