<!--
 * AG-grid学习
 * https://www.ag-grid.com/vue-data-grid/getting-started/
  -->
<script setup lang="ts">
import { h, ref, reactive, onMounted } from 'vue';
import { AgGridVue } from 'ag-grid-vue3';
import 'ag-grid-enterprise';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
import AgGridStudyCom from './AgGridStudyCom.vue';

const defaultColDef = {
  sortable: true,
  filter: true,
  enableRowGroup: true,
};

const SimpleComp = {
  setup(props: any) {
    const { params } = props;
    return () => h('span', { class: 'text-red' }, params.value);
  },
};

const gridApi = ref<any>(null);

const state = reactive({
  columnDefs: [
    { field: 'age' },
    { field: 'year' },
    {
      field: 'country',
      cellRenderer: AgGridStudyCom,
      cellRendererParams: {
        config: {
          color: 'primary',
          textColor: 'white',
          square: true,
        },
      },
    },
    {
      field: 'sport',
      cellRenderer: SimpleComp,
    },
    { field: 'gold' },
    { field: 'silver' },
    {
      field: 'bronze',
      cellRendererSelector: (data: any) => {
        if (data.value > 2) {
          return { component: SimpleComp };
        } else {
          return {
            component: AgGridStudyCom,
            params: { config: { square: true } },
          };
        }
      },
    },
  ],
  rowData: [],
});

onMounted(() => {
  fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
    .then((result) => result.json())
    .then((remoteRowData) => (state.rowData = remoteRowData));
});

function cellWasClicked(event: any) {
  console.log('cellWasClicked >>>>', event);
}

function onGridReady(params: any) {
  gridApi.value = params.api;
}

function deselectRows() {
  gridApi.value.deselectAll();
}
</script>
<template>
  <div class="box">
    <div>
      <q-btn label="取消选择行" color="primary" @click="deselectRows" />
    </div>
    <!-- 
        rowSelection="multiple"：多选，按住control键多选；【control+shift+鼠标点击】可选中多行
        animateRows=true：启用行动画

        分组：https://ag-grid.com/vue-data-grid/grouping-group-panel/
        【rowGroup: true】 【enableRowGroup: true】 【rowGroupPanelShow="always"】
     -->

    <div>
      <ag-grid-vue
        style="height: 500px"
        class="ag-theme-alpine"
        :columnDefs="state.columnDefs"
        :rowData="state.rowData"
        :defaultColDef="defaultColDef"
        rowSelection="multiple"
        :animateRows="true"
        rowGroupPanelShow="always"
        @cell-clicked="cellWasClicked"
        @grid-ready="onGridReady"
      >
      </ag-grid-vue>
    </div>
  </div>
</template>

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