<script lang="ts" setup>
import type { OnActionClickParams, VxeTableGridOptions } from '#/adapter';

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

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

import { useTableGridOptions, useVbenVxeGrid } from '#/adapter';
import { DatabaseApi } from '#/api';

import FormEdit from './components/edit.vue';
import { useColumns, useSearchSchema } from './data.config';

const [FormEditModal, formEditApi] = useVbenModal({
  connectedComponent: FormEdit,
});

const handleDelete = async (id: number) => {
  await DatabaseApi.deleteDetail(id);
  message.success('数据删除成功');
  reload();
};

const handelCreate = async (id: number) => {
  await DatabaseApi.getCreate(id);
  message.success('创建表成功');
  reload();
};

const handleEdit = (record: any, isUpdate: boolean) => {
  formEditApi
    .setData({
      isUpdate,
      baseData: { id: record.id },
    })
    .open();
};

const handelSuccess = () => {
  reload();
};

const handleActionClick = async ({
  code,
  row,
}: OnActionClickParams<DatabaseApi.RecordItem>) => {
  switch (code) {
    case 'create': {
      handelCreate(row.id);
      break;
    }
    case 'delete': {
      await handleDelete(row.id);
      break;
    }
    case 'edit': {
      handleEdit(row, true);
      break;
    }
  }
};

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      schema: useSearchSchema(),
    },
    gridOptions: {
      columns: useColumns(handleActionClick),
      proxyConfig: {
        ajax: {
          query: async ({ page }, formValues) => {
            return await DatabaseApi.getPage({
              pageIndex: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);
</script>

<template>
  <Page auto-content-height>
    <FormEditModal @success="handelSuccess" />
    <Grid>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'table:add'"
          @click="() => handleEdit({}, false)"
        >
          新增表
        </Button>
      </template>
    </Grid>
  </Page>
</template>
