<!--
 * @FileDescription: 主页
 * @Date: 2023-08-03
 * @LastEditTime: 2023-10-08
-->
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { AgGridVue } from 'ag-grid-vue3';
import type { GridOptions, GetRowIdParams } from 'ag-grid-community';
import { sportEnums } from './config';
import CountryCellRender from './elements/CountryCellRender.vue';

const sportMap = computed(() => {
  const obj: any = {};
  for (const item of sportEnums) {
    obj[item.value] = item.label;
  }

  return obj;
});

// Ag Grid
const gridOptions: GridOptions<any> = reactive({
  rowModelType: 'serverSide',
  cacheBlockSize: 50, // 这将块大小设置为50，因此每次回读50行。
  maxBlocksInCache: 2, // 这意味着网格将只在内存中保留两个块。

  suppressContextMenu: true, // 阻止“右键单击”上下文菜单
  suppressCellFocus: true, // 阻止单元格聚焦，这意味着键盘导航将对网格单元格禁用
  rowSelection: 'single',
  defaultColDef: {
    suppressMenu: true, // 阻止此列标头菜单显示
  },
  columnDefs: [
    {
      headerName: '序号',
      maxWidth: 80,
      valueFormatter: (params: any) => {
        return params.node?.rowIndex + 1;
      },
    },
    { headerName: '运动员', field: 'athlete', minWidth: 170 },
    { headerName: '年龄', field: 'age' },
    { headerName: '国家', field: 'country', cellRenderer: CountryCellRender },
    { headerName: '年份', field: 'year' },
    { headerName: '日期', field: 'date' },
    {
      headerName: '运动项目',
      field: 'sport',
      valueFormatter: (params) => {
        return sportMap.value[params.value] || params.value;
      },
    },
    {
      headerName: '金牌',
      field: 'gold',
      cellStyle: { color: '#FFA500' },
    },
    { headerName: '银牌', field: 'silver', cellStyle: { color: '#717A84' } },
    { headerName: '铜牌', field: 'bronze', cellStyle: { color: '#834C24' } },
    { headerName: '总数', field: 'total' },
  ],
  rowData: [],
  onGridReady,

  // Server-Side Row Selection requires Row ID's to be supplied to grid.
  // https://www.ag-grid.com/vue-data-grid/server-side-model-configuration/#providing-row-ids
  getRowId,
});

const count = ref(0);
const state = reactive({
  sport: null,
});

onMounted(() => {
  //
});

function onGridReady() {
  onFetch();
}
function onFetch() {
  fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
    .then((resp) => resp.json())
    .then((data: any[]) => {
      // if (state.sport) {
      //   data = data.filter((item) => item.sport == state.sport);
      // }

      const newList: any[] = [];

      let index = 1;
      for (const item of data) {
        item.id = index;
        if (state.sport) {
          item.sport == state.sport ? newList.push(item) : '';
        } else {
          newList.push(item);
        }
        index++;
      }
      updateData(newList);
      count.value = newList.length;
    });
}
function updateData(data: any) {
  const fakeServer = createFakeServer(data);
  const datasource = createServerSideDatasource(fakeServer);
  // 向网格注册数据源
  gridOptions.api?.setServerSideDatasource(datasource);
}

// 用整个数据集设置假服务器
function createFakeServer(allData: any[]) {
  return {
    getData: (request: any) => {
      // 在这个简化的假服务器中，所有行都包含在一个数组中
      const requestedRows = allData.slice(request.startRow, request.endRow);
      return {
        success: true,
        rows: requestedRows,
      };
    },
  };
}
// 使用对假服务器的引用创建数据源
function createServerSideDatasource(server: any) {
  return {
    getRows: (params: any) => {
      // console.log('[Datasource] - rows requested by grid: ', params.request);
      // 从我们的假服务器获取请求的数据
      const response = server.getData(params.request);

      // 模拟真实服务器调用，延迟1000ms
      setTimeout(function () {
        if (response.success) {
          // 向网格提供请求块的行
          params.success({ rowData: response.rows });
        } else {
          params.fail();
        }
      }, 1000);
    },
  };
}
function getRowId(params: GetRowIdParams) {
  return 'leaf-' + params.data.id;
}

function onSearch() {
  onFetch();
}
function onReset() {
  state.sport = null;
  onFetch();
}
</script>
<template>
  <div class="home-page-home fit">
    <div class="actions q-pa-md">
      <div class="form-item">
        <div class="form-label">运动项目</div>
        <q-select
          dense
          filled
          clearable
          v-model="state.sport"
          :options="sportEnums"
          emit-value
          map-options
        />
      </div>
      <div class="btns-box">
        <div class="q-gutter-xs">
          <q-btn color="primary" label="重置" outline @click="onReset" />
          <q-btn color="primary" label="搜索" unelevated @click="onSearch" />
        </div>
      </div>
      <q-space />
      <div class="count-text">
        共有 <q-chip square :ripple="false">{{ count }}</q-chip
        >条数据
      </div>
    </div>
    <div class="table-box">
      <ag-grid-vue class="ag-theme-material fit" :grid-options="gridOptions">
      </ag-grid-vue>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.home-page-home {
  display: flex;
  flex-direction: column;
  .table-box {
    flex: 1;
  }

  .actions {
    display: flex;
    flex-direction: row;
    align-items: flex-end;
  }

  .count-text {
    font-family: $font-family;
    font-size: 13px;
    color: $text-color;
  }

  .btns-box {
    margin-left: $padding-lg;
    padding-bottom: 2px;
  }

  .form-item {
    width: 240px;
    .form-label {
      font-family: $font-family;
      font-size: 13px;
      color: $text-color;
    }
  }
}
</style>
