<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { useStore } from '../store';
import { AgGridVue } from 'ag-grid-vue3';
import type { GridOptions, GridApi } from 'ag-grid-community';

const store = useStore();

const isGridReady = ref(false);
const gridApi = ref<GridApi>();
// Ag Grid
const gridOptions: GridOptions<any> = reactive({
    suppressContextMenu: true, // 阻止“右键单击”上下文菜单
    suppressCellFocus: true, // 阻止单元格聚焦，这意味着键盘导航将对网格单元格禁用
    defaultColDef: {
        suppressMenu: true, // 阻止此列标头菜单显示
    },
    columnDefs: [
        {
            headerName: '序号',
            maxWidth: 80,
            valueFormatter: (params: any) => {
                return params.node?.rowIndex + 1;
            },
        },

        { headerName: 'Dessert (100g serving)', field: 'name' },
        { headerName: 'Calories', field: 'calories' },
        { headerName: 'Fat (g)', field: 'fat' },
        { headerName: 'Carbs (g)', field: 'carbs' },
        { headerName: 'Protein (g)', field: 'protein' },
        { headerName: 'Sodium (mg)', field: 'sodium' },
        { headerName: 'Calcium (%)', field: 'calcium' },
        { headerName: 'Iron (%)', field: 'iron' },
    ],
    rowData: [],
    onGridReady: (params) => {
        isGridReady.value = true;
        gridApi.value = params.api;
    }

});

watch(
    () => store.rows,
    () => {
        doSetMyRows();
    },
    {
        immediate: true,
        deep: true
    }
)

function doSetMyRows() {
    if (isGridReady.value) {
        setMyRows();
    } else {
        setTimeout(() => {
            doSetMyRows();
        }, 500);
    }
}
function setMyRows() {
    console.log('变了');
    gridApi.value?.setRowData(store.rows)
}
</script>
<template>
    <div>

        <div style="height:500px;width:100%">
            <ag-grid-vue class="ag-theme-material fit" :grid-options="gridOptions">
            </ag-grid-vue>
        </div>
    </div>
</template>

<style lang="scss" scoped></style>
