<!--
 * @FileDescription: Ag Grid Selection
 * @Date: 2023-08-07
 * @LastEditTime: 2023-10-08
-->
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { AgGridVue } from 'ag-grid-vue3';
import type { GridOptions } from 'ag-grid-community';
import { cloneDeep } from 'src/common/utils';
import { useMessage } from 'src/common/hooks';
import { tableData } from './config';

const { warn } = useMessage();

const show = ref(true);
const state = reactive({
  rows: [] as any[],
  selectedRows: [] as any[],
});

// Ag Grid
// https://www.ag-grid.com/vue-data-grid/data-update-transactions/
const gridOptions: GridOptions<any> = reactive({
  suppressContextMenu: true, // 阻止“右键单击”上下文菜单
  suppressCellFocus: true, // 阻止单元格聚焦，这意味着键盘导航将对网格单元格禁用
  rowSelection: 'single',
  enableCellTextSelection: true, // 选择单元格中的文本
  defaultColDef: {
    suppressMenu: true, // 阻止此列标头菜单显示
    flex: 1,
  },
  columnDefs: [
    {
      headerName: '',
      field: '',
      maxWidth: 50,
      checkboxSelection: true,
    },

    {
      headerName: '序号',
      maxWidth: 80,
      valueFormatter: (params: any) => {
        return params.node?.rowIndex + 1;
      },
    },
    { headerName: '姓名', field: 'name' },
    { headerName: '年龄', field: 'age' },
  ],
  rowData: [],
  onGridReady,
  onFirstDataRendered: (params) => {
    // const nodesToSelect: any[] = [];
    // params.api.forEachNode((node, index) => {
    //   if (node.data && index === 0) {
    //     nodesToSelect.push(node);
    //   }
    // });
    // params.api.setNodesSelected({ nodes: nodesToSelect, newValue: true });

    const nodesToSelect: any[] = [];
    for (const item of state.selectedRows) {
      const idStr = item.id.toString();
      const rowNode = params.api.getRowNode(idStr);
      rowNode ? nodesToSelect.push(rowNode) : '';
    }
    // 默认选中第一条
    if (nodesToSelect.length < 1 && state.rows.length > 0) {
      const idStr = state.rows[0].id.toString();
      const rowNode = params.api.getRowNode(idStr);
      rowNode ? nodesToSelect.push(rowNode) : '';
    }
    params.api.setNodesSelected({ nodes: nodesToSelect, newValue: true });
  },
  getRowId: (params) => {
    return String(params.data.id);
  },
  onSelectionChanged: (params) => {
    state.selectedRows = params.api?.getSelectedRows();

    // 已选择的复选框，点击取消选择时，继续选中
    // const lastId = state.selectedRows[0]?.id;
    // if (state.selectedRows.length === 0 && lastId) {
    //   const rowNode = params.api.getRowNode(String(lastId));
    //   rowNode ? rowNode.setSelected(true) : '';
    // }
  },
});

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

function onGridReady() {
  state.rows = tableData;
  gridOptions.api?.setRowData(tableData);
}

function onUpdata() {
  const data = cloneDeep(tableData);
  data[0].name = '甄漂亮';
  gridOptions.api?.setRowData(data);
  state.selectedRows = gridOptions.api?.getSelectedRows() as any[];
}
function onDestroy() {
  show.value = false;
  state.rows = [];
}
function onRedraw() {
  show.value = true;
}
function onGetRowData() {
  const rowData: any[] = [];
  gridOptions.api?.forEachNode(function (node) {
    rowData.push(node.data);
  });
  state.rows = rowData;
  console.table(rowData);
}
function addItem() {
  const newData = {
    id: Date.now(),
    name: 'xxx',
    age: 0,
  };
  const newItems = [newData];
  gridOptions.api?.applyTransaction({
    add: newItems,
  });
}
function removeItem() {
  const selectedDatas = gridOptions.api?.getSelectedRows();
  if (selectedDatas && selectedDatas.length > 0) {
    gridOptions.api?.applyTransaction({ remove: selectedDatas });
  } else {
    warn('请选择一条数据');
  }
}
</script>
<template>
  <div class="ag-grid-selection fit">
    <div class="actions">
      <div class="q-gutter-xs">
        <q-btn color="primary" label="更新" unelevated @click="onUpdata" />
        <q-btn color="primary" label="销毁" unelevated @click="onDestroy" />
        <q-btn color="primary" label="重绘" unelevated @click="onRedraw" />
        <q-btn color="primary" label="添加一条" unelevated @click="addItem" />
        <q-btn
          color="primary"
          label="删除一条"
          unelevated
          @click="removeItem"
        />
        <q-btn
          color="primary"
          label="Get Row Data"
          unelevated
          @click="onGetRowData"
        />
      </div>
    </div>
    <div class="table-box">
      <ag-grid-vue
        v-if="show"
        class="ag-theme-material"
        style="width: 500px; height: 600px"
        :grid-options="gridOptions"
      >
      </ag-grid-vue>
    </div>
    <div>
      <div>已选择</div>
      <div>{{ state.selectedRows }}</div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.ag-grid-selection {
  display: flex;
  flex-direction: column;
}
</style>
