<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Space } from 'ant-design-vue'
import { DisconnectOutlined, LinkOutlined } from '@ant-design/icons-vue'
import { BindingDeviceDrawer, GroupList } from './components'
import { useColumns, useSearchFormSchemas } from './data'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { useMessage } from '@/hooks/web/useMessage'
import { getDeviceListByGroup, unbindingDeviceFromGroup } from '@/api/device-manage/group'
import { useDrawer } from '@/components/Drawer'
import { noop } from '@/utils'

const [register, { getSelectRowKeys, reload }] = useTable({
  async api(params) {
    if (!selectedGroupId.value)
      return []

    return getDeviceListByGroup({
      ...params,
      groupId: selectedGroupId.value,
    })
  },
  rowKey: 'id',
  columns: useColumns(),
  formConfig: {
    schemas: useSearchFormSchemas(),
    labelWidth: 90,
  },
  rowSelection: {},
  bordered: true,
  canResize: false,
  useSearchForm: true,
  actionColumn: {
    width: 210,
    title: '操作',
    dataIndex: 'action',
  },
})

const [registerBindingDeviceDrawer, { openDrawer }] = useDrawer()

const selectedGroupId = ref<string | undefined>()
watch(selectedGroupId, reload)

const message = useMessage()
function handleBindingDivice() {
  if (!selectedGroupId.value)
    return message.createMessage.warn('请先选择分组')

  openDrawer(true, selectedGroupId.value)
}
function handleUnbindingDivice(id?: string) {
  const selectionKeys = id ? [id] : getSelectRowKeys()
  if (!selectionKeys.length)
    return message.createMessage.warn('请先选择设备')

  function execute() {
    unbindingDeviceFromGroup(selectedGroupId.value!, selectionKeys.join(','))
      .then(() => {
        message.createMessage.success('解绑成功')
        reload()
      })
      .catch(noop)
  }

  if (id)
    return execute()

  // 批量绑定设备二次确认
  message.createConfirm({
    iconType: 'warning',
    title: '是否要解绑选择的设备？',
    onOk: execute,
  })
}
</script>

<template>
  <div flex="~">
    <GroupList v-model:selectedGroupId="selectedGroupId" my="12px" ml="12px" />
    <BasicTable flex="1" @register="register">
      <template #tableTitle>
        <Space>
          <a-button @click="handleBindingDivice">
            <LinkOutlined />
            批量绑定设备
          </a-button>
          <a-button @click="handleUnbindingDivice()">
            <DisconnectOutlined />
            批量解绑设备
          </a-button>
        </Space>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'i-ant-design:file-search-outlined',
                label: '设备详情',
                onClick: () => $router.push(`/device-manage/device/detail/${record.id}`),
              },
              {
                icon: 'i-ant-design:edit-outlined',
                label: '解绑设备',
                popConfirm: {
                  title: '是否要解绑该设备？',
                  placement: 'left',
                  confirm: () => handleUnbindingDivice(record.id),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>

    <BindingDeviceDrawer @register="registerBindingDeviceDrawer" @success="reload" />
  </div>
</template>
