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

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

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

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

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

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

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

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

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

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

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      schema: useSearchSchema(),
    },
    gridOptions: {
      pagerConfig: {
        enabled: false,
      },
      treeConfig: {
        rowField: 'id',
        childrenField: 'children',
      },
      columns: useColumns(handleActionClick),
      proxyConfig: {
        ajax: {
          query: async ({ page }, formValues) => {
            return await MenuApi.getList({
              pageIndex: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);
</script>

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