<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增设备 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div class="flex items-center justify-center">
            <TableAction
              :actions="[
                { label: '编辑', onClick: handleEdit.bind(null, record) },
                {
                  label: '删除',
                  popConfirm: {
                    title: '是否确认删除',
                    placement: 'topRight',
                    confirm: handleDelete.bind(null, record),
                  },
                },
              ]"
            />
          </div>
        </template>
      </template>
    </BasicTable>
    <DeviceDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '/@/components/Table'
  import { getDevices, deleteDevice } from '/@/api/sys/other'
  import { message } from 'ant-design-vue'
  import { useDrawer } from '/@/components/Drawer'
  import DeviceDrawer from './DeviceDrawer.vue'
  import { columns, searchFormSchema } from './management.data'
  const [registerDrawer, { openDrawer }] = useDrawer()
  const [registerTable, { reload }] = useTable({
    title: '设备列表',
    api: async (e) => {
      const { data, meta } = await getDevices({ ...e })
      return {
        items: data,
        total: meta?.total,
      }
    },
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: true,
  })

  const handleSuccess = () => {
    message.success('操作成功')
    reload()
  }
  const handleCreate = () => {
    openDrawer(true, {
      id: false,
    })
  }
  const handleEdit = (record: Recordable) => {
    openDrawer(true, {
      ...record,
      isUpdate: true,
    })
  }
  const handleDelete = async (record: Recordable) => {
    await deleteDevice(record.id)
    message.success('删除成功')
    reload()
  }
</script>
