<template>
  <div>
    <DynamicTable
      row-key="id"
      header-title="附件管理"
      :data-request="loadTableData"
      :columns="baseColumns"
      bordered
      size="small"
    >
      <template #toolbar>
        <a-popconfirm
          title="你确定要删除这些附件吗?"
          ok-text="确定"
          cancel-text="取消"
          @confirm="handleDelete"
        >
          <a-button :disabled="!$auth('tool:storage:delete') || !checkedKeys.length" type="error">
            删除
          </a-button>
        </a-popconfirm>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { baseColumns, searchFormSchema } from './columns';
  import { useTable, type LoadDataParams } from '@/components/core/dynamic-table';
  import Api from '@/api/';

  defineOptions({
    name: 'AttachmentManage',
  });
  const props = defineProps({
    fileIds: {
      type: Array as PropType<number[]>,
    },
    onDelete: { type: Function as PropType<(ids: number[]) => Promise<void>>, default: () => {} },
  });
  const checkedKeys = ref<Array<number>>([]);
  const loadTableData = async (params: LoadDataParams) => {
    const data = await Api.toolsStorage.storageList({
      ...params,
      ids: (props.fileIds || []).join(','),
    });
    return data;
  };
  const [DynamicTable, dynamicTableInstance] = useTable({
    formProps: {
      schemas: searchFormSchema,
    },
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys as unknown as Key[],
      onSelect: (record, selected) => {
        if (selected) {
          checkedKeys.value = [...checkedKeys.value, record.id];
        } else {
          checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
        }
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const changeIds = changeRows.map((item) => item.id);
        if (selected) {
          checkedKeys.value = [...checkedKeys.value, ...changeIds];
        } else {
          checkedKeys.value = checkedKeys.value.filter((id) => {
            return !changeIds.includes(id);
          });
        }
      },
    },
  });

  const handleDelete = async () => {
    await props.onDelete?.(checkedKeys.value); // 通常是unlink
    await Api.toolsStorage.storageDelete({ ids: checkedKeys.value });
    checkedKeys.value = [];
    dynamicTableInstance?.reload();
  };
</script>
