<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue'
import TenantModal from './TenantFormModal.vue'
import { columns, searchFormSchema } from './data'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { deleteTenant, getTenantList } from '@/api/system/tenant'
import type { Tenant } from '@/api/system/tenant/types'
import { useModal } from '@/components/Modal'
import { useMessage } from '@/hooks/web/useMessage'

defineOptions({ name: 'SystemTenant' })

const [registerModal, { openModal }] = useModal<Tenant>()
const [registerTable, { reload }] = useTable({
  api: getTenantList,
  columns,
  formConfig: {
    labelWidth: 100,
    schemas: searchFormSchema,
    actionColOptions: { span: 4 },
  },
  bordered: true,
  canResize: false,
  useSearchForm: true,
  actionColumn: {
    width: 140,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
})

async function handleDelete(id: string) {
  try {
    await deleteTenant(id)
    useMessage().createMessage.success('删除成功！')
    reload()
  }
  catch {}
}
</script>

<template>
  <div>
    <BasicTable :api="async () => ([] as Tenant[])" @register="registerTable">
      <template #tableTitle>
        <a-button type="primary" @click="openModal">
          <PlusOutlined />
          新建
        </a-button>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'i-ant-design:edit-outlined',
                label: '编辑',
                onClick: () => openModal(true, record),
              },
              {
                icon: 'i-ant-design:delete-outlined',
                label: '删除',
                danger: true,
                popConfirm: {
                  title: '确定要删除数据吗？',
                  placement: 'left',
                  confirm: () => handleDelete(record.id),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>

    <TenantModal @register="registerModal" @success="reload()" />
  </div>
</template>
