<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'
import { usePermission } from '@/hooks/web/usePermission'

defineOptions({ name: 'SystemDept' })

const { t } = useI18n()

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

const { hasPermission } = usePermission()

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',
    auth: ['dept_delete', 'dept_edit'],
  },
})

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 v-if="hasPermission('dept_add')" #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'),
                auth: 'dept_edit',
                onClick: () => openModal(true, record),
              },
              {
                icon: IconEnum.DELETE,
                danger: true,
                label: t('action.delete'),
                auth: 'dept_delete',
                popConfirm: {
                  title: t('common.delMessage'),
                  placement: 'left',
                  confirm: handleDelete.bind(null, record.id),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>

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