<template>
  <!--引用表格-->
  <BasicTable v-if="!visible" @register="registerTable" :rowSelection="rowSelection">
    <!--插槽:table标题-->
    <template #tableTitle>
      <c-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd">新增</c-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <template #overlay>
          <a-menu>
            <a-menu-item key="1" @click="batchHandleDelete">
              <Icon icon="ant-design:delete-outlined" />
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <c-button>
          批量操作
          <Icon icon="ant-design:down-outlined" />
        </c-button>
      </a-dropdown>
    </template>
    <!--操作栏-->
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" />
    </template>
  </BasicTable>
  <!-- 表单区域 -->
  <Detail v-if="visible" :id="id" @close="visible = false" />
</template>

<script lang="ts" name="iot-iotDeviceAccessCertificate" setup>
  import { ref } from 'vue';
  import { BasicTable, TableAction } from '@jdlinker/ui';
  import { useListPage } from '@jdlinker/ui';
  import Detail from './Detail/index.vue';
  import { columns, searchFormSchema } from './data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from '../../../api/link/certificate';

  const visible = ref<boolean>(false);
  const id = ref<string>('');
  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      api: list,
      columns,
      formConfig: {
        schemas: searchFormSchema
      }
    },
    exportConfig: {
      name: 'linker_device_access_certificate',
      url: getExportUrl
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess
    }
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  /**
   * 新增事件
   */
  function handleAdd() {
    visible.value = true;
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: any) {
    visible.value = true;
    id.value = record.id;
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        icon: 'clarity:note-edit-line',
        tooltip: '编辑',
        onClick: handleEdit.bind(null, record)
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        tooltip: '删除',
        popConfirm: {
          title: '是否确认删除',
          placement: 'left',
          confirm: handleDelete.bind(null, record)
        }
      }
    ];
  }
</script>
