<script lang="tsx" setup>
import { Button, Popconfirm } from 'ant-design-vue';
import { computed } from 'vue';

interface IProps {
  title: string;
  loading: boolean;
  columns: Record<string, any>[];
  list?: Record<string, any>[];
  tableSize?: 'small' | 'middle' | 'large';
  pagination?: Record<string, number>;
  componentProps?: Record<string, number>;
}

const props = withDefaults(defineProps<IProps>(), {
  list: () => [],
  pagination: () => ({}),
  componentProps: () => ({}),
  tableSize: 'small'
});

const { columns, title, list, pagination, componentProps } = toRefs(props);

const searchColumns = computed(() => {
  return columns.value.filter(item => item?.search);
});

const emit = defineEmits<{
  (e: 'setPage', data: Record<string, any>): void;
  (e: 'setParams', data: Record<string, any>): void;
}>();

const aTableRef = ref<any>();
</script>

<template>
  <div class="falling-table">
    <ACard v-if="searchColumns.length" :bordered="false" class="card-wrapper" title="搜索">
      <SearchBox :search-columns="searchColumns" @set-params="emit('setParams', $event)" />
    </ACard>
    <ACard :bordered="false" :title="title">
      <template #extra>
        <slot name="table-extra"></slot>
      </template>
      <ATable
        ref="aTableRef"
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="pagination"
        :size="tableSize"
        v-bind="componentProps"
        @change="emit('setPage', $event)"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.dataIndex === 'operation'">
            <div class="flex-center gap-8px">
              <div v-for="(item, key) in (column as any).actions" :key="key">
                <Popconfirm
                  v-if="item.delete"
                  title="确定要删除吗？"
                  @confirm="item?.onClick({ record, index, column })"
                >
                  <Button danger size="small">{{ item?.title }}</Button>
                </Popconfirm>
                <Button v-else size="small" type="primary" @click="item?.onClick({ record, index, column })">
                  {{ item?.title }}
                </Button>
              </div>
            </div>
          </template>
          <slot :column="column" :index="index" :record="record" :text="text" name="bodyCell"></slot>
        </template>
      </ATable>
    </ACard>
  </div>
</template>

<style scoped>
.falling-table {
  display: flex;
  flex-direction: column;
  gap: 15px;
}
</style>
