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

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

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

const handleCreateDb = async (id: number) => {
  await TenantApi.createDb(id);
  message.success('创建/更新租户数据库成功');
};

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

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

  formEditApi.open();
};

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

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

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      schema: useSearchSchema(),
    },
    gridOptions: {
      checkboxConfig: {
        highlight: true,
        labelField: 'name',
      },
      columns: useColumns(handleActionClick),
      proxyConfig: {
        ajax: {
          query: async ({ page }, formValues) => {
            return await TenantApi.getPage({
              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="'tenant:add'"
          @click="() => handleEdit({}, false)"
        >
          新增租户
        </Button>
      </template>
    </Grid>
  </Page>
</template>
