<!--
 * 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_LOCALE from 'src/config/ag-grid-locale';

import AgGridStudyCom from './AgGridStudyCom.vue';
import AgGridStudyYearFilter from './AgGridStudyYearFilter.vue';

/**
 * filter 过滤器
 * https://ag-grid.com/vue-data-grid/filtering/#provided-filters
 *
 * agNumberColumnFilter: 一个用于数字比较的过滤器
 * agTextColumnFilter: 一个用于字符串比较的过滤器
 * agDateColumnFilter: 一个用于日期比较的过滤器
 * agSetColumnFilter: 一个受Microsoft Excel中过滤器工作方式影响的过滤器。这是一个AG网格企业的功能。
 * **/

const defaultColDef = {
  flex: 1,
  filterParams: {
    buttons: ['apply', 'reset', 'clear'],
    // debounceMs: 0, // 当`apply`按钮存在时，`debounceMs`被忽略
  },
  floatingFilter: true,
};

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

const gridApi = ref<any>(null);
const savedFilterModel = ref<any>(null);

const state = reactive({
  columnDefs: [
    { field: 'age', headerName: '年龄', filter: 'agNumberColumnFilter' },
    // { field: 'year', filter: 'agSetColumnFilter' }, // 企业版 https://ag-grid.com/vue-data-grid/filter-set/
    {
      field: 'year',
      headerName: '年份',
      filter: AgGridStudyYearFilter,
      filterParams: {
        title: '标题',
      },
    },

    {
      field: 'date',
      headerName: '日期',
      filter: 'agDateColumnFilter',
      // https://ag-grid.com/vue-data-grid/filter-date/#date-filter-comparator
      // add extra parameters for the date filter
      filterParams: {
        // provide comparator function
        comparator: (filterLocalDateAtMidnight: any, cellValue: any) => {
          const dateAsString = cellValue;

          if (dateAsString == null) {
            return 0;
          }

          // In the example application, dates are stored as dd/mm/yyyy
          // We create a Date object for comparison against the filter date
          const dateParts = dateAsString.split('/');
          const year = Number(dateParts[2]);
          const month = Number(dateParts[1]) - 1;
          const day = Number(dateParts[0]);
          const cellDate = new Date(year, month, day);

          // Now that both parameters are Date objects, we can compare
          if (cellDate < filterLocalDateAtMidnight) {
            return -1;
          } else if (cellDate > filterLocalDateAtMidnight) {
            return 1;
          }
          return 0;
        },
      },
    },
    {
      field: 'country',
      headerName: '国家',
      filter: 'agMultiColumnFilter', // 企业版 https://ag-grid.com/vue-data-grid/filter-multi/
      cellRenderer: AgGridStudyCom,
      cellRendererParams: {
        config: {
          color: 'primary',
          textColor: 'white',
          square: true,
        },
      },
    },
    {
      field: 'sport',
      headerName: '运动',
      cellRenderer: SimpleComp,
    },
    { field: 'gold', headerName: '金牌' },
    { field: 'silver', headerName: '银牌' },
    {
      field: 'bronze',
      headerName: '铜牌',
      cellRendererSelector: (data: any) => {
        if (data.value < 2) {
          return { component: SimpleComp };
        } else {
          return {
            component: AgGridStudyCom,
            params: { config: { square: true } },
          };
        }
      },
    },
  ],
  rowData: [],
  popupParent: document.body, // https://ag-grid.com/vue-data-grid/column-menu/#popup-parent
});

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();
}

function savaFilterState() {
  const filterModel = gridApi.value.getFilterModel();
  savedFilterModel.value = filterModel;
}

function applyFilterState() {
  const filterModel = savedFilterModel.value;
  gridApi.value.setFilterModel(filterModel);
}
</script>
<template>
  <div class="box">
    <div>
      <q-btn label="取消选择行" color="primary" @click="deselectRows" />
      <q-btn label="保存" color="primary" @click="savaFilterState" />
      <q-btn label="应用" color="primary" @click="applyFilterState" />
    </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"
        :localeText="AG_GRID_LOCALE"
        :popupParent="state.popupParent"
        :columnDefs="state.columnDefs"
        :rowData="state.rowData"
        :defaultColDef="defaultColDef"
        :animateRows="true"
        @cell-clicked="cellWasClicked"
        @grid-ready="onGridReady"
      >
      </ag-grid-vue>
    </div>
  </div>
</template>

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