<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue'
import DeptFormModal from './DeptFormModal.vue'
import { columns, searchFormSchema } from './data'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { useModal } from '@/components/Modal'
import { IconEnum } from '@/enums/appEnum'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { deleteDept, lazyGetDeptList } from '@/api/system/dept'
import type { Department } from '@/api/system/dept/types'

defineOptions({ name: 'SystemDept' })

const { t } = useI18n()

const [registerModal, { openModal }] = useModal<Department>()

const [register, { reload }] = useTable({
  async api(params) {
    const list = await lazyGetDeptList(params)
    return list.map(item => ({
      ...item,
      children: item.hasChildren ? [] : undefined,
    }))
  },
  async onExpand(isExpand, data: Department) {
    if (!isExpand || data.children.length)
      return

    try {
      data.children = await lazyGetDeptList({ parentId: data.id })
    }
    catch {}
  },
  columns,
  formConfig: {
    labelWidth: 80,
    schemas: searchFormSchema,
  },
  bordered: true,
  canResize: false,
  isTreeTable: true,
  useSearchForm: true,
  pagination: false,
  actionColumn: {
    width: 140,
    title: t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
  },
})

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

<template>
  <div>
    <BasicTable :api="async () => ([] as Department[])" @register="register">
      <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: IconEnum.EDIT,
                label: t('action.edit'),
                onClick: () => openModal(true, record),
              },
              {
                icon: IconEnum.DELETE,
                danger: true,
                label: t('action.delete'),
                popConfirm: {
                  title: t('common.delMessage'),
                  placement: 'left',
                  confirm: handleDelete.bind(null, record.id),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>

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