<script lang="ts" setup>
import FactoryModal from './FactoryModal.vue'
import { columns } from './Factory'
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 { deleteFactory, getFactoryPage } from '@/api/system/config/Factory'

defineOptions({ name: 'UnitFactory' })

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

const [register, { getForm, reload }] = useTable({
  title: '厂级列表',
  api: getList,
  columns,
  rowKey: 'id',
  formConfig: { labelWidth: 120 },
  pagination: true,
  useSearchForm: false,
  showTableSetting: true,
  showIndexColumn: false,
  actionColumn: {
    width: 140,
    title: t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
  },
})

async function getList() {
  const res = await getFactoryPage(getForm().getFieldsValue() as any)
  return res
}

function handleCreate() {
  openModal(true, { isUpdate: false })
}

function handleEdit(record: Recordable) {
  openModal(true, { record, isUpdate: true })
}

async function handleDelete(record: Recordable) {
  await deleteFactory(record.id)
  createMessage.success(t('common.delSuccessText'))
  reload()
}
</script>

<template>
  <div>
    <BasicTable @register="register">
      <template #toolbar>
        <a-button v-auth="['system:Factory:create']" type="primary" :pre-icon="IconEnum.ADD" @click="handleCreate">
          {{ 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: 'system:Factory:update', onClick: handleEdit.bind(null, record) },
              {
                icon: IconEnum.DELETE,
                danger: true,
                label: t('action.delete'),
                auth: 'system:Factory:delete',
                popConfirm: {
                  title: t('common.delMessage'),
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <FactoryModal @register="registerModal" @success="reload()" />
  </div>
</template>

<style scoped>
/* 深度选择器覆盖 Ant Design 内部样式 */
:deep(.ant-table-body) {
  height: auto !important;
  min-height: 200px;
  max-height: 300 !important;
}
</style>
