<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue'
import UserFormModal from './UserFormModal.vue'
import { columns, searchFormSchema } from './data'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { useModal } from '@/components/Modal'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { deleteUser, getUserList } from '@/api/system/user'
import type { SystemUser } from '@/api/system/user/types'

defineOptions({ name: 'SystemUser' })

const { t } = useI18n()
const { createMessage } = useMessage()
const [registerModal, { openModal }] = useModal<SystemUser>()

const [registerTable, { reload }] = useTable({
  api(params) {
    return getUserList(params)
  },
  columns,
  formConfig: {
    labelWidth: 80,
    schemas: searchFormSchema,
    autoSubmitOnEnter: true,
  },
  useSearchForm: true,
  bordered: true,
  canResize: false,
  actionColumn: {
    width: 140,
    title: t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
  },
})

async function handleDelete(id: string) {
  try {
    await deleteUser(id)
    createMessage.success(t('common.delSuccessText'))
    reload()
  }
  catch {}
}
</script>

<template>
  <div>
    <BasicTable :api="async () => ([] as SystemUser[])" @register="registerTable">
      <template #tableTitle>
        <a-button type="primary" @click="openModal">
          <PlusOutlined />
          {{ t('action.create') }}
        </a-button>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'i-ant-design:edit-outlined',
                label: t('action.edit'),
                onClick: () => openModal(true, record),
              },
              {
                icon: 'i-ant-design:delete-outlined',
                danger: true,
                label: t('action.delete'),
                popConfirm: {
                  title: t('common.delMessage'),
                  placement: 'left',
                  confirm: () => handleDelete(record.id),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>

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