<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { UserApi } from '#/api';

import { ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteLogs, queryLogList } from '#/api';

import { useColumns, useGridFormSchema } from './data';

const [FormDrawer] = useVbenDrawer({
  destroyOnClose: true,
});

const selectedRowIds = ref<number[]>([]);

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    fieldMappingTime: [['createTime', ['startTime', 'endTime']]],
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          const res = await queryLogList({
            page: page.currentPage,
            size: page.pageSize,
            current: page.currentPage,
            ...formValues,
          });
          return {
            items: res.records,
            total: res.total,
          };
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },

    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
  } as VxeTableGridOptions<UserApi.User>,
});

function onRefresh() {
  gridApi.query();
}

async function onDelete() {
  const ids = gridApi.grid.getCheckboxRecords();
  selectedRowIds.value = ids.map((item) => item.id);
  try {
    await deleteLogs(selectedRowIds.value);
    message.success('删除成功');
    onRefresh();
  } catch {
    message.error('删除失败');
  }
}
</script>
<template>
  <Page auto-content-height>
    <FormDrawer />
    <Grid table-title="用户列表">
      <template #toolbar-tools>
        <Button
          type="primary"
          @click="onDelete"
          danger
          v-access:code="'system:log:delete'"
        >
          批量删除
        </Button>
      </template>
      <template #makeTime="{ row }">
        {{ dayjs(row.makeTime).format('YYYY-MM-DD HH:mm') }}
      </template>
    </Grid>
  </Page>
</template>
