<script lang="ts" setup>
import { useAccess } from '@vben/access';
import { Page, useVbenModal } from '@vben/common-ui';

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TenantApi } from '#/api';
import { TableAction } from '#/components/table-action';

import FormEdit from './components/edit.vue';
import { gridOptions, searchFormOptions } from './data.config';

const { hasAccessByCodes } = useAccess();

const [Grid, { reload }] = useVbenVxeGrid({
  formOptions: searchFormOptions,
  gridOptions,
});

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

const handleCreateDb = (id: number) => {
  Modal.confirm({
    iconType: 'info',
    title: '提示',
    content: `确定创建/更新租户数据库?`,
    cancelText: `关闭`,
    onOk: async () => {
      await TenantApi.createDb(id);
      message.success('创建/更新租户数据库成功');
    },
  });
};

const handleDelete = (id: number) => {
  Modal.confirm({
    iconType: 'info',
    title: '删除提示',
    content: `确定要删除选择的记录吗?`,
    cancelText: `关闭`,
    onOk: async () => {
      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();
};
</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>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '创建库',
              type: 'text',
              disabled:
                !hasAccessByCodes(['tenant:createDb']) || row.tenantType === 0,
              onClick: handleCreateDb.bind(null, row),
            },
            {
              label: '编辑',
              type: 'text',
              danger: true,
              disabled: !hasAccessByCodes(['tenant:edit']),
              onClick: handleEdit.bind(null, row, true),
            },
          ]"
          :drop-down-actions="[
            {
              label: '重置密码',
              type: 'link',
              disabled: !hasAccessByCodes(['tenant:resetPwd']),
            },
            {
              label: '删除',
              type: 'link',
              disabled: !hasAccessByCodes(['tenant:delete']),
              onClick: handleDelete.bind(null, row.id),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
