<!--
 * AG-grid 细节网格细节配置
 * https://www.ag-grid.com/vue-data-grid/master-detail-grids/
 -->
<script setup lang="ts">
import { 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';

const defaultColDef = {
  flex: 1,
  suppressMenu: true, // 禁用标题行菜单
};

const gridApi = ref<any>(null);
const gridColumnApi = ref<any>(null);
const detailCellRendererParams = reactive({
  // 提供要在细节网格上使用的网格选项
  detailGridOptions: {
    columnDefs: [
      { field: 'callId', headerName: '呼叫标识' },
      { field: 'direction', headerName: '方向' },
      { field: 'number', headerName: '号码' },
      {
        field: 'duration',
        headerName: '持续时间',
        valueFormatter: 'x.toLocaleString() + "秒"',
      },
      { field: 'switchCode', headerName: '开关代码' },
    ],
    defaultColDef,
    rowSelection: 'multiple',
    suppressRowClickSelection: true, // 抑制行点击选择
    enableRangeSelection: true, // 启用范围选择
    pagination: true,
    paginationAutoPageSize: true,
  },
  // 获得每个细节网格的行数
  getDetailRowData: (params: any) => {
    params.successCallback(params.data.callRecords || []);
  },
});

const state = reactive({
  columnDefs: [
    { field: 'name', headerName: '姓名', cellRenderer: 'agGroupCellRenderer' },
    { field: 'account', headerName: '帐户' },
    { field: 'calls', headerName: '呼叫' },
    {
      field: 'minutes',
      headerName: '分钟',
      valueFormatter: 'x.toLocaleString() + "分钟"',
    },
  ],
  rowData: [] as any,
});

onMounted(() => {
  fetch('https://www.ag-grid.com/example-assets/master-detail-data.json')
    .then((result) => result.json())
    .then((remoteRowData) => {
      state.rowData = remoteRowData;
      console.log('rowData', state.rowData[0]);
    });

  // .then((remoteRowData) => (state.rowData = remoteRowData));
});

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

function isRowMaster(dataItem: any) {
  let flag;
  if (dataItem && dataItem.callRecords && dataItem.callRecords.length > 0) {
    flag = true;
  } else {
    flag = false;
  }
  return flag;
}
</script>
<template>
  <div class="box">
    <!-- 
        rowSelection="multiple"：多选，按住control键多选；【control+shift+鼠标点击】可选中多行
        animateRows=true：启用行动画
        :masterDetail="true" 启用展开的细节网格行
        :isRowMaster="isRowMaster" 确定哪一个行该展开
     -->

    <div>
      <ag-grid-vue
        style="height: 700px"
        class="ag-theme-alpine"
        :columnDefs="state.columnDefs"
        :rowData="state.rowData"
        :defaultColDef="defaultColDef"
        :animateRows="true"
        :masterDetail="true"
        :isRowMaster="isRowMaster"
        :detailCellRendererParams="detailCellRendererParams"
        @grid-ready="onGridReady"
      >
      </ag-grid-vue>
    </div>
  </div>
</template>

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