<!--
 * Ag Grid 自定义日期组件
 * https://www.ag-grid.com/vue-data-grid/component-date/
 -->
<script lang="ts">
import { ref, reactive, defineComponent } from 'vue';
import { AgGridVue } from 'ag-grid-vue3';
// import { date } from 'quasar';

import Com from 'src/components';
import AG_GRID_LOCALE from 'src/config/ag-grid-locale';
import { isEmpty } from 'src/common/utils';

export default defineComponent({
  name: 'AgGridCustomDateComponent',
  components: {
    'ag-grid-vue': AgGridVue,
    // eslint-disable-next-line vue/no-unused-components
    agDateInput: Com.AgGridDateComponent,
  },
  setup() {
    const gridApi = ref<any>(null);
    const gridColumnApi = ref<any>(null);

    const defaultColDef = reactive({
      flex: 1,
      minWidth: 100,
      resizable: true,
      editable: true, // 可编辑
      sortable: true,
      filter: true,
      // floatingFilter: true,
    });

    const columnDefs = reactive([
      { field: 'athlete', headerName: '运动员' },
      { field: 'age', headerName: '年龄', filter: 'agNumberColumnFilter' },
      { field: 'country', headerName: '国家' },
      { field: 'year', headerName: '年份' },
      {
        field: 'date',
        minWidth: 190,
        headerName: '日期',
        filter: 'agDateColumnFilter',
        filterParams: {
          comparator: (filterLocalDateAtMidnight: any, cellValue: any) => {
            // const formattedString = date.formatDate(
            //   filterLocalDateAtMidnight,
            //   'YYYY/MM/DD'
            // );
            // console.log(
            //   'filterLocalDateAtMidnight',
            //   formattedString,
            //   'cellValue',
            //   cellValue
            // );

            const dateAsString = cellValue;
            const dateParts = dateAsString.split('/');
            const cellDate = new Date(
              Number(dateParts[2]),
              Number(dateParts[1]) - 1,
              Number(dateParts[0])
            );
            if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
              return 0;
            }
            if (cellDate < filterLocalDateAtMidnight) {
              return -1;
            }
            if (cellDate > filterLocalDateAtMidnight) {
              return 1;
            }
          },
        },
        comparator: (d1: any, d2: any) => {
          return getComparatorDate(d1).getTime() <
            getComparatorDate(d2).getTime()
            ? -1
            : 1;
        },
        valueFormatter: (params: any) => {
          let resStr = '';
          if (!isEmpty(params.value)) {
            const dateArr = params.value.split('/');
            resStr = dateArr[2] + '-' + dateArr[1] + '-' + dateArr[0];
          }
          return resStr;
        },
      },
      { field: 'sport', headerName: '运动' },
      { field: 'gold', headerName: '金牌', filter: 'agNumberColumnFilter' },
      { field: 'silver', headerName: '银牌', filter: 'agNumberColumnFilter' },
      { field: 'bronze', headerName: '铜牌', filter: 'agNumberColumnFilter' },
      { field: 'total', headerName: '共计', filter: false },
    ]);

    const state = reactive({
      rowData: [] as any[],
    });

    const onGridReady = (params: any) => {
      gridApi.value = params.api;
      gridColumnApi.value = params.columnApi;
      getData();
    };

    const getData = () => {
      fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
        .then((resp) => resp.json())
        .then((data) => updateData(data));
    };

    const updateData = (data: any) => {
      state.rowData = data.slice(0, 5);
      console.log('rowData[0]', state.rowData[0]);
    };

    const onReset = () => {
      gridApi.value.setFilterModel(null);
      gridApi.value.destroyFilter('date');
    };

    const getComparatorDate = (data: string) => {
      // 21/01/2008
      const dateArr = data.split('/');
      const year = Number(dateArr[2]);
      const month = Number(dateArr[1]);
      const day = Number(dateArr[0]);
      const newDate = new Date(year, month, day);
      return newDate;
    };

    return {
      AG_GRID_LOCALE,
      Com,
      defaultColDef,
      columnDefs,
      state,
      onGridReady,
      onReset,
    };
  },
});
</script>
<template>
  <div>
    <div class="btns">
      <q-btn color="primary" label="重置" no-caps unelevated @click="onReset" />
    </div>
    <!-- 
        rowSelection="multiple"：多选，按住control键多选；【control+shift+鼠标点击】可选中多行
        animateRows=true：启用行动画
        :masterDetail="true" 启用展开的细节网格行
        :isRowMaster="isRowMaster" 确定哪一个行该展开
        :pagination="true"
        :paginationPageSize="100"
     -->
    <div class="ag-table">
      <ag-grid-vue
        style="height: 580px"
        class="ag-theme-alpine"
        :localeText="AG_GRID_LOCALE"
        :animateRows="true"
        :pagination="true"
        :paginationPageSize="10"
        :defaultColDef="defaultColDef"
        :columnDefs="columnDefs"
        :rowData="state.rowData"
        @grid-ready="onGridReady"
      >
      </ag-grid-vue>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.btns {
  padding: 10px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  column-gap: 10px;
}
.ag-table {
  padding: 0 10px 10px 10px;
}
</style>
