<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 { DepartmentApi } from '#/api';

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

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

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

const handleEdit = (record: any, isUpdate: boolean) => {
  formEditApi
    .setData({
      isUpdate,
      baseData: { id: record.id },
    })
    .open();
};
const handleActionClick = async ({
  code,
  row,
}: OnActionClickParams<DepartmentApi.RecordItem>) => {
  switch (code) {
    case 'delete': {
      await handleDelete(row.id);
      break;
    }
    case 'edit': {
      handleEdit(row, true);
      break;
    }
  }
};

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      schema: useSearchSchema(),
    },
    gridOptions: {
      pagerConfig: {
        enabled: false,
      },
      treeConfig: {
        rowField: 'id',
        childrenField: 'children',
        transform: false,
      },
      columns: useColumns(handleActionClick),
      proxyConfig: {
        ajax: {
          query: async (_, formValues) => {
            return await DepartmentApi.getTree({
              ...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="'department:add'"
          @click="() => handleEdit({}, false)"
        >
          新增组织
        </Button>
      </template>
    </Grid>
  </Page>
</template>
